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
41 changes: 33 additions & 8 deletions design/file-helper.md
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,23 @@ helpers for independent project/source/managed boundaries.
existing leaves, including dangling links, before opening the destination.
This avoids target creation on backends that follow dangling links despite
exclusive-open flags. `O_EXCL` and `O_NOFOLLOW` (where available) remain in use;
the static preflight does not eliminate concurrent path-change races.
the policy-resolved parent hierarchy is anchored through creation. POSIX
opens each resolved directory without following links and creates the leaf
relative to the final directory descriptor. Search-only handles (`O_PATH`
or `O_SEARCH`, where available) avoid adding a directory-read permission
requirement; macOS uses the native `O_SEARCH` value when an older Python
build does not expose it. Traversal closes each previous parent after opening
its child, keeping the number of live directory descriptors independent of
path depth.
Windows pins the canonical root and every resolved parent with non-reparse
handles withholding delete sharing. Each anchored directory must permit
`FILE_LIST_DIRECTORY` and `FILE_READ_ATTRIBUTES` access. An ACL that permits
creating files but denies directory listing can therefore cause creation to
fail before opening the leaf.
Allowed contained parent links and trusted root aliases are resolved before
anchoring; they are not banned. Parents must already exist, and the supplied
mode remains filtered by the process umask. Unsupported anchoring primitives
fail explicitly rather than falling back to unanchored creation.
- `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically
create or update files with existing parents. Text variants also accept
`encoding="utf-8"`. Replacement files use the supplied mode; metadata and
Expand Down Expand Up @@ -209,13 +225,19 @@ entries, not reject a whole project for excluded/unrelated links.

Preflight detects static policy failures before recursive deletion or parent
creation. Atomic writes recheck the original path before replacement, and
deletion rechecks each accessed entry. Portable path checks are **not** a
race-free sandbox: another process can exchange parents or entries between
deletion rechecks each accessed entry. For all operations that still use
validated paths (reads, directory creation, atomic writes, non-atomic
overwrites, symlink creation, and deletion), portable path checks are **not**
a race-free sandbox: another process can exchange parents or entries between
checks and syscalls, and an I/O failure during mutation can leave partial
results. Protect against concurrent untrusted mutation separately; descriptor-
relative traversal or platform-specific mechanisms are future work, not a
claim of this API. The helper does not constrain subprocesses or third-party
code. Exclusive creation uses `O_EXCL` and `O_NOFOLLOW` where available.
results. Protect against concurrent untrusted mutation separately.
Exclusive file creation anchors its resolved parent hierarchy as described
above. On POSIX, renaming an opened directory does not redirect creation to
its replacement: creation stays with the opened directory, even if it is
renamed out of the root. This is not a guarantee of stable namespace membership
under concurrent renames, nor does parent anchoring make every leaf preflight
atomic with the subsequent open. The helper does not constrain subprocesses
or third-party code.

Existing safe-write mechanisms informed this helper, but existing shared
infrastructure warning/skip behavior and development-mode link creation are
Expand All @@ -229,4 +251,7 @@ path replacement.
Windows path classification and directory-mode reparse rejection have portable
regression tests. Native Windows path and junction tests also exist and are
skipped on other hosts; running the portable cases on macOS does not validate
Windows filesystem syscalls or junction behavior.
Windows filesystem syscalls or junction behavior. Exclusive-creation tests
cover parent replacement before anchoring and at the final open, along with
native Windows parent-handle pinning and portable handle-lifetime checks;
portable checks do not substitute for native Windows execution.
63 changes: 63 additions & 0 deletions src/specify_cli/_file_handles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""Private platform handles for confined filesystem operations."""

import errno
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path


@contextmanager
def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]:
"""Pin a non-reparse path by withholding Windows delete sharing."""
import ctypes
from ctypes import wintypes

class AttributeTagInfo(ctypes.Structure):
_fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)]

kernel = ctypes.WinDLL("kernel32", use_last_error=True)
create = kernel.CreateFileW
create.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
wintypes.HANDLE,
]
create.restype = wintypes.HANDLE
info = kernel.GetFileInformationByHandleEx
info.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
info.restype = wintypes.BOOL
close = kernel.CloseHandle
close.argtypes = [wintypes.HANDLE]
close.restype = wintypes.BOOL

# OPEN_REPARSE_POINT inspects the link itself; BACKUP_SEMANTICS permits
# directory handles. Holding every ancestor without FILE_SHARE_DELETE
# prevents a junction/symlink swap during path-based create/replace.
# Attribute-only handles bypass share checking: include FILE_LIST_DIRECTORY
# with FILE_READ_ATTRIBUTES so even an empty directory cannot be renamed.
handle = create(
str(path),
(0x80 | 0x1) if directory else 0x80000000,
0x3,
None,
3,
0x00200000 | 0x02000000,
None,
)
if handle == wintypes.HANDLE(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
try:
attributes = AttributeTagInfo()
if not info(handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes)):
raise ctypes.WinError(ctypes.get_last_error())
if attributes.attributes & 0x400:
raise OSError(errno.ELOOP, "Refusing a reparse-point filesystem path", str(path))
if bool(attributes.attributes & 0x10) != directory:
raise OSError(errno.EINVAL, "Unexpected filesystem object type", str(path))
yield handle
finally:
close(handle)
55 changes: 52 additions & 3 deletions src/specify_cli/file_helper.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""Scoped filesystem operations; see design/file-helper.md for the contract."""

from dataclasses import dataclass, field
from collections.abc import Iterator
from contextlib import ExitStack, contextmanager
import codecs
import errno
import os
from pathlib import Path, PurePath, PureWindowsPath
import stat
import sys
import tempfile
from typing import TypeVar

from specify_cli._file_handles import _windows_handle


_PathType = TypeVar("_PathType", bound=PurePath)

Expand Down Expand Up @@ -167,6 +172,41 @@ def read_bytes(self, path: Path | str) -> bytes:
def read_text(self, path: Path | str, *, encoding: str = "utf-8") -> str:
return self.read_bytes(path).decode(encoding)

@contextmanager
def _creation_directory(self, directory: Path) -> Iterator[int | Path]:
"""Anchor an already policy-resolved parent without following new links."""
parts = directory.relative_to(self._canonical_root).parts
if os.name == "nt":
with ExitStack() as stack:
current = self._canonical_root
stack.enter_context(_windows_handle(current, directory=True))
for part in parts:
current = current / part
stack.enter_context(_windows_handle(current, directory=True))
yield current
return

if not (
getattr(os, "O_NOFOLLOW", 0)
and getattr(os, "O_DIRECTORY", 0)
and os.open in os.supports_dir_fd
):
raise OSError(errno.ENOTSUP, "Anchored file creation is unsupported on this platform")
access = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0)
if not access:
# Darwin's O_SEARCH ABI is missing from some older Python builds.
access = (0x40000000 | os.O_DIRECTORY) if sys.platform == "darwin" else os.O_RDONLY
flags = access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0)
parent = os.open(self._canonical_root, flags)
try:
for part in parts:
child = os.open(part, flags, dir_fd=parent)
os.close(parent)
parent = child
yield parent
finally:
os.close(parent)

def create_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None:
"""Exclusively create a file; never overwrite an existing entry."""
destination = self._path(path, allow_missing=True, follow_leaf=False)
Expand All @@ -178,9 +218,18 @@ def create_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -
raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(destination))
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
flags |= getattr(os, "O_NOFOLLOW", 0)
fd = os.open(destination, flags, mode)
with os.fdopen(fd, "wb") as stream:
stream.write(content)
with self._creation_directory(destination.parent) as directory:
if isinstance(directory, Path):
fd = os.open(directory / destination.name, flags, mode)
else:
fd = os.open(destination.name, flags, mode, dir_fd=directory)
try:
stream = os.fdopen(fd, "wb")
except BaseException:
os.close(fd)
raise
with stream:
stream.write(content)

def create_text(
self, path: Path | str, content: str, *, encoding: str = "utf-8", mode: int = 0o644
Expand Down
59 changes: 1 addition & 58 deletions src/specify_cli/workflows/_catalog_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,64 +12,7 @@
from typing import Any
from uuid import uuid4


@contextmanager
def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]:
"""Pin a non-reparse path by withholding Windows delete sharing."""
import ctypes
from ctypes import wintypes

class AttributeTagInfo(ctypes.Structure):
_fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)]

kernel = ctypes.WinDLL("kernel32", use_last_error=True)
create = kernel.CreateFileW
create.argtypes = [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
wintypes.HANDLE,
]
create.restype = wintypes.HANDLE
info = kernel.GetFileInformationByHandleEx
info.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD]
info.restype = wintypes.BOOL
close = kernel.CloseHandle
close.argtypes = [wintypes.HANDLE]
close.restype = wintypes.BOOL

# OPEN_REPARSE_POINT inspects the link itself; BACKUP_SEMANTICS permits
# directory handles. Holding every ancestor without FILE_SHARE_DELETE
# prevents a junction/symlink swap during path-based create/replace.
# Attribute-only handles bypass share checking: include FILE_LIST_DIRECTORY
# with FILE_READ_ATTRIBUTES so even an empty directory cannot be renamed.
handle = create(
str(path),
(0x80 | 0x1) if directory else 0x80000000,
0x3,
None,
3,
0x00200000 | 0x02000000,
None,
)
if handle == wintypes.HANDLE(-1).value:
raise ctypes.WinError(ctypes.get_last_error())
try:
attributes = AttributeTagInfo()
if not info(handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes)):
raise ctypes.WinError(ctypes.get_last_error())
if attributes.attributes & 0x400:
raise OSError(
errno.ELOOP, "Refusing a reparse-point catalog cache path", str(path)
)
if bool(attributes.attributes & 0x10) != directory:
raise OSError(errno.EINVAL, "Unexpected catalog cache file type", str(path))
yield handle
finally:
close(handle)
from specify_cli._file_handles import _windows_handle


@contextmanager
Expand Down
59 changes: 59 additions & 0 deletions tests/test_file_handles.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Portable contract checks for the private Windows handle primitive."""

import ctypes
from ctypes import wintypes
from types import SimpleNamespace

import pytest

from specify_cli._file_handles import _windows_handle


@pytest.mark.parametrize("directory", [False, True])
def test_windows_handle_declares_complete_createfile_prototype(tmp_path, monkeypatch, directory):
closed = []

def create(*args):
assert create.argtypes == [
wintypes.LPCWSTR,
wintypes.DWORD,
wintypes.DWORD,
wintypes.LPVOID,
wintypes.DWORD,
wintypes.DWORD,
wintypes.HANDLE,
]
assert create.restype is wintypes.HANDLE
assert args == (
str(tmp_path),
(0x80 | 0x1) if directory else 0x80000000,
0x3,
None,
3,
0x00200000 | 0x02000000,
None,
)
return 123

def info(handle, info_class, buffer, size):
assert handle == 123 and info_class == 9
assert size == 2 * ctypes.sizeof(wintypes.DWORD)
attributes = ctypes.cast(buffer, ctypes.POINTER(wintypes.DWORD))
attributes[0] = 0x10 if directory else 0
return True

def close(handle):
closed.append(handle)
return True

def load_kernel(name, *, use_last_error):
assert name == "kernel32" and use_last_error
return SimpleNamespace(
CreateFileW=create, GetFileInformationByHandleEx=info, CloseHandle=close
)

monkeypatch.setattr(ctypes, "WinDLL", load_kernel, raising=False)
with _windows_handle(tmp_path, directory=directory) as handle:
assert handle == 123
assert closed == []
assert closed == [123]
Loading
Loading