Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,25 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-latest, windows-latest]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13", "3.14"]
exclude:
# Reduce matrix size: test all Python versions on Linux, min/max on others
- os: macos-latest
python-version: "3.10"
- os: macos-latest
python-version: "3.11"
- os: macos-latest
python-version: "3.12"
- os: macos-latest
python-version: "3.13"
- os: windows-latest
python-version: "3.10"
- os: windows-latest
python-version: "3.11"
- os: windows-latest
python-version: "3.12"
- os: windows-latest
python-version: "3.13"
steps:
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
- uses: dtolnay/rust-toolchain@4be9e76fd7c4901c61fb841f559994984270fce7 # stable
Expand Down
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Changelog

## 0.4.0 - 2026-11-10

- Add `FdJail` guarded file operations, policy options, capabilities, and attestations.
- Add guarded directory mutations on supported Linux platforms.
- Add `Jail.join_segments()` for independently validated path components.
- Upgrade the `path_jail` Rust core to 0.6.0.
- Upgrade PyO3 to 0.30.
- Add Python 3.14 to the tested and advertised version range.

8 changes: 4 additions & 4 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "path_jail_py"
version = "0.3.0"
version = "0.4.0"
edition = "2021"
license = "MIT OR Apache-2.0"
description = "Python bindings for path_jail - secure filesystem sandbox"
Expand All @@ -11,8 +11,8 @@ name = "path_jail"
crate-type = ["cdylib"]

[dependencies]
path_jail = "0.5"
pyo3 = { version = "0.24", features = ["extension-module", "abi3-py39"] }
path_jail = { version = "0.6", features = ["guard"] }
pyo3 = { version = "0.30", features = ["extension-module", "abi3-py39"] }

[package.metadata]
authors = ["Niki A. <[email protected]>"]
authors = ["Niki A. <[email protected]>"]
84 changes: 68 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ pip install path-jail
## Quick Start

```python
from path_jail import Jail, join
from path_jail import FdJail, Jail, join

# One-shot validation
safe_path = join("/var/uploads", "user/report.pdf")
Expand All @@ -28,6 +28,14 @@ jail = Jail("/var/uploads")
path1 = jail.join("2025/report.pdf")
path2 = jail.join("data.csv")

# Validate independent path components without string concatenation
path3 = jail.join_segments("users", user_id, filename)

# Open untrusted paths through a pinned directory descriptor (Unix)
guard = FdJail("/var/uploads")
with guard.open("user/report.pdf", "rb", require_regular_file=True) as file:
contents = file.read()

# These raise ValueError:
jail.join("../../etc/passwd") # Path traversal
jail.join("/etc/passwd") # Absolute path
Expand Down Expand Up @@ -82,6 +90,54 @@ Join a relative path to the jail root. Returns the absolute path.
safe = jail.join("subdir/file.txt")
```

### `Jail.join_segments(*parts) -> str`

Join separately validated path components. Empty components are skipped;
separators, `..`, and null bytes are rejected in every non-empty component.

```python
safe = jail.join_segments("users", user_id, filename)
```

### `FdJail(root)`

On Unix, `FdJail` opens files relative to a pinned jail root and returns normal
Python file objects. Linux 5.6+ on x86_64 and aarch64 uses `openat2` for atomic,
kernel-enforced resolution. macOS and other Unix platforms use an `O_NOFOLLOW`
fallback; check `capabilities().toctou_safe` when atomicity is required.

```python
from path_jail import FdJail

guard = FdJail("/var/uploads")

with guard.open(
"user/report.pdf",
"rb",
require_regular_file=True,
reject_hard_links=True,
) as file:
contents = file.read()

with guard.create("user/new.bin") as file:
file.write(b"new content")

file, attestation = guard.open_with_attestation("user/report.pdf", "rb")
with file:
contents = file.read()
print(attestation.toctou_safe, attestation.file_inode)
```

`open()` supports standard `r`, `w`, `a`, and `x` modes with optional `b`, `t`,
and `+`. Policy options are `require_regular_file`, `reject_hard_links`,
`no_symlinks`, and `no_xdev`. The latter two require a backend whose matching
capability is true.

Guarded `create_dir`, `remove_file`, `remove_dir`, and `rename` are available
when `capabilities().directory_operations` is true. Unsupported guarded
operations raise `NotImplementedError`. `FdJail` itself is unavailable on
Windows and its constructor raises `NotImplementedError` there.

### `Jail.contains(path) -> str`

Verify an existing absolute path is inside the jail.
Expand Down Expand Up @@ -167,7 +223,7 @@ jail = Jail(UPLOAD_DIR)
def save_upload(user_id: str, filename: str, data: bytes) -> str:
"""Safely save an uploaded file."""
# Validate and build path
safe_path = jail.join(f"{user_id}/{filename}")
safe_path = jail.join_segments(user_id, filename)

# Create parent directories
Path(safe_path).parent.mkdir(parents=True, exist_ok=True)
Expand Down Expand Up @@ -276,6 +332,7 @@ ln /etc/passwd /var/uploads/innocent.txt
```

**Mitigations:**
- Use `FdJail.open(..., reject_hard_links=True)` for untrusted files
- Use a separate partition for the jail (hard links cannot cross partitions)
- Don't give untrusted users shell access
- Use container isolation
Expand All @@ -291,19 +348,13 @@ open(safe_path) # Escapes!
```

**Mitigations:**
- Open with `O_NOFOLLOW` so a symlink swapped in at the final component is
refused (intermediate directories are still unprotected):
```python
import os

fd = os.open(safe_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o644)
with os.fdopen(fd, "wb") as f:
f.write(data)
```
- Use container/chroot isolation for strong guarantees
- The Rust crate's `guard` feature makes validate-and-open a single
kernel-checked step on Linux x86_64/aarch64 with kernel 5.6+; it is not
exposed in these bindings yet.
- Use `FdJail.open()` so validation and opening are performed by the guarded
backend. On Linux 5.6+ x86_64/aarch64 this is a single kernel-checked step.
- Check `FdJail.capabilities().toctou_safe` or the returned attestation before
relying on atomic path resolution. Other Unix platforms use a fallback that
protects the final component but is not fully TOCTOU-safe.
- Use container/chroot isolation when the active backend does not meet the
threat model.

#### Windows Reserved Device Names

Expand Down Expand Up @@ -408,7 +459,8 @@ path-jail crosses the Python/Rust boundary once per call. The tight syscall loop

## Thread Safety

`Jail` instances are thread-safe and can be shared across threads without locks.
`Jail` and `FdJail` instances are thread-safe and can be shared across threads
without locks.

## Development

Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "maturin"

[project]
name = "path-jail"
version = "0.3.0"
version = "0.4.0"
description = "Secure filesystem sandbox. Restricts paths to a root directory, preventing traversal attacks."
readme = "README.md"
license = { text = "MIT OR Apache-2.0" }
Expand All @@ -21,6 +21,7 @@ classifiers = [
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Programming Language :: Rust",
"Topic :: Security",
"Typing :: Typed",
Expand Down
4 changes: 2 additions & 2 deletions python/path_jail/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Re-export from native module
from .path_jail import Jail, join
from .path_jail import Attestation, FdJail, GuardCapabilities, Jail, join

__all__ = ["Jail", "join"]
__all__ = ["Attestation", "FdJail", "GuardCapabilities", "Jail", "join"]
from importlib.metadata import version as _version

__version__ = _version("path-jail")
84 changes: 84 additions & 0 deletions python/path_jail/__init__.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Type stubs for path_jail."""

from os import PathLike
from typing import IO, Any, BinaryIO

__version__: str

Expand Down Expand Up @@ -56,6 +57,13 @@ class Jail:
"""
...

def join_segments(self, *parts: _PathLike) -> str:
"""Join separately validated path components beneath the jail root.

Empty parts are skipped. Separators, ``..``, and null bytes are rejected.
"""
...

def contains(self, path: _PathLike) -> str:
"""Verify an absolute path is inside the jail.

Expand Down Expand Up @@ -90,6 +98,82 @@ class Jail:
def __repr__(self) -> str: ...
def __str__(self) -> str: ...

class GuardCapabilities:
"""Guarantees and operations provided by the active guarded backend."""

@property
def toctou_safe(self) -> bool: ...
@property
def directory_operations(self) -> bool: ...
@property
def no_symlinks(self) -> bool: ...
@property
def no_xdev(self) -> bool: ...

class Attestation:
"""Metadata captured from the exact handle returned by a guarded open."""

@property
def jail_root(self) -> str: ...
@property
def opened_path(self) -> str: ...
@property
def root_inode(self) -> int: ...
@property
def file_inode(self) -> int: ...
@property
def device(self) -> int: ...
@property
def nlink(self) -> int: ...
@property
def toctou_safe(self) -> bool: ...
@property
def opened_at_ns(self) -> int: ...
@property
def signature(self) -> bytes | None: ...

class FdJail:
"""Descriptor-based jail for guarded file operations on Unix."""

def __init__(self, root: _PathLike) -> None: ...
@property
def root(self) -> str: ...
def capabilities(self) -> GuardCapabilities: ...
def open(
self,
path: _PathLike,
mode: str = "r",
*,
require_regular_file: bool = False,
reject_hard_links: bool = False,
no_symlinks: bool = False,
no_xdev: bool = False,
) -> IO[Any]: ...
def open_with_attestation(
self,
path: _PathLike,
mode: str = "r",
*,
require_regular_file: bool = False,
reject_hard_links: bool = False,
no_symlinks: bool = False,
no_xdev: bool = False,
) -> tuple[IO[Any], Attestation]: ...
def create(
self,
path: _PathLike,
*,
require_regular_file: bool = False,
reject_hard_links: bool = False,
no_symlinks: bool = False,
no_xdev: bool = False,
) -> BinaryIO: ...
def create_dir(self, path: _PathLike) -> None: ...
def remove_file(self, path: _PathLike) -> None: ...
def remove_dir(self, path: _PathLike) -> None: ...
def rename(self, source: _PathLike, destination: _PathLike) -> None: ...
def __repr__(self) -> str: ...

def join(root: _PathLike, path: _PathLike) -> str:
"""One-shot path validation.

Expand Down
Loading
Loading