Skip to content
Closed
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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

All notable changes to `moca-reader`. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).

## Unreleased: 0.8.0

### Fixed (directory source)

- **The open file must be the one listed.** The directory source records each file's device and inode when it lists
the package, and a read refuses a handle that is another file. On POSIX each step was already opened without
following a link; the step-by-step check used on Windows (no `O_NOFOLLOW`) checked the path and then opened it by
path, so a folder swapped for a link in between was followed. Test in `tests/test_malformed_input.py`.

## [0.7.0] - 2026-11-15

For moca-spec 0.7.0 ([moca-spec#5](https://github.com/openmoca/moca-spec/issues/5) and
Expand Down
30 changes: 21 additions & 9 deletions src/moca_reader/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ def directory_source(root: str | os.PathLike[str], limits: dict[str, int] | None
root_dir = os.fspath(root)
lim = {**DEFAULT_LIMITS, **(limits or {})}
read_bytes = [0]
# Each listed file's device and inode: a read must open that same file (contract §3).
identities: dict[str, tuple[int, int]] = {}

def walk() -> list[SourceEntry]:
out: list[SourceEntry] = []
Expand All @@ -130,6 +132,7 @@ def visit(abs_dir: str, rel_dir: str) -> None:
visit(abs_path, rel)
elif stat.S_ISREG(st.st_mode):
out.append(SourceEntry(rel, "file", st.st_size))
identities[rel] = (st.st_dev, st.st_ino)
else:
out.append(SourceEntry(rel, "other"))

Expand All @@ -146,7 +149,7 @@ def visit(abs_dir: str, rel_dir: str) -> None:
def read(path: str) -> bytes:
# Contract §3: never follow a link, including one swapped in after listing, at any step of the path. At
# most one byte past the limit is read.
data = _read_no_follow(root_dir, path.split("/"), lim["maxBytes"] - read_bytes[0] + 1)
data = _read_no_follow(root_dir, path.split("/"), lim["maxBytes"] - read_bytes[0] + 1, identities.get(path))
read_bytes[0] += len(data)
if read_bytes[0] > lim["maxBytes"]:
raise TargetError("T003_ARCHIVE_REJECTED", f"directory exceeds the {lim['maxBytes']}-byte limit")
Expand All @@ -165,17 +168,28 @@ def _is_link(st: os.stat_result) -> bool:
return stat.S_ISLNK(st.st_mode) or getattr(st, "st_reparse_tag", 0) in _WINDOWS_LINK_TAGS


def _read_no_follow(root: str, parts: list[str], most: int) -> bytes:
def _check_opened(st: os.stat_result, parts: list[str], listed: tuple[int, int] | None) -> None:
"""The open file must be a regular file and, when it was listed, the same file (device and inode), however the
path led to it."""
if not stat.S_ISREG(st.st_mode):
raise OSError(f"{'/'.join(parts)} is no longer a regular file")
if listed is not None and (st.st_dev, st.st_ino) != listed:
raise OSError(f"{'/'.join(parts)} is not the file that was listed")


def _read_no_follow(root: str, parts: list[str], most: int, listed: tuple[int, int] | None = None) -> bytes:
"""The bytes of a regular file under ``root`` (the host's), never through a symbolic link at any step.

Where the platform has them (POSIX), each directory and the file are opened relative to the one before with
O_NOFOLLOW, and what was opened is checked, not the path. Elsewhere (Windows has neither O_NOFOLLOW nor
O_DIRECTORY), each step of the path is checked with lstat, links and junctions refused, before the file is read.
Either way the open file must be the one listed (``listed``, its device and inode), so a link swapped in between
the checks and the open leads to another file and is refused.
"""
if sys.platform == "win32":
return _read_checking_each_step(root, parts, most)
return _read_checking_each_step(root, parts, most, listed)
if os.open not in os.supports_dir_fd:
return _read_checking_each_step(root, parts, most)
return _read_checking_each_step(root, parts, most, listed)
directory = os.open(root, os.O_RDONLY | os.O_DIRECTORY)
try:
for part in parts[:-1]:
Expand All @@ -188,21 +202,19 @@ def _read_no_follow(root: str, parts: list[str], most: int) -> bytes:
os.close(directory)
with os.fdopen(fd, "rb") as f:
st = os.fstat(f.fileno())
if not stat.S_ISREG(st.st_mode):
raise OSError(f"{'/'.join(parts)} is no longer a regular file")
_check_opened(st, parts, listed)
return _read_bounded(f, st.st_size, most)


def _read_checking_each_step(root: str, parts: list[str], most: int) -> bytes:
def _read_checking_each_step(root: str, parts: list[str], most: int, listed: tuple[int, int] | None = None) -> bytes:
here = root
for part in parts:
here = os.path.join(here, part)
if _is_link(os.lstat(here)):
raise OSError(f"{'/'.join(parts)} has a symbolic link or junction in its path")
with open(here, "rb") as f:
st = os.fstat(f.fileno())
if not stat.S_ISREG(st.st_mode):
raise OSError(f"{'/'.join(parts)} is no longer a regular file")
_check_opened(st, parts, listed)
return _read_bounded(f, st.st_size, most)


Expand Down
28 changes: 28 additions & 0 deletions tests/test_malformed_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from moca_reader import Library, bind_sidecar, read_package
from moca_reader import reader as reader_module
from moca_reader import source as source_module
from moca_reader._js import MAX_NESTING, json_loads, json_nesting_scan, parse_date
from moca_reader.diagnostics import Diagnostics
from moca_reader.evidence_text import html_text
Expand Down Expand Up @@ -244,6 +245,33 @@ def test_the_step_by_step_check_used_on_windows_refuses_links(tmp_path: Path) ->
_read_checking_each_step(str(root), ["content", "a.md"], 1 << 20)


@pytest.mark.skipif(not hasattr(os, "symlink") or os.name == "nt", reason="needs POSIX symbolic links")
def test_the_step_by_step_check_refuses_a_folder_swapped_after_the_checks(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
# Windows has no O_NOFOLLOW, so each step is checked and then the file is opened by path. A folder swapped for a
# link between the last check and the open leads to another file; the read must open the file that was listed.
root = Path(package(tmp_path / "p", {"moca.json": json.dumps(MANIFEST), "content/a.md": NODE}))
elsewhere = Path(package(tmp_path / "elsewhere", {"a.md": "host file"}))
source = directory_source(root)
assert [e.path for e in source.list()] == ["content/a.md", "moca.json"]
real_open = open

def swap_then_open(path: str, *args: object, **kwargs: object) -> object:
(root / "content" / "a.md").unlink()
(root / "content").rmdir()
(root / "content").symlink_to(elsewhere, target_is_directory=True)
return real_open(path, *args, **kwargs) # type: ignore[call-overload]

monkeypatch.setattr(source_module, "sys", type("Win", (), {"platform": "win32"}))
monkeypatch.setattr(source_module, "open", swap_then_open, raising=False)
try:
data = source.read("content/a.md")
except OSError:
return # refused: correct
assert data != b"host file", "read a file through a folder swapped for a link"


TTL = "@prefix ex: <https://example.com/> .\n"


Expand Down
Loading