path-containment
path-containment

how path-containment fits in

Install

consolepip install path-containment

API

pythonfrom path_containment import (
    UnsafePathError, is_within, safe_join, safe_member_name, safe_target, sanitize_filename,
)

is_within("/srv/uploads", "/srv/uploads/a/b.txt")    # True
is_within("/srv/uploads", "/srv/other")              # False

safe_join("/srv/uploads", "reports", "q1.pdf")       # /srv/uploads/reports/q1.pdf
safe_join("/srv/uploads", "../etc/passwd")           # raises UnsafePathError

safe_member_name("./docs\\a.txt")                    # "docs/a.txt"
safe_member_name("/etc/passwd")                      # raises
safe_target("/srv/uploads", "..\\..\\win.ini")       # raises

sanitize_filename('a/b:c?.txt')                      # "a_b_c_.txt"
sanitize_filename("CON")                             # "_CON"
sanitize_filename("name.txt...")                     # "name.txt"

Every refusal raises UnsafePathError, a ValueError, with a message that says what was wrong with which component.

Why not os.path.join

os.path.join("uploads", "../../etc/passwd") returns a path outside uploads, and Path.resolve() alone only tells you where it lands — after the fact. On Windows ntpath.isabs("/etc/passwd") is False (there is no drive), so a check that relies on isabs alone lets that through. Both cases are covered here, and the resolved result is compared against the resolved base, which also catches a symlink that points outside.

Behaviour worth knowing

absolute paths, drive letters, control characters and any .. component.

characters, trims trailing dots and spaces, prefixes reserved Windows device names (CON, NUL, COM1…) and truncates to max_length without leaving a trailing dot.

Development

consolepython -m venv .venv
.venv/bin/pip install -e ".[test]"
.venv/bin/pytest

The suite covers every line of the package (pytest --cov --cov-branch), and the examples in the docstrings run as tests through --doctest-modules.

License

MIT.

Other libraries here

One problem each, standard library only, no runtime dependencies.