Safe Path Join Against Directory Traversal

Resolve user-supplied relative paths under a fixed root, reject absolute or traversal inputs, and verify the final path stays inside.

PythonSecurity Boundaries

Code

pythonsnippet
38 lines
from pathlib import Path


class UnsafePathError(ValueError):
    pass


def safe_join(root: str | Path, user_path: str) -> Path:
    if not isinstance(user_path, str) or not user_path.strip():
        raise UnsafePathError("path must be a non-empty string")
    if "\x00" in user_path:
        raise UnsafePathError("path must not contain NUL bytes")

    candidate = Path(user_path)
    if candidate.is_absolute() or candidate.drive:
        raise UnsafePathError("absolute paths are not allowed")

    base = Path(root).resolve()
    target = (base / candidate).resolve()
    try:
        target.relative_to(base)
    except ValueError as error:
        raise UnsafePathError(f"path escapes root: {user_path!r}") from error
    return target


def main() -> None:
    root = Path.cwd() / "public"
    for value in ["reports/2026/q1.csv", "../secrets.env", "/etc/passwd", "a/../../b"]:
        try:
            print(value, "->", safe_join(root, value))
        except UnsafePathError as error:
            print(value, "-> rejected:", error)


if __name__ == "__main__":
    main()

Output

Captured from a sandboxed run of this snippet in the build pipeline.

reports/2026/q1.csv -> C:\Users\guangming\AppData\Local\Temp\devex-run-ljx6Wf\public\reports\2026\q1.csv
../secrets.env -> rejected: path escapes root: '../secrets.env'
/etc/passwd -> rejected: path escapes root: '/etc/passwd'
a/../../b -> rejected: path escapes root: 'a/../../b'

How the snippet works

Safe Path Join Against Directory Traversal is built around the class UnsafePathError and the functions safe_join and main.

The one repetition in this snippet is the loop for value in ["reports/2026/q1.csv", "../secrets.env", "/etc/passwd", "a/../../b"]. UnsafePathError appears at a raise inside an except handler — it fires only while that failure type is already being handled.

What to watch for

  • The guard not isinstance(user_path, str) or not user_path.strip() short-circuits the flow with an early raise when its condition holds.

Applying it

Signature: def safe_join(root: str | Path, user_path: str) -> Path

Launch the file; main takes over and steps through safe_join.

Statements that matter

def main() -> None:
    root = Path.cwd() / "public"
    for value in ["reports/2026/q1.csv", "../secrets.env", "/etc/passwd", "a/../../b"]:
        try:
            print(value, "->", safe_join(root, value))
        except UnsafePathError as error:
            print(value, "-> rejected:", error)
except ValueError as error:
    raise UnsafePathError(f"path escapes root: {user_path!r}") from error

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `UnsafePathError` fires only while that failure type is already being handled, not on its own trigger.
How do you run Safe Path Join Against Directory Traversal?
The runtime alone is enough: execute the file as a complete program.