Skip to main content

safejoin

Path-traversal-safe joining of a trusted base directory with untrusted relative parts. Typed, zero dependencies, tested on the real filesystem with real symlinks and Windows junctions.

Install

pip install safejoin

Usage

from pathlib import Path

from safejoin import UnsafePathError, safe_join, safe_open

base = Path("/srv/uploads")

# A normal request resolves to a path inside the base.
path = safe_join(base, "images", "avatar.png")

# Anything that would escape the base is refused, and the error names the part.
try:
    safe_join(base, "images", "../../etc/passwd")
except UnsafePathError as exc:
    print(exc.reason, exc.part)  # escape ../../etc/passwd

# Open without a window for a symlink swapped in after the check.
with safe_open(base, "images", "avatar.png", mode="rb") as handle:
    data = handle.read()

Archives:

import zipfile

from safejoin import safe_member_path

with zipfile.ZipFile("upload.zip") as archive:
    for info in archive.infolist():
        target = safe_member_path("/srv/extract", info.filename)  # raises on zip slip

Command line:

safejoin check /srv/uploads images/cat.png   # prints the safe path, exit 0
safejoin check /srv/uploads ../etc/passwd    # message on stderr, exit 1
safejoin scan upload.zip                     # audits every member and link
safejoin --help                              # every option, with examples

API

Name What it does
safe_join(base, *parts, resolve=True, symlinks="allow_inside", windows_rules=None) Join and return the safe absolute path, or raise
is_within(base, target, *, resolve=True) True when target is base or lies below it
check_part(part, *, windows_rules=None) Validate one untrusted part without the filesystem
safe_open(base, *parts, mode="r", ...) Open a regular file inside base with no link swap window
member_parts(name) Validate a zip or tar member name, return its components
safe_member_path(base, name) Where a member may be extracted, or raise
link_target_parts(member, target, *, hard=False) Validate a tar link target inside the archive
safe_link_target(base, member, target, *, hard=False) Check a link target against what is on disk
UnsafePathError Base error (a ValueError) with .part and .reason
AbsolutePartError, TraversalError, InvalidPartError, SymlinkError Its typed subclasses
RESERVED_NAMES The Windows device names that are refused

Threat model in one page

safejoin guards code that takes a trusted base directory and a path fragment from an untrusted source (a URL, a form field, a member name inside a zip or tar archive) and joins them. The full statement, per mode, is in GUIDE.md.

Refused, with the test that pins it:

  • .. that climbs above the base, even if later parts come back down (tests/test_join.py, tests/test_corpus.py).
  • Absolute and rooted parts: /etc, \Windows, C:\x, drive-relative C:x, UNC \\host\share and //host/share, device paths \\?\ and \\.\ (tests/test_rules.py).
  • NUL bytes, in every mode and on every platform.
  • On Windows by default, and anywhere with windows_rules=True: device names (CON, nul.txt, COM1, COM with a superscript digit, CONIN$), alternate data streams (file.txt:stream, dir::$INDEX_ALLOCATION), names ending in a dot or space, characters Windows forbids, and look-alikes that compatibility normalisation or best-fit code page conversion turn into /, \ or :. The best-fit list is checked against the real WideCharToMultiByte across 16 code pages (test_every_best_fit_separator_is_refused).
  • Symlinks and junctions that lead outside the base (resolved mode), and every link below the base with symlinks="deny". Real links are created in a temp directory; junctions with _winapi.CreateJunction, symlinks with os.symlink (skipped with a reason where the OS forbids them).
  • On Windows, links below the base are followed with readlink before resolving, so a link to a named pipe or a remote share is refused without being opened (tests/test_prescreen.py).
  • A resolution that stops half way (a loop, a component that cannot be inspected): the resolved result is walked again and any link still present is refused.

Every accepted result in the contract corpus (over 2,000 hostile inputs, four modes) and in seeded fuzzing is created on disk and checked to land inside the base with nothing written outside.

Not covered, by design:

  • URL decoding. safejoin never decodes %2e%2e/. Decode exactly once, then call it. A double-encoded input decoded twice is a caller bug.
  • Races between the check and later use of a returned path (TOCTOU). Use safe_open, which closes that window on POSIX with O_NOFOLLOW and on Windows by checking the final path of the opened handle. See the guide for what remains.
  • Hard links. A hard link is indistinguishable from an ordinary file by path. safe_open refuses to write to a file with several links; reads cannot detect them.
  • OEM code pages other than 437 and 850 for best-fit look-alikes; see the guide.

Background

License

MIT. See LICENSE.

Metadata

Release files for safejoin 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for safejoin 0.2.0
File Size Uploaded Provenance Actions
safejoin-0.2.0.tar.gz 39.7 kB Without provenance Details for safejoin-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for safejoin 0.2.0
File Interpreter ABI Platform Actions
safejoin-0.2.0-py3-none-any.whl Python 3 none any Details for safejoin-0.2.0-py3-none-any.whl

Total release size: 63.6 kB

Release files / safejoin-0.2.0.tar.gz

Download URL safejoin-0.2.0.tar.gz
Size 39.7 kB
Tags Source
SHA-256 checksum
How to use checksums
bad296ffa348239829dc37ba90a126b7880d2c771dd78d018259bc381a490311
BLAKE2b-256 checksum
How to use checksums
61bc968f74d3326984148b89d6a89edccc5f28f719ee61be347f776990f22cf6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Release files / safejoin-0.2.0-py3-none-any.whl

Download URL safejoin-0.2.0-py3-none-any.whl
Size 23.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6fcf4d439de7dbf8bc48ae1000bbfd0ce57a15cf653b5dbde0601d84c2359b1c
BLAKE2b-256 checksum
How to use checksums
02bd6dbb8399a07f32221429a53b7d7e8073b2857d93e4889bdad8f24b7f33ca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.2

Security for safejoin 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page