From 073af65a7af25323d87a82a3bcab7b51f5ba4cac Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 17:26:25 +0000 Subject: [PATCH 01/18] feat(file-helper): add public stat, in-place byte rewrite and owner-only create Integrations that rewrite a user's file in place, or keep an owner-only backup beside it, had to reach into FileHelper's private resolution and anchored-descriptor methods. Add public operations for both, plus stat for the identity check a rewrite needs: - stat(path): metadata of the policy-resolved entry - open_rewrite(path): anchored, non-truncating, non-creating binary write descriptor on an existing regular file - create_private_bytes(path, content): exclusive, flushed creation that only the current user can open (0o600 on POSIX, an owner-only protected DACL set at creation on Windows), removing only its own partial file Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WirNuLtfqtefs4BFj5Y --- design/file-helper.md | 30 ++ src/specify_cli/_file_handles.py | 157 ++++++++- src/specify_cli/file_helper.py | 118 ++++++- tests/test_file_helper_overwrite.py | 11 +- tests/test_file_helper_rewrite.py | 505 ++++++++++++++++++++++++++++ 5 files changed, 808 insertions(+), 13 deletions(-) create mode 100644 tests/test_file_helper_rewrite.py diff --git a/design/file-helper.md b/design/file-helper.md index 15c600d7aa..6deba1cb34 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -244,6 +244,11 @@ descriptor-relative or change their documented concurrency limitations. with cleanup details attached as a note. The yielded path uses the same spelling rule as `iterdir`; cleanup uses the resolved staging location. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. +- `stat(path)` returns the metadata of an existing entry after the normal policy + walk: allowed contained links, including a leaf link, are resolved, and the + resolved entry itself is not followed. Missing entries raise + `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that + act on the result must re-check identity on the descriptor they act through. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. @@ -266,6 +271,21 @@ descriptor-relative or change their documented concurrency limitations. 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. +- `create_private_bytes(path, content)` exclusively creates a file only the + current user can open, with existing parents, and flushes it before + returning. It shares `create_bytes`'s policy walk, no-follow `lstat` + preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` + relative to the anchored parent, writes and `fsync`s through that one + descriptor, then flushes the parent best effort through a readable descriptor + opened from the anchor (search-only and `O_PATH` anchors reject `fsync`); a + parent that cannot be flushed does not fail the call. Windows creates the leaf + with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security + descriptor naming the current user as owner with a protected DACL granting + only that user full access, so the content is never readable under an + inherited ACL. A failure after creation removes only the file this call + created: POSIX unlinks the name only while it still has the created file's + identity, and Windows marks the open handle for deletion. If that removal + fails, the original exception carries a note naming the file. - `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 @@ -306,6 +326,16 @@ descriptor-relative or change their documented concurrency limitations. Windows creation also honors the CRT process mask: masking the owner-write bit creates a read-only file, matching native text creation, without changing the attributes of an existing file. +- `open_rewrite(path)` is a context manager yielding a binary, writable + descriptor on an existing regular file at offset 0, for in-place byte + rewrites that must keep the file's identity, owner, mode, ACL and hard links. + It uses `overwrite_text`'s anchored, non-truncating open, but never creates: + POSIX omits `O_CREAT` and Windows does not fall back to creation, so a leaf + removed after resolution raises `FileNotFoundError`. The opened file type is + checked with `fstat` before the descriptor is yielded, and the descriptor is + closed on exit. Writing, truncating, flushing and any rollback belong to the + caller; nothing is written or truncated by the helper. There is no newline + translation on either platform. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. Recursive enumeration and each removal use anchored diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 9dceb5a80e..1f655b3635 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -3,6 +3,7 @@ from collections.abc import Iterator from contextlib import contextmanager import errno +import functools import os import secrets import stat @@ -462,11 +463,13 @@ def windows_read_fd(handle: int) -> Iterator[int]: @contextmanager -def _windows_overwrite_fd(path: Path) -> Iterator[int]: +def _windows_overwrite_fd(path: Path, *, create: bool = True) -> Iterator[int]: """Open/create without following a new leaf or changing the CRT mask.""" try: handle = _open_windows_handle(path, directory=False, overwrite=True) except FileNotFoundError: + if not create: + raise attributes = _windows_creation_attributes() handle = _open_windows_handle( path, directory=False, overwrite=True, create_attributes=attributes @@ -500,3 +503,155 @@ def _windows_creation_attributes() -> int: os.close(fd) os.unlink(probe) return 0x1 if readonly else 0 + + +_GENERIC_WRITE = 0x40000000 +_DELETE = 0x00010000 +_CREATE_NEW = 1 +_FILE_ATTRIBUTE_NORMAL = 0x80 +_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 +_FILE_DISPOSITION_INFO = 4 +_TOKEN_QUERY = 0x8 +_TOKEN_USER = 1 +_ERROR_INSUFFICIENT_BUFFER = 122 +_SDDL_REVISION_1 = 1 + + +def _windows_create_private_fd(path: Path) -> int: + """Create ``path`` owned by, and only accessible to, the current user. + + The owner and protected access-control list are set by the call that + creates the file, and nothing is shared until it closes, so the content is + never readable under an inherited list. Returns a binary CRT descriptor. + """ + import ctypes + import msvcrt + from ctypes import wintypes + + kernel, advapi, attributes_type = _windows_security_api() + descriptor = ctypes.c_void_p() + if not advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( + _windows_owner_only_sddl(), _SDDL_REVISION_1, ctypes.byref(descriptor), None, + ): + raise ctypes.WinError(ctypes.get_last_error()) + try: + attributes = attributes_type(ctypes.sizeof(attributes_type), descriptor, False) + # DELETE lets a later failure remove the file through its own handle. + handle = kernel.CreateFileW( + str(path), _GENERIC_WRITE | _DELETE, 0, ctypes.byref(attributes), _CREATE_NEW, + _FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT, None, + ) + if handle is None or handle == wintypes.HANDLE(-1).value: + raise ctypes.WinError(ctypes.get_last_error()) + finally: + kernel.LocalFree(descriptor) + try: + return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) + except BaseException as error: + # No descriptor reaches the caller, so remove the empty file here. With + # no sharing, nothing else could have opened, renamed or replaced it. + class FileDispositionInfo(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + try: + disposition = FileDispositionInfo(True) + if not kernel.SetFileInformationByHandle( + handle, _FILE_DISPOSITION_INFO, ctypes.byref(disposition), + ctypes.sizeof(disposition), + ): + raise ctypes.WinError(ctypes.get_last_error()) + except Exception as cleanup_error: + error.add_note(f"Could not remove empty file {path}: {cleanup_error}") + finally: + kernel.CloseHandle(handle) + raise + + +def _windows_owner_only_sddl() -> str: + """The security descriptor, as SDDL, private files are created with.""" + sid = _windows_current_user_sid() + return f"O:{sid}D:P(A;;FA;;;{sid})" + + +@functools.lru_cache(maxsize=1) +def _windows_current_user_sid() -> str: + import ctypes + from ctypes import wintypes + + kernel, advapi, _ = _windows_security_api() + token = wintypes.HANDLE() + if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + size = wintypes.DWORD() + if not advapi.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(size)): + code = ctypes.get_last_error() + if code != _ERROR_INSUFFICIENT_BUFFER: + raise ctypes.WinError(code) + buffer = ctypes.create_string_buffer(size.value) + if not advapi.GetTokenInformation( + token, _TOKEN_USER, buffer, size, ctypes.byref(size), + ): + raise ctypes.WinError(ctypes.get_last_error()) + # TOKEN_USER starts with SID_AND_ATTRIBUTES, whose first field is the SID. + sid = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0] + text = wintypes.LPWSTR() + if not advapi.ConvertSidToStringSidW(sid, ctypes.byref(text)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + value = text.value + finally: + kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) + finally: + kernel.CloseHandle(token) + if not value or not value.startswith("S-"): + raise OSError(errno.EINVAL, "Could not read the current user's security identifier") + return value + + +@functools.lru_cache(maxsize=1) +def _windows_security_api(): + """kernel32 and advapi32 with private prototypes, and SECURITY_ATTRIBUTES.""" + import ctypes + from ctypes import wintypes + + class SecurityAttributes(ctypes.Structure): + _fields_ = [ + ("nLength", wintypes.DWORD), + ("lpSecurityDescriptor", ctypes.c_void_p), + ("bInheritHandle", wintypes.BOOL), + ] + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + advapi = ctypes.WinDLL("advapi32", use_last_error=True) + kernel.LocalFree.argtypes = [ctypes.c_void_p] + kernel.LocalFree.restype = ctypes.c_void_p + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + kernel.CloseHandle.restype = wintypes.BOOL + kernel.GetCurrentProcess.argtypes = [] + kernel.GetCurrentProcess.restype = wintypes.HANDLE + kernel.CreateFileW.argtypes = [ + wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, + ctypes.POINTER(SecurityAttributes), wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE, + ] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.SetFileInformationByHandle.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, + ] + kernel.SetFileInformationByHandle.restype = wintypes.BOOL + advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [ + wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), wintypes.LPVOID, + ] + advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL + advapi.OpenProcessToken.argtypes = [ + wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE), + ] + advapi.OpenProcessToken.restype = wintypes.BOOL + advapi.GetTokenInformation.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), + ] + advapi.GetTokenInformation.restype = wintypes.BOOL + advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)] + advapi.ConvertSidToStringSidW.restype = wintypes.BOOL + return kernel, advapi, SecurityAttributes diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index c7b393fb58..74b6906dd9 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -16,9 +16,10 @@ from weakref import finalize from specify_cli._file_handles import ( - _WindowsFileIdentity, _windows_delete, _windows_directory_names, _windows_entry, - _windows_file_id, _windows_handle, _windows_mode, _windows_overwrite_fd, - _windows_readlink, _windows_stat, rename_noreplace, windows_read_fd, + _WindowsFileIdentity, _windows_create_private_fd, _windows_delete, + _windows_directory_names, _windows_entry, _windows_file_id, _windows_handle, + _windows_mode, _windows_overwrite_fd, _windows_readlink, _windows_stat, + rename_noreplace, windows_read_fd, ) @@ -33,6 +34,15 @@ _POSIX_OPEN = os.open +def _write_all(fd: int, content: bytes) -> None: + view = memoryview(content) + while view: + count = os.write(fd, view) + if count == 0: + raise OSError(errno.EIO, "Write made no progress") + view = view[count:] + + def _strip_extended_length_prefix(path: _PathType) -> _PathType: """Normalize Windows extended drive/UNC spellings for comparison only.""" raw = str(path) @@ -377,6 +387,10 @@ def _require_directory(path: Path) -> None: if not stat.S_ISDIR(path.stat().st_mode): raise NotADirectoryError(path) + def stat(self, path: Path | str) -> os.stat_result: + """Return the metadata of an existing entry, resolving only allowed links.""" + return os.stat(self._path(path), follow_symlinks=False) + def mkdir( self, path: Path | str, *, parents: bool = False, exist_ok: bool = False ) -> None: @@ -567,6 +581,82 @@ def create_text( ) -> None: self.create_bytes(path, content.encode(encoding), mode=mode) + def create_private_bytes(self, path: Path | str, content: bytes) -> None: + """Exclusively create a file only the current user can open, flushed to disk. + + A failure after creation removes only the file this call created. + """ + destination = self._path(path, allow_missing=True, follow_leaf=False) + try: + self._entry_mode(destination) + except FileNotFoundError: + pass + else: + raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(destination)) + with self._creation_directory(destination.parent) as directory: + if isinstance(directory, Path): + self._windows_create_private(directory / destination.name, content) + else: + self._posix_create_private(directory, destination.name, content) + + @staticmethod + def _posix_create_private(directory: int, name: str, content: bytes) -> None: + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + flags |= getattr(os, "O_CLOEXEC", 0) + fd = os.open(name, flags, 0o600, dir_fd=directory) + created: os.stat_result | None = None + try: + try: + created = os.fstat(fd) + _write_all(fd, content) + os.fsync(fd) + finally: + os.close(fd) + except BaseException: + # Never reopen the name: remove it only if it is still the created file. + try: + current = os.stat(name, dir_fd=directory, follow_symlinks=False) + if created is None or (current.st_dev, current.st_ino) == ( + created.st_dev, created.st_ino + ): + os.unlink(name, dir_fd=directory) + except OSError: + pass + raise + # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. + try: + parent = os.open( + ".", os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_CLOEXEC", 0), + dir_fd=directory, + ) + except OSError: + return + try: + os.fsync(parent) + except OSError: + pass + finally: + os.close(parent) + + @staticmethod + def _windows_create_private(path: Path, content: bytes) -> None: + fd = _windows_create_private_fd(path) + try: + try: + _write_all(fd, content) + os.fsync(fd) + except BaseException as error: + import msvcrt + + # The handle shares nothing, so it can only name the created file. + try: + _windows_delete(msvcrt.get_osfhandle(fd)) + except Exception as cleanup_error: + error.add_note(f"Could not remove partial file {path}: {cleanup_error}") + raise + finally: + os.close(fd) + def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Atomically create/replace a file, preserving any allowed leaf link.""" destination = self._path(path, allow_missing=True) @@ -605,7 +695,21 @@ def overwrite_text( stream.write(content) @contextmanager - def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: + def open_rewrite(self, path: Path | str) -> Iterator[int]: + """Yield a binary write descriptor on an existing regular file, untruncated. + + The descriptor starts at offset 0 and is closed on exit. The caller owns + writing, truncating and flushing; owner, mode and links are unchanged. + """ + destination = self._path(path) + self._require_file(destination) + with self._overwrite_descriptor(destination, create=False) as fd: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise UnsupportedPathError(f"Expected a regular file: {destination}") + yield fd + + @contextmanager + def _overwrite_descriptor(self, destination: Path, *, create: bool = True) -> Iterator[int]: """Anchor the resolved hierarchy before opening a non-truncating leaf.""" with ExitStack() as stack: if os.name == "nt": @@ -615,7 +719,7 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: for part in parts[:-1]: current = current / part stack.enter_context(_windows_handle(current, directory=True)) - yield stack.enter_context(_windows_overwrite_fd(destination)) + yield stack.enter_context(_windows_overwrite_fd(destination, create=create)) return unsupported = "Scoped text overwrite is unsupported on this platform" @@ -623,8 +727,8 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: raise OSError(errno.ENOTSUP, unsupported) with self._posix_directory(destination.parent, unsupported_message=unsupported) as parent: flags = ( - os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK - | getattr(os, "O_CLOEXEC", 0) + os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0) + | (os.O_CREAT if create else 0) ) fd = os.open(destination.name, flags, 0o666, dir_fd=parent) try: diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 2a785a32d5..6dfb6f9a24 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -540,7 +540,8 @@ def pin(path, *, directory): events.append(("unpin", path)) @contextmanager - def open_leaf(path): + def open_leaf(path, *, create=True): + assert create assert active == [tmp_path, parent] assert leaf.read_text() == "old" fd = os.open(path, os.O_WRONLY) @@ -582,12 +583,12 @@ def test_native_windows_overwrite_holds_every_parent_and_leaf(tmp_path, monkeypa parents_checked = [] @contextmanager - def open_while_pinned(path): + def open_while_pinned(path, *, create=True): for directory in (root, parent): with pytest.raises(PermissionError): directory.rename(directory.with_name(directory.name + "-moved")) parents_checked.append(directory) - with open_leaf(path) as fd: + with open_leaf(path, create=create) as fd: yield fd def truncate(fd, length): @@ -630,11 +631,11 @@ def test_native_windows_leaf_swap_at_open_never_follows_new_link( original = file_helper._windows_overwrite_fd @contextmanager - def swap(path): + def swap(path, *, create=True): if existing: leaf.rename(root / "original") leaf.symlink_to(outside) - with original(path) as fd: + with original(path, create=create) as fd: yield fd monkeypatch.setattr(file_helper, "_windows_overwrite_fd", swap) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py new file mode 100644 index 0000000000..3cc65b586c --- /dev/null +++ b/tests/test_file_helper_rewrite.py @@ -0,0 +1,505 @@ +"""Public in-place byte rewrite, owner-only creation and stat on FileHelper.""" + +import errno +import os +import stat +import subprocess +import sys +import types +from contextlib import contextmanager + +import pytest + +from specify_cli import _file_handles +from specify_cli.file_helper import ( + FileHelper, SymlinkDeniedError, UnsupportedPathError, +) + + +REL = "parent/file" + + +def _symlinks_available(tmp_path): + probe = tmp_path / "probe" + try: + probe.symlink_to(tmp_path, target_is_directory=True) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + + +def _seed(tmp_path, content=b"0123456789"): + path = tmp_path / REL + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return path + + +# stat + + +def test_stat_matches_the_entry(tmp_path): + path = _seed(tmp_path) + with FileHelper(tmp_path) as files: + info = files.stat(REL) + native = path.stat() + assert (info.st_dev, info.st_ino, info.st_size) == (native.st_dev, native.st_ino, 10) + assert stat.S_ISREG(info.st_mode) + + +def test_stat_reports_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + assert stat.S_ISDIR(files.stat("parent").st_mode) + + +def test_stat_of_a_missing_entry_raises(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.stat("missing") + + +def test_stat_refuses_a_symlink_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + files.stat("link") + with FileHelper(tmp_path, allow_symlinks=True) as files: + assert files.stat("link").st_ino == path.stat().st_ino + + +def test_stat_refuses_a_path_outside_the_root(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(ValueError): + files.stat("../outside") + + +# open_rewrite + + +def test_open_rewrite_writes_in_place_without_truncating(tmp_path): + path = _seed(tmp_path) + inode = path.stat().st_ino + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.lseek(fd, 0, os.SEEK_CUR) == 0 + assert os.fstat(fd).st_size == 10 + os.write(fd, b"ab\r\n") + assert path.read_bytes() == b"ab\r\n456789" + assert path.stat().st_ino == inode + + +def test_open_rewrite_keeps_the_mode(tmp_path): + path = _seed(tmp_path) + path.chmod(0o640) + before = stat.S_IMODE(path.stat().st_mode) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + os.ftruncate(fd, 0) + os.write(fd, b"new") + assert path.read_bytes() == b"new" + assert stat.S_IMODE(path.stat().st_mode) == before + + +def test_open_rewrite_closes_the_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + with files.open_rewrite(REL) as fd: + pass + with pytest.raises(OSError) as raised: + os.fstat(fd) + assert raised.value.errno == errno.EBADF + + +def test_open_rewrite_never_creates(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not (tmp_path / REL).exists() + + +def test_open_rewrite_does_not_create_a_leaf_removed_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path) + original = FileHelper._overwrite_descriptor + + @contextmanager + def remove_first(self, destination, **kwargs): + path.unlink() + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", remove_first) + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not path.exists() + + +def test_open_rewrite_refuses_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite("parent"): + pass + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_open_rewrite_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._overwrite_descriptor + + @contextmanager + def swap_first(self, destination, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError): + with files.open_rewrite(REL) as fd: + os.write(fd, b"written") + assert (outside / "file").read_bytes() == b"outside" + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_fifo_without_blocking(tmp_path): + (tmp_path / "parent").mkdir() + os.mkfifo(tmp_path / REL) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + pass + + +def test_open_rewrite_refuses_a_symlinked_leaf_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + with files.open_rewrite("link"): + pass + with FileHelper(tmp_path, allow_symlinks=True) as files, files.open_rewrite("link") as fd: + os.write(fd, b"ab") + assert (tmp_path / "link").is_symlink() + assert path.read_bytes() == b"ab23456789" + + +# create_private_bytes + + +def test_create_private_bytes_creates_exclusively(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"first") + with pytest.raises(FileExistsError): + files.create_private_bytes(REL, b"second") + assert (tmp_path / REL).read_bytes() == b"first" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") +def test_create_private_bytes_is_owner_only(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert stat.S_IMODE((tmp_path / REL).stat().st_mode) & 0o077 == 0 + + +def test_create_private_bytes_needs_an_existing_parent(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / "parent").exists() + + +def test_create_private_bytes_refuses_a_dangling_link(tmp_path): + _symlinks_available(tmp_path) + (tmp_path / "parent").mkdir() + (tmp_path / REL).symlink_to(tmp_path / "target") + with FileHelper(tmp_path, allow_symlinks=True) as files, pytest.raises(FileExistsError): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / "target").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_create_private_bytes_refuses_a_symlinked_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + project = tmp_path / "project" + project.mkdir() + (project / "parent").symlink_to(outside) + with FileHelper(project) as files, pytest.raises(SymlinkDeniedError): + files.create_private_bytes(REL, b"secret") + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_create_private_bytes_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): + outside = tmp_path / "outside" + outside.mkdir() + parent = tmp_path / "parent" + parent.mkdir() + original = FileHelper._creation_directory + + @contextmanager + def swap_first(self, directory): + parent.rename(tmp_path / "moved") + parent.symlink_to(outside, target_is_directory=True) + with original(self, directory) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError): + files.create_private_bytes(REL, b"secret") + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_create_private_bytes_refuses_a_junctioned_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + project = tmp_path / "project" + project.mkdir() + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], + check=True, capture_output=True, + ) + with FileHelper(project) as files, pytest.raises(UnsupportedPathError): + files.create_private_bytes(REL, b"secret") + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("step", ["write", "fsync", "close"]) +def test_posix_create_private_bytes_uses_one_descriptor_and_removes_a_partial_file( + tmp_path, monkeypatch, step +): + # Reopening the file by name could block on a FIFO swapped in for it. + (tmp_path / "parent").mkdir() + real_open, real_step = os.open, getattr(os, step) + leaf: list[int] = [] + live: set[int] = set() + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + live.add(fd) + return fd + + def fail(fd, *args): + if fd not in live: + return real_step(fd, *args) + if step == "close": + # Its number may be reused once closed. + live.discard(fd) + real_step(fd) + raise OSError("disk full") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, step, fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert len(leaf) == 1 + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_keeps_a_replacement_it_did_not_create(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def replace_then_fail(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + (tmp_path / REL).unlink() + (tmp_path / REL).write_bytes(b"someone else's") + raise OSError("disk full") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", replace_then_fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).read_bytes() == b"someone else's" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_flushes_the_file_and_its_directory(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_open, real_fsync, real_creation = os.open, os.fsync, FileHelper._creation_directory + leaf: list[int] = [] + pinned: list[int] = [] + synced: list[tuple[int, bool]] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + @contextmanager + def creation_directory(self, directory): + with real_creation(self, directory) as anchored: + pinned.append(anchored) + yield anchored + + def fsync(fd): + synced.append((fd, stat.S_ISDIR(os.fstat(fd).st_mode))) + return real_fsync(fd) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "fsync", fsync) + monkeypatch.setattr(FileHelper, "_creation_directory", creation_directory) + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert len(leaf) == 1 and (leaf[0], False) in synced + # The pinned descriptor may be O_PATH, which fsync rejects, so a readable one is used. + directories = [fd for fd, is_dir in synced if is_dir] + assert len(directories) == 1 and directories[0] not in pinned + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_succeeds_when_the_directory_cannot_be_flushed( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def fsync(fd): + if stat.S_ISDIR(os.fstat(fd).st_mode): + raise OSError(errno.EBADF, "Bad file descriptor") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(os.name != "nt", reason="Windows creation path") +def test_windows_create_private_bytes_removes_a_partial_file(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + created: list[int] = [] + real_create = _file_handles._windows_create_private_fd + + def create(path): + fd = real_create(path) + created.append(fd) + return fd + + def fsync(fd): + if fd in created: + raise OSError("disk full") + return real_fsync(fd) + + from specify_cli import file_helper + + monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert not (tmp_path / REL).exists() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows creation path") +def test_windows_create_private_bytes_leaves_no_file_if_no_descriptor_is_made( + tmp_path, monkeypatch +): + import msvcrt + + def fail(handle, flags): + raise OSError("too many open files") + + (tmp_path / "parent").mkdir() + monkeypatch.setattr(msvcrt, "open_osfhandle", fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="too many open files"): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / REL).exists() + monkeypatch.undo() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.parametrize("marked", [True, False, None]) +def test_windows_private_fd_removes_its_file_through_the_handle_if_no_descriptor_is_made( + tmp_path, monkeypatch, marked +): + # Simulates the Windows calls, so this runs everywhere; the test above + # makes the real ones. + import ctypes + + calls = [] + + class Attributes(ctypes.Structure): + _fields_ = [("nLength", ctypes.c_ulong), ("descriptor", ctypes.c_void_p), + ("inherit", ctypes.c_int)] + + class Kernel: + def CreateFileW(self, path, access, share, attributes, disposition, flags, template): + calls.append(("CreateFileW", access, share, disposition)) + return 1234 + + def SetFileInformationByHandle(self, handle, kind, info, size): + calls.append(("SetFileInformationByHandle", handle, kind, bytes(info._obj))) + if marked is None: + raise ctypes.ArgumentError("bad argument") + return int(marked) + + def CloseHandle(self, handle): + calls.append(("CloseHandle", handle)) + return 1 + + def LocalFree(self, pointer): + return None + + class Advapi: + def ConvertStringSecurityDescriptorToSecurityDescriptorW(self, *args): + return 1 + + def open_osfhandle(handle, flags): + raise OSError("too many open files") + + monkeypatch.setattr( + _file_handles, "_windows_security_api", lambda: (Kernel(), Advapi(), Attributes) + ) + monkeypatch.setattr(_file_handles, "_windows_owner_only_sddl", lambda: "O:S-1-0D:P") + monkeypatch.setattr(ctypes, "get_last_error", lambda: 5, raising=False) + monkeypatch.setattr(ctypes, "WinError", lambda code=None: OSError(code, "denied"), raising=False) + monkeypatch.setitem(sys.modules, "msvcrt", types.SimpleNamespace(open_osfhandle=open_osfhandle)) + monkeypatch.setattr(os, "O_BINARY", 0x8000, raising=False) + with pytest.raises(OSError, match="too many open files") as raised: + _file_handles._windows_create_private_fd(tmp_path / "file") + delete, create_new = 0x00010000, 1 + access, share, disposition = calls[0][1:] + assert access & delete and share == 0 and disposition == create_new + # FileDispositionInfo with DeleteFile set, before the handle closes. + assert calls[1:] == [("SetFileInformationByHandle", 1234, 4, b"\x01"), ("CloseHandle", 1234)] + # If it cannot be marked, the error names the empty file so it can be deleted. + noted = any(str(tmp_path / "file") in note for note in getattr(raised.value, "__notes__", [])) + assert noted is not bool(marked) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + result = subprocess.run( + ["powershell", "-NoProfile", "-Command", + f"(Get-Acl -LiteralPath '{tmp_path / REL}').Sddl"], + check=True, capture_output=True, text=True, + ) + sddl = result.stdout.strip() + sid = _file_handles._windows_current_user_sid() + assert f"O:{sid}" in sddl + dacl = sddl.split("D:", 1)[1] + assert dacl.startswith("P") + assert dacl.count("(") == 1 and f";;;{sid})" in dacl From bcf331e3ccb87a90c185c2495296fc3414ea0a9a Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 17:39:03 +0000 Subject: [PATCH 02/18] fix(file-helper): anchor stat and harden owner-only create cleanup - stat queries the leaf through the anchored parent hierarchy - open_rewrite yields a blocking descriptor and documents that the helper closes it - create_private_bytes clears ACL entries a macOS parent's inheritable ACEs add, never removes a name whose identity it could not read, keeps the first error when close also fails, and notes a partial file it could not remove - design doc lists the new operations among the Windows leaf-by-pathname limits; a missed Windows test stub accepts create Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WirNuLtfqtefs4BFj5Y --- design/file-helper.md | 28 +++--- src/specify_cli/file_helper.py | 119 +++++++++++++++++------- tests/test_file_helper.py | 3 +- tests/test_file_helper_rewrite.py | 148 ++++++++++++++++++++++++++++++ 4 files changed, 255 insertions(+), 43 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 6deba1cb34..5daf5f4b4a 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -246,8 +246,9 @@ descriptor-relative or change their documented concurrency limitations. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. - `stat(path)` returns the metadata of an existing entry after the normal policy walk: allowed contained links, including a leaf link, are resolved, and the - resolved entry itself is not followed. Missing entries raise - `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that + resolved entry itself is not followed. The entry is queried relative to the + anchored parent hierarchy, so a parent swapped after resolution cannot + redirect it. Missing entries raise `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects @@ -275,7 +276,9 @@ descriptor-relative or change their documented concurrency limitations. current user can open, with existing parents, and flushes it before returning. It shares `create_bytes`'s policy walk, no-follow `lstat` preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` - relative to the anchored parent, writes and `fsync`s through that one + relative to the anchored parent; on macOS it then clears any extended ACL + entries a parent's inheritable ACEs added (Linux default ACLs are bounded by + the mask the mode sets). It writes and `fsync`s through that one descriptor, then flushes the parent best effort through a readable descriptor opened from the anchor (search-only and `O_PATH` anchors reject `fsync`); a parent that cannot be flushed does not fail the call. Windows creates the leaf @@ -284,8 +287,9 @@ descriptor-relative or change their documented concurrency limitations. only that user full access, so the content is never readable under an inherited ACL. A failure after creation removes only the file this call created: POSIX unlinks the name only while it still has the created file's - identity, and Windows marks the open handle for deletion. If that removal - fails, the original exception carries a note naming the file. + identity (an identity never read leaves the name in place), and Windows marks + the open handle for deletion. If that removal or the close fails, the original + exception is kept and carries a note naming the file. - `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 @@ -326,14 +330,15 @@ descriptor-relative or change their documented concurrency limitations. Windows creation also honors the CRT process mask: masking the owner-write bit creates a read-only file, matching native text creation, without changing the attributes of an existing file. -- `open_rewrite(path)` is a context manager yielding a binary, writable - descriptor on an existing regular file at offset 0, for in-place byte +- `open_rewrite(path)` is a context manager yielding a blocking, binary, + writable descriptor on an existing regular file at offset 0, for in-place byte rewrites that must keep the file's identity, owner, mode, ACL and hard links. It uses `overwrite_text`'s anchored, non-truncating open, but never creates: POSIX omits `O_CREAT` and Windows does not fall back to creation, so a leaf removed after resolution raises `FileNotFoundError`. The opened file type is - checked with `fstat` before the descriptor is yielded, and the descriptor is - closed on exit. Writing, truncating, flushing and any rollback belong to the + checked with `fstat` before the descriptor is yielded. The helper closes the + descriptor on exit, so callers must not close it; wrap it with + `closefd=False`. Writing, truncating, flushing and any rollback belong to the caller; nothing is written or truncated by the helper. There is no newline translation on either platform. - `delete(path, recursive=False)` unlinks files/links or removes directories. @@ -471,8 +476,9 @@ 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. -On Windows, exclusive creation and text overwrite still open their leaf by -pathname after pinning the parent hierarchy. Attribute-only reparse updates +On Windows, exclusive creation (including `create_private_bytes`), text +overwrite and `open_rewrite` still open their leaf by pathname after pinning the +parent hierarchy, and `stat` queries its leaf the same way. Attribute-only reparse updates can redirect those opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 74b6906dd9..43be99bf90 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -34,6 +34,50 @@ _POSIX_OPEN = os.open +def _remove_created( + directory: int, name: str, created: os.stat_result | None, error: BaseException +) -> None: + """Unlink ``name`` only while it is still the file this call created.""" + if created is None: + error.add_note(f"Left {name}, which may be empty; delete it before retrying") + return + try: + current = os.stat(name, dir_fd=directory, follow_symlinks=False) + if (current.st_dev, current.st_ino) == (created.st_dev, created.st_ino): + os.unlink(name, dir_fd=directory) + except OSError as cleanup_error: + error.add_note(f"Could not remove partial file {name}: {cleanup_error}") + + +def _clear_extended_acl(fd: int) -> None: + """Drop ACL entries a macOS parent's inheritable ACEs added to a new file. + + Elsewhere the creation mode bounds access: Linux default ACLs are limited by + the mask that mode sets. + """ + if sys.platform != "darwin": + return + import ctypes + + libc = ctypes.CDLL(None, use_errno=True) + libc.acl_init.restype = ctypes.c_void_p + libc.acl_init.argtypes = [ctypes.c_int] + libc.acl_set_fd.argtypes = [ctypes.c_int, ctypes.c_void_p] + libc.acl_free.argtypes = [ctypes.c_void_p] + acl = libc.acl_init(0) + if not acl: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + try: + if libc.acl_set_fd(fd, acl) != 0: + code = ctypes.get_errno() + # A filesystem without ACLs cannot have added any. + if code not in (errno.ENOTSUP, errno.EOPNOTSUPP): + raise OSError(code, f"Could not clear inherited ACL entries: {os.strerror(code)}") + finally: + libc.acl_free(acl) + + def _write_all(fd: int, content: bytes) -> None: view = memoryview(content) while view: @@ -389,7 +433,14 @@ def _require_directory(path: Path) -> None: def stat(self, path: Path | str) -> os.stat_result: """Return the metadata of an existing entry, resolving only allowed links.""" - return os.stat(self._path(path), follow_symlinks=False) + destination = self._path(path) + if destination == self._canonical_root: + return os.stat(destination) + # Stat through the anchored parent so a swapped ancestor cannot redirect it. + with self._creation_directory(destination.parent) as directory: + if isinstance(directory, Path): + return os.stat(directory / destination.name, follow_symlinks=False) + return os.stat(destination.name, dir_fd=directory, follow_symlinks=False) def mkdir( self, path: Path | str, *, parents: bool = False, exist_ok: bool = False @@ -606,22 +657,21 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: fd = os.open(name, flags, 0o600, dir_fd=directory) created: os.stat_result | None = None try: + created = os.fstat(fd) + _clear_extended_acl(fd) + _write_all(fd, content) + os.fsync(fd) + except BaseException as error: try: - created = os.fstat(fd) - _write_all(fd, content) - os.fsync(fd) - finally: os.close(fd) - except BaseException: - # Never reopen the name: remove it only if it is still the created file. - try: - current = os.stat(name, dir_fd=directory, follow_symlinks=False) - if created is None or (current.st_dev, current.st_ino) == ( - created.st_dev, created.st_ino - ): - os.unlink(name, dir_fd=directory) - except OSError: - pass + except OSError as close_error: + error.add_note(f"Could not close {name}: {close_error}") + _remove_created(directory, name, created, error) + raise + try: + os.close(fd) + except BaseException as error: + _remove_created(directory, name, created, error) raise # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. try: @@ -642,20 +692,22 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: def _windows_create_private(path: Path, content: bytes) -> None: fd = _windows_create_private_fd(path) try: - try: - _write_all(fd, content) - os.fsync(fd) - except BaseException as error: - import msvcrt + _write_all(fd, content) + os.fsync(fd) + except BaseException as error: + import msvcrt - # The handle shares nothing, so it can only name the created file. - try: - _windows_delete(msvcrt.get_osfhandle(fd)) - except Exception as cleanup_error: - error.add_note(f"Could not remove partial file {path}: {cleanup_error}") - raise - finally: - os.close(fd) + # The handle shares nothing, so it can only name the created file. + try: + _windows_delete(msvcrt.get_osfhandle(fd)) + except Exception as cleanup_error: + error.add_note(f"Could not remove partial file {path}: {cleanup_error}") + try: + os.close(fd) + except OSError as close_error: + error.add_note(f"Could not close {path}: {close_error}") + raise + os.close(fd) def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Atomically create/replace a file, preserving any allowed leaf link.""" @@ -696,16 +748,21 @@ def overwrite_text( @contextmanager def open_rewrite(self, path: Path | str) -> Iterator[int]: - """Yield a binary write descriptor on an existing regular file, untruncated. + """Yield a blocking binary write descriptor on an existing regular file, untruncated. - The descriptor starts at offset 0 and is closed on exit. The caller owns - writing, truncating and flushing; owner, mode and links are unchanged. + The descriptor starts at offset 0 and the helper closes it on exit, so the + caller must not close it (wrap it with ``os.fdopen(fd, "wb", closefd=False)``). + The caller owns writing, truncating and flushing; owner, mode and links are + unchanged. """ destination = self._path(path) self._require_file(destination) with self._overwrite_descriptor(destination, create=False) as fd: if not stat.S_ISREG(os.fstat(fd).st_mode): raise UnsupportedPathError(f"Expected a regular file: {destination}") + if os.name != "nt": + # Opened non-blocking only so a FIFO swapped in cannot hang the open. + os.set_blocking(fd, True) yield fd @contextmanager diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 32a8dc8238..5238ea967a 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -776,7 +776,8 @@ def denied(*args, **kwargs): raise PermissionError("denied") if os.name == "nt": - def denied_windows(path): + def denied_windows(path, *, create=True): + assert create assert path == root / "new" calls.append(path) raise PermissionError("denied") diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 3cc65b586c..4af9f593d1 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -503,3 +503,151 @@ def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path) dacl = sddl.split("D:", 1)[1] assert dacl.startswith("P") assert dacl.count("(") == 1 and f";;;{sid})" in dacl + + +# Review regressions + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside, longer") + original = FileHelper._creation_directory + + @contextmanager + def swap_first(self, directory): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, directory) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError): + files.stat(REL) + + +def test_stat_of_the_root(tmp_path): + with FileHelper(tmp_path) as files: + assert files.stat(tmp_path).st_ino == tmp_path.stat().st_ino + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptors") +def test_open_rewrite_yields_a_blocking_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.get_blocking(fd) + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") +def test_create_private_bytes_drops_acl_entries_inherited_from_the_parent(tmp_path): + parent = tmp_path / "parent" + parent.mkdir() + subprocess.run( + ["chmod", "+a", "everyone allow read,file_inherit", str(parent)], + check=True, capture_output=True, + ) + (parent / "plain").write_bytes(b"") + inherited = subprocess.run( + ["ls", "-le", str(parent / "plain")], check=True, capture_output=True, text=True, + ).stdout + if "everyone" not in inherited: + pytest.skip("filesystem did not apply the inheritable ACE") + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"secret") + listing = subprocess.run( + ["ls", "-le", str(tmp_path / REL)], check=True, capture_output=True, text=True, + ).stdout + assert "everyone" not in listing + assert (tmp_path / REL).read_bytes() == b"secret" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_notes_a_partial_file_it_could_not_remove( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fsync, real_unlink = os.fsync, os.unlink + + def fsync(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError(errno.ENOSPC, "No space left") + return real_fsync(fd) + + def unlink(path, *args, **kwargs): + if os.fspath(path) == "file": + raise PermissionError(errno.EACCES, "denied") + return real_unlink(path, *args, **kwargs) + + monkeypatch.setattr(os, "fsync", fsync) + monkeypatch.setattr(os, "unlink", unlink) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("Could not remove partial file" in note for note in raised.value.__notes__) + assert (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_never_removes_a_name_it_could_not_identify( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fstat = os.fstat + leaf: list[int] = [] + real_open = os.open + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def fstat(fd): + if fd in leaf: + raise OSError(errno.EIO, "fstat failed") + return real_fstat(fd) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "fstat", fstat) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="fstat failed") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).exists() + assert any("delete it before retrying" in note for note in raised.value.__notes__) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_keeps_the_write_error_when_close_also_fails( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_open, real_write, real_close = os.open, os.write, os.close + leaf: list[int] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def write(fd, data): + if fd in leaf: + raise OSError(errno.ENOSPC, "No space left") + return real_write(fd, data) + + def close(fd): + real_close(fd) + if fd in leaf: + leaf.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(os, "close", close) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("Could not close" in note for note in raised.value.__notes__) + assert not (tmp_path / REL).exists() From 8bbe5520b050b8994c3e35445c79c31f2628585a Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 17:44:49 +0000 Subject: [PATCH 03/18] fix(file-helper): refuse private files others can open, anchor stat per platform - create_private_bytes refuses, before writing, a file that came out with group/other mode bits or (macOS) inherited ACL entries, which a directory-relative create cannot withhold; it adds F_FULLFSYNC on macOS and no longer fails on closing the flushed parent - stat walks POSIX parents with its own unsupported message and pins Windows parents with traverse handles, as read_bytes does - a Windows close failure after a complete write is noted - swapped-parent tests assert the refusal errno; design doc narrowed to what the code guarantees Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WirNuLtfqtefs4BFj5Y --- design/file-helper.md | 19 +++--- src/specify_cli/file_helper.py | 99 +++++++++++++++++++++++-------- tests/test_file_helper_rewrite.py | 47 ++++++++++----- 3 files changed, 118 insertions(+), 47 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 5daf5f4b4a..b999afbbcd 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -276,10 +276,13 @@ descriptor-relative or change their documented concurrency limitations. current user can open, with existing parents, and flushes it before returning. It shares `create_bytes`'s policy walk, no-follow `lstat` preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` - relative to the anchored parent; on macOS it then clears any extended ACL - entries a parent's inheritable ACEs added (Linux default ACLs are bounded by - the mask the mode sets). It writes and `fsync`s through that one - descriptor, then flushes the parent best effort through a readable descriptor + relative to the anchored parent. Before any content is written, it refuses + (removing the still-empty file) when the file came out with group or other + mode bits, which means the filesystem ignored the mode, or, on macOS, with + ACL entries inherited from the parent, which a directory-relative create + cannot withhold. Linux default ACLs are bounded by the mask the mode sets. + NFSv4-style inherited ACLs on other systems are not inspected. It writes and + `fsync`s (adding `F_FULLFSYNC` on macOS) through that one descriptor, then flushes the parent best effort through a readable descriptor opened from the anchor (search-only and `O_PATH` anchors reject `fsync`); a parent that cannot be flushed does not fail the call. Windows creates the leaf with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security @@ -287,9 +290,11 @@ descriptor-relative or change their documented concurrency limitations. only that user full access, so the content is never readable under an inherited ACL. A failure after creation removes only the file this call created: POSIX unlinks the name only while it still has the created file's - identity (an identity never read leaves the name in place), and Windows marks - the open handle for deletion. If that removal or the close fails, the original - exception is kept and carries a note naming the file. + identity, checked immediately before the unlink rather than atomically with + it (an identity never read leaves the name in place), and Windows marks the + open handle for deletion. If that removal or the close fails, the original + exception is kept and carries a note naming the file. A Windows close failure + after a complete write leaves the file and says so in the note. - `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 diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 43be99bf90..7294e83533 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -37,7 +37,7 @@ def _remove_created( directory: int, name: str, created: os.stat_result | None, error: BaseException ) -> None: - """Unlink ``name`` only while it is still the file this call created.""" + """Unlink ``name`` if it still has the created file's identity (best effort).""" if created is None: error.add_note(f"Left {name}, which may be empty; delete it before retrying") return @@ -49,35 +49,63 @@ def _remove_created( error.add_note(f"Could not remove partial file {name}: {cleanup_error}") -def _clear_extended_acl(fd: int) -> None: - """Drop ACL entries a macOS parent's inheritable ACEs added to a new file. +def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: + """Refuse a new, still-empty file that someone other than its owner can open. - Elsewhere the creation mode bounds access: Linux default ACLs are limited by - the mask that mode sets. + Group or other mode bits mean the filesystem ignored the creation mode. On + macOS, a parent's inheritable ACEs are added to a new file whatever its mode, + and they cannot be withheld from a directory-relative create, so such a file + is refused before any content reaches it. NFSv4-style inherited ACLs on other + systems are not inspected. """ - if sys.platform != "darwin": - return + if stat.S_IMODE(info.st_mode) & 0o077: + raise PermissionError( + errno.EACCES, + f"Filesystem did not create {name} owner-only " + f"(mode {stat.S_IMODE(info.st_mode):o})", + ) + if sys.platform == "darwin" and _has_extended_acl(fd): + raise PermissionError( + errno.EACCES, + f"Refusing to write {name}: its directory's inherited ACL entries grant " + "access to others", + ) + + +def _has_extended_acl(fd: int) -> bool: import ctypes libc = ctypes.CDLL(None, use_errno=True) - libc.acl_init.restype = ctypes.c_void_p - libc.acl_init.argtypes = [ctypes.c_int] - libc.acl_set_fd.argtypes = [ctypes.c_int, ctypes.c_void_p] + libc.acl_get_fd_np.restype = ctypes.c_void_p + libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] + libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] libc.acl_free.argtypes = [ctypes.c_void_p] - acl = libc.acl_init(0) + acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED if not acl: code = ctypes.get_errno() - raise OSError(code, os.strerror(code)) + # No ACL, or a filesystem that cannot hold one. + if code in (errno.ENOENT, errno.ENOTSUP, errno.EOPNOTSUPP): + return False + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") try: - if libc.acl_set_fd(fd, acl) != 0: - code = ctypes.get_errno() - # A filesystem without ACLs cannot have added any. - if code not in (errno.ENOTSUP, errno.EOPNOTSUPP): - raise OSError(code, f"Could not clear inherited ACL entries: {os.strerror(code)}") + entry = ctypes.c_void_p() + return libc.acl_get_entry(acl, 0, ctypes.byref(entry)) == 0 # ACL_FIRST_ENTRY finally: libc.acl_free(acl) +def _full_fsync(fd: int) -> None: + """Flush to stable storage; macOS ``fsync`` alone leaves data in the drive cache.""" + os.fsync(fd) + if sys.platform == "darwin": + import fcntl + + try: + fcntl.fcntl(fd, fcntl.F_FULLFSYNC) + except OSError: + pass # Not every filesystem supports it; fsync has already run. + + def _write_all(fd: int, content: bytes) -> None: view = memoryview(content) while view: @@ -437,9 +465,20 @@ def stat(self, path: Path | str) -> os.stat_result: if destination == self._canonical_root: return os.stat(destination) # Stat through the anchored parent so a swapped ancestor cannot redirect it. - with self._creation_directory(destination.parent) as directory: - if isinstance(directory, Path): - return os.stat(directory / destination.name, follow_symlinks=False) + if os.name == "nt": + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + return os.stat(destination, follow_symlinks=False) + with self._posix_directory( + destination.parent, unsupported_message="Anchored stat is unsupported on this platform", + ) as directory: return os.stat(destination.name, dir_fd=directory, follow_symlinks=False) def mkdir( @@ -658,9 +697,9 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: created: os.stat_result | None = None try: created = os.fstat(fd) - _clear_extended_acl(fd) + _require_owner_only(fd, created, name) _write_all(fd, content) - os.fsync(fd) + _full_fsync(fd) except BaseException as error: try: os.close(fd) @@ -682,18 +721,21 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: except OSError: return try: - os.fsync(parent) + _full_fsync(parent) except OSError: pass finally: - os.close(parent) + try: + os.close(parent) + except OSError: + pass @staticmethod def _windows_create_private(path: Path, content: bytes) -> None: fd = _windows_create_private_fd(path) try: _write_all(fd, content) - os.fsync(fd) + _full_fsync(fd) except BaseException as error: import msvcrt @@ -707,7 +749,12 @@ def _windows_create_private(path: Path, content: bytes) -> None: except OSError as close_error: error.add_note(f"Could not close {path}: {close_error}") raise - os.close(fd) + try: + os.close(fd) + except OSError as error: + # The handle is gone, so it can no longer remove the file. + error.add_note(f"{path} was written and flushed but may need deleting before a retry") + raise def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Atomically create/replace a file, preserving any allowed leaf link.""" diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 4af9f593d1..f1dbc4cb31 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -156,9 +156,10 @@ def swap_first(self, destination, **kwargs): yield fd monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) - with FileHelper(tmp_path) as files, pytest.raises(OSError): + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: with files.open_rewrite(REL) as fd: os.write(fd, b"written") + assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) assert (outside / "file").read_bytes() == b"outside" @@ -247,8 +248,9 @@ def swap_first(self, directory): yield anchored monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) - with FileHelper(tmp_path) as files, pytest.raises(OSError): + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: files.create_private_bytes(REL, b"secret") + assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) assert not list(outside.iterdir()) @@ -514,18 +516,19 @@ def test_stat_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, m outside = tmp_path / "outside" outside.mkdir() (outside / "file").write_bytes(b"outside, longer") - original = FileHelper._creation_directory + original = FileHelper._posix_directory @contextmanager - def swap_first(self, directory): + def swap_first(self, directory, **kwargs): path.parent.rename(tmp_path / "moved") path.parent.symlink_to(outside, target_is_directory=True) - with original(self, directory) as anchored: + with original(self, directory, **kwargs) as anchored: yield anchored - monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) - with FileHelper(tmp_path) as files, pytest.raises(OSError): + monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: files.stat(REL) + assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) def test_stat_of_the_root(tmp_path): @@ -541,7 +544,7 @@ def test_open_rewrite_yields_a_blocking_descriptor(tmp_path): @pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") -def test_create_private_bytes_drops_acl_entries_inherited_from_the_parent(tmp_path): +def test_create_private_bytes_refuses_a_directory_with_inheritable_acl_entries(tmp_path): parent = tmp_path / "parent" parent.mkdir() subprocess.run( @@ -554,13 +557,29 @@ def test_create_private_bytes_drops_acl_entries_inherited_from_the_parent(tmp_pa ).stdout if "everyone" not in inherited: pytest.skip("filesystem did not apply the inheritable ACE") - with FileHelper(tmp_path) as files: + with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="inherited ACL"): files.create_private_bytes(REL, b"secret") - listing = subprocess.run( - ["ls", "-le", str(tmp_path / REL)], check=True, capture_output=True, text=True, - ).stdout - assert "everyone" not in listing - assert (tmp_path / REL).read_bytes() == b"secret" + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") +def test_create_private_bytes_refuses_a_filesystem_that_ignores_the_mode(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fstat = os.fstat + + def fstat(fd): + info = real_fstat(fd) + if stat.S_ISREG(info.st_mode): + values = list(info) + values[0] = stat.S_IFREG | 0o777 + return os.stat_result(values) + return info + + monkeypatch.setattr(os, "fstat", fstat) + with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="owner-only"): + files.create_private_bytes(REL, b"secret") + monkeypatch.undo() + assert not (tmp_path / REL).exists() @pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") From 3543a087e604b02e251a195722459d1a84397fc1 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 17:49:50 +0000 Subject: [PATCH 04/18] fix(file-helper): refuse only inherited allow entries, surface real full-fsync errors - create_private_bytes refuses a macOS file only for inherited ACL allow entries; deny-only entries grant nothing and no longer leave an empty file behind - F_FULLFSYNC ignores only unsupported-operation errors - stat reports ENOTSUP where os.stat lacks dir_fd/no-follow support - tests: deny-only ACL, full-fsync errors, the Windows close note, a junctioned stat parent, and BSD no-follow errnos; design doc rewrapped Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WirNuLtfqtefs4BFj5Y --- design/file-helper.md | 17 +++--- src/specify_cli/file_helper.py | 34 +++++++---- tests/test_file_helper_rewrite.py | 99 +++++++++++++++++++++++++++++-- 3 files changed, 129 insertions(+), 21 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b999afbbcd..ee64892857 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -248,8 +248,9 @@ descriptor-relative or change their documented concurrency limitations. walk: allowed contained links, including a leaf link, are resolved, and the resolved entry itself is not followed. The entry is queried relative to the anchored parent hierarchy, so a parent swapped after resolution cannot - redirect it. Missing entries raise `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that - act on the result must re-check identity on the descriptor they act through. + redirect it. Missing entries raise `FileNotFoundError`. It is a + point-in-time query, not an anchor: callers that act on the result must + re-check identity on the descriptor they act through. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. @@ -279,11 +280,13 @@ descriptor-relative or change their documented concurrency limitations. relative to the anchored parent. Before any content is written, it refuses (removing the still-empty file) when the file came out with group or other mode bits, which means the filesystem ignored the mode, or, on macOS, with - ACL entries inherited from the parent, which a directory-relative create - cannot withhold. Linux default ACLs are bounded by the mask the mode sets. - NFSv4-style inherited ACLs on other systems are not inspected. It writes and - `fsync`s (adding `F_FULLFSYNC` on macOS) through that one descriptor, then flushes the parent best effort through a readable descriptor - opened from the anchor (search-only and `O_PATH` anchors reject `fsync`); a + inherited ACL allow entries, which a directory-relative create cannot + withhold (inherited deny entries are accepted). Linux default ACLs are + bounded by the mask the mode sets. NFSv4-style inherited ACLs on other + systems are not inspected. It writes and `fsync`s through that one + descriptor, adding `F_FULLFSYNC` on macOS where the filesystem supports it, + then flushes the parent best effort through a readable descriptor opened + from the anchor (search-only and `O_PATH` anchors reject `fsync`); a parent that cannot be flushed does not fail the call. Windows creates the leaf with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security descriptor naming the current user as owner with a protected DACL granting diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 7294e83533..8510058749 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -64,21 +64,23 @@ def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: f"Filesystem did not create {name} owner-only " f"(mode {stat.S_IMODE(info.st_mode):o})", ) - if sys.platform == "darwin" and _has_extended_acl(fd): + if sys.platform == "darwin" and _has_inherited_allow_entry(fd): raise PermissionError( errno.EACCES, - f"Refusing to write {name}: its directory's inherited ACL entries grant " - "access to others", + f"Refusing to write {name}: its directory's inheritable ACL entries allow " + "others access", ) -def _has_extended_acl(fd: int) -> bool: +def _has_inherited_allow_entry(fd: int) -> bool: + """Whether a macOS file's ACL has an allow entry; deny entries grant nothing.""" import ctypes libc = ctypes.CDLL(None, use_errno=True) libc.acl_get_fd_np.restype = ctypes.c_void_p libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] + libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] libc.acl_free.argtypes = [ctypes.c_void_p] acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED if not acl: @@ -89,7 +91,16 @@ def _has_extended_acl(fd: int) -> bool: raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") try: entry = ctypes.c_void_p() - return libc.acl_get_entry(acl, 0, ctypes.byref(entry)) == 0 # ACL_FIRST_ENTRY + tag = ctypes.c_int() + which = 0 # ACL_FIRST_ENTRY, then ACL_NEXT_ENTRY + while libc.acl_get_entry(acl, which, ctypes.byref(entry)) == 0: + which = -1 + if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: + code = ctypes.get_errno() + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") + if tag.value == 1: # ACL_EXTENDED_ALLOW + return True + return False finally: libc.acl_free(acl) @@ -102,8 +113,10 @@ def _full_fsync(fd: int) -> None: try: fcntl.fcntl(fd, fcntl.F_FULLFSYNC) - except OSError: - pass # Not every filesystem supports it; fsync has already run. + except OSError as error: + # Not every filesystem supports it, and fsync has already run. + if error.errno not in (errno.ENOTSUP, errno.EOPNOTSUPP, errno.EINVAL, errno.ENOTTY): + raise def _write_all(fd: int, content: bytes) -> None: @@ -476,9 +489,10 @@ def stat(self, path: Path | str) -> os.stat_result: Path(part), directory=True, parent=parent, traverse=True, )) return os.stat(destination, follow_symlinks=False) - with self._posix_directory( - destination.parent, unsupported_message="Anchored stat is unsupported on this platform", - ) as directory: + unsupported = "Anchored stat is unsupported on this platform" + if os.stat not in os.supports_dir_fd or os.stat not in os.supports_follow_symlinks: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: return os.stat(destination.name, dir_fd=directory, follow_symlinks=False) def mkdir( diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index f1dbc4cb31..4d97e6f81c 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -17,6 +17,10 @@ REL = "parent/file" +# What open(O_NOFOLLOW | O_DIRECTORY) of a symlink raises: Linux/macOS, FreeBSD, NetBSD. +_NOFOLLOW_REFUSALS = { + errno.ELOOP, errno.ENOTDIR, errno.EMLINK, getattr(errno, "EFTYPE", errno.ELOOP), +} def _symlinks_available(tmp_path): @@ -159,7 +163,7 @@ def swap_first(self, destination, **kwargs): with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: with files.open_rewrite(REL) as fd: os.write(fd, b"written") - assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) + assert raised.value.errno in _NOFOLLOW_REFUSALS assert (outside / "file").read_bytes() == b"outside" @@ -250,7 +254,7 @@ def swap_first(self, directory): monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: files.create_private_bytes(REL, b"secret") - assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) + assert raised.value.errno in _NOFOLLOW_REFUSALS assert not list(outside.iterdir()) @@ -528,7 +532,7 @@ def swap_first(self, directory, **kwargs): monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: files.stat(REL) - assert raised.value.errno in (errno.ELOOP, errno.ENOTDIR) + assert raised.value.errno in _NOFOLLOW_REFUSALS def test_stat_of_the_root(tmp_path): @@ -557,7 +561,7 @@ def test_create_private_bytes_refuses_a_directory_with_inheritable_acl_entries(t ).stdout if "everyone" not in inherited: pytest.skip("filesystem did not apply the inheritable ACE") - with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="inherited ACL"): + with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="inheritable ACL entries allow"): files.create_private_bytes(REL, b"secret") assert not (tmp_path / REL).exists() @@ -670,3 +674,90 @@ def close(fd): monkeypatch.undo() assert any("Could not close" in note for note in raised.value.__notes__) assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") +def test_create_private_bytes_accepts_inherited_deny_only_acl_entries(tmp_path): + parent = tmp_path / "parent" + parent.mkdir() + subprocess.run( + ["chmod", "+a", "everyone deny delete,file_inherit", str(parent)], + check=True, capture_output=True, + ) + try: + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"secret") + assert (tmp_path / REL).read_bytes() == b"secret" + finally: + subprocess.run(["chmod", "-RN", str(parent)], check=False, capture_output=True) + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") +@pytest.mark.parametrize(("code", "raises"), [(errno.ENOTSUP, False), (errno.EINVAL, False), + (errno.EIO, True)]) +def test_create_private_bytes_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): + import fcntl + + (tmp_path / "parent").mkdir() + real_fcntl = fcntl.fcntl + + def fail(fd, command, *args): + if command == fcntl.F_FULLFSYNC and stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError(code, os.strerror(code)) + return real_fcntl(fd, command, *args) + + monkeypatch.setattr(fcntl, "fcntl", fail) + with FileHelper(tmp_path) as files: + if raises: + with pytest.raises(OSError) as raised: + files.create_private_bytes(REL, b"content") + assert raised.value.errno == code + else: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).exists() is not raises + + +def test_windows_create_private_notes_a_close_failure_after_a_complete_write( + tmp_path, monkeypatch +): + # Drives the Windows branch with a real descriptor so it runs everywhere. + from specify_cli import file_helper + + target = tmp_path / "file" + real_close = os.close + opened: list[int] = [] + + def create(path): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + opened.append(fd) + return fd + + def close(fd): + real_close(fd) + if fd in opened: + opened.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) + monkeypatch.setattr(os, "close", close) + with pytest.raises(OSError, match="Input/output error") as raised: + FileHelper._windows_create_private(target, b"content") + monkeypatch.undo() + assert any("may need deleting" in note for note in raised.value.__notes__) + assert target.read_bytes() == b"content" + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_stat_refuses_a_junctioned_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + project = tmp_path / "project" + project.mkdir() + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], + check=True, capture_output=True, + ) + with FileHelper(project) as files, pytest.raises(UnsupportedPathError): + files.stat(REL) From 7e9de98a5ffb00cace5dac9099563f96014ab68b Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 18:17:20 +0000 Subject: [PATCH 05/18] feat(file-helper): add access() and canonical_root Callers moving off direct filesystem I/O (#5117's Codex policy checks) still need two things the public API lacked: - access(path, mode) answers os.access for an entry found and anchored as stat finds it, without following links. It reports what mode bits miss: a file owned by someone else, a read-only filesystem, and on Windows the read-only attribute. - canonical_root exposes the root resolved on construction, so a caller can compare against resolved paths without calling Path.resolve. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5Wip1LjrZn3fBQteLAq9 --- design/file-helper.md | 8 +++ src/specify_cli/file_helper.py | 33 ++++++++++++ tests/test_file_helper_rewrite.py | 89 +++++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+) diff --git a/design/file-helper.md b/design/file-helper.md index ee64892857..d5637247f1 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -251,6 +251,14 @@ descriptor-relative or change their documented concurrency limitations. redirect it. Missing entries raise `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. +- `access(path, mode)` answers `os.access` for an existing entry found and + anchored as `stat` finds it, without following links: POSIX checks relative + to the anchored parent descriptor, Windows pins the parent hierarchy first. + It uses the real user and group ids, so it also reports a read-only + filesystem or a file owned by someone else, which mode bits miss. It is + advisory, like `stat`. +- `canonical_root` is the root with OS and link aliases resolved, fixed on + construction; it is the base that resolved operation paths share. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 8510058749..af10152f1c 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -472,6 +472,39 @@ def _require_directory(path: Path) -> None: if not stat.S_ISDIR(path.stat().st_mode): raise NotADirectoryError(path) + @property + def canonical_root(self) -> Path: + """``root`` with OS and link aliases resolved, as fixed on construction.""" + return self._canonical_root + + def access(self, path: Path | str, mode: int) -> bool: + """Return whether ``os.access`` grants ``mode`` on an existing entry. + + The entry is found and anchored as ``stat`` finds it, and links are not + followed. Like ``os.access``, the answer uses the real user and group + ids and is advisory: act through a descriptor and handle its errors. + """ + destination = self._path(path) + if destination == self._canonical_root: + return os.access(destination, mode) + if os.name == "nt": + # Pin the hierarchy as ``stat`` does; Windows ``os.access`` has no ``dir_fd``. + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + return os.access(destination, mode) + unsupported = "Anchored access check is unsupported on this platform" + if os.access not in os.supports_dir_fd or os.access not in os.supports_follow_symlinks: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + return os.access(destination.name, mode, dir_fd=directory, follow_symlinks=False) + def stat(self, path: Path | str) -> os.stat_result: """Return the metadata of an existing entry, resolving only allowed links.""" destination = self._path(path) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 4d97e6f81c..672b6402ec 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -77,6 +77,74 @@ def test_stat_refuses_a_path_outside_the_root(tmp_path): files.stat("../outside") +# access and canonical_root + + +def test_access_grants_an_accessible_entry(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK | os.W_OK) + assert files.access("parent", os.X_OK) + assert files.access(tmp_path, os.W_OK) + + +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX permissions enforced for the current user", +) +def test_access_refuses_what_the_mode_denies(tmp_path): + path = _seed(tmp_path) + path.chmod(0o444) + try: + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK) + assert not files.access(REL, os.W_OK) + finally: + path.chmod(0o644) + + +@pytest.mark.skipif(os.name != "nt", reason="the read-only attribute is Windows-only") +def test_access_reports_the_windows_read_only_attribute(tmp_path): + path = _seed(tmp_path) + path.chmod(stat.S_IREAD) + try: + with FileHelper(tmp_path) as files: + assert not files.access(REL, os.W_OK) + finally: + path.chmod(stat.S_IREAD | stat.S_IWRITE) + + +def test_access_of_a_missing_entry_raises(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.access("missing", os.R_OK) + + +def test_access_refuses_a_symlink_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + files.access("link", os.R_OK) + with FileHelper(tmp_path, allow_symlinks=True) as files: + assert files.access("link", os.R_OK) + + +def test_access_refuses_a_path_outside_the_root(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(ValueError): + files.access("../outside", os.R_OK) + + +def test_canonical_root_resolves_a_root_alias(tmp_path): + _symlinks_available(tmp_path) + real = tmp_path / "real" + real.mkdir() + alias = tmp_path / "alias" + alias.symlink_to(real, target_is_directory=True) + with FileHelper(alias) as files: + assert files.root == alias + assert files.canonical_root == real.resolve() + + # open_rewrite @@ -535,6 +603,27 @@ def swap_first(self, directory, **kwargs): assert raised.value.errno in _NOFOLLOW_REFUSALS +@pytest.mark.skipif(os.name == "nt", reason="POSIX anchors through parent descriptors") +def test_access_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._posix_directory + + @contextmanager + def swap_first(self, directory, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, directory, **kwargs) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.access(REL, os.R_OK) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + def test_stat_of_the_root(tmp_path): with FileHelper(tmp_path) as files: assert files.stat(tmp_path).st_ino == tmp_path.stat().st_ino From 68809dd1b07c76808fe56bdaf25892193f1327ff Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 18:22:37 +0000 Subject: [PATCH 06/18] fix(file-helper): check access with a plain faccessat follow_symlinks=False makes CPython pass AT_SYMLINK_NOFOLLOW, which the faccessat syscall cannot take. Without faccessat2 (Linux before 5.8, some seccomp profiles), glibc emulates it from mode bits, which misses read-only mounts and ACLs, and musl fails outright. The policy walk has already refused or resolved a leaf link, so the plain call is exact. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5Wip1LjrZn3fBQteLAq9 --- design/file-helper.md | 12 +++++++----- src/specify_cli/file_helper.py | 13 ++++++++----- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index d5637247f1..5dd7c43757 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -252,11 +252,13 @@ descriptor-relative or change their documented concurrency limitations. point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. - `access(path, mode)` answers `os.access` for an existing entry found and - anchored as `stat` finds it, without following links: POSIX checks relative - to the anchored parent descriptor, Windows pins the parent hierarchy first. - It uses the real user and group ids, so it also reports a read-only - filesystem or a file owned by someone else, which mode bits miss. It is - advisory, like `stat`. + anchored as `stat` finds it; the policy walk refuses or resolves a leaf link. + POSIX checks relative to the anchored parent descriptor with a plain + `faccessat` (no `AT_SYMLINK_NOFOLLOW`, which libc emulates from mode bits + where `faccessat2` is missing); Windows pins the parent hierarchy first. It + uses the real user and group ids, so it also reports a read-only filesystem + or a file owned by someone else, which mode bits miss. It is advisory, like + `stat`. - `canonical_root` is the root with OS and link aliases resolved, fixed on construction; it is the base that resolved operation paths share. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index af10152f1c..ab279af157 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -480,9 +480,10 @@ def canonical_root(self) -> Path: def access(self, path: Path | str, mode: int) -> bool: """Return whether ``os.access`` grants ``mode`` on an existing entry. - The entry is found and anchored as ``stat`` finds it, and links are not - followed. Like ``os.access``, the answer uses the real user and group - ids and is advisory: act through a descriptor and handle its errors. + The entry is found and anchored as ``stat`` finds it, so a leaf link is + refused or resolved by the normal policy walk. Like ``os.access``, the + answer uses the real user and group ids and is advisory: act through a + descriptor and handle its errors. """ destination = self._path(path) if destination == self._canonical_root: @@ -500,10 +501,12 @@ def access(self, path: Path | str, mode: int) -> bool: )) return os.access(destination, mode) unsupported = "Anchored access check is unsupported on this platform" - if os.access not in os.supports_dir_fd or os.access not in os.supports_follow_symlinks: + if os.access not in os.supports_dir_fd: raise OSError(errno.ENOTSUP, unsupported) with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: - return os.access(destination.name, mode, dir_fd=directory, follow_symlinks=False) + # No ``follow_symlinks=False``: the walk already handled a leaf link, + # and without ``faccessat2`` libc emulates that flag from mode bits. + return os.access(destination.name, mode, dir_fd=directory) def stat(self, path: Path | str) -> os.stat_result: """Return the metadata of an existing entry, resolving only allowed links.""" From 14f6190461f3846017fdf0ac8eaefed1b61d988d Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 18:31:01 +0000 Subject: [PATCH 07/18] test(file-helper): pin access to a plain faccessat Fails on the previous follow_symlinks=False call and passes now, so the flag cannot come back unnoticed. The docstring also says a leaf swapped for a link after the walk is followed. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5Wip1LjrZn3fBQteLAq9 --- src/specify_cli/file_helper.py | 7 ++++--- tests/test_file_helper_rewrite.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index ab279af157..963451f603 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -481,9 +481,10 @@ def access(self, path: Path | str, mode: int) -> bool: """Return whether ``os.access`` grants ``mode`` on an existing entry. The entry is found and anchored as ``stat`` finds it, so a leaf link is - refused or resolved by the normal policy walk. Like ``os.access``, the - answer uses the real user and group ids and is advisory: act through a - descriptor and handle its errors. + refused or resolved by the normal policy walk; a leaf swapped for a link + after that walk is followed. Like ``os.access``, the answer uses the + real user and group ids and is advisory: act through a descriptor and + handle its errors. """ destination = self._path(path) if destination == self._canonical_root: diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 672b6402ec..abc6a370de 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -114,6 +114,26 @@ def test_access_reports_the_windows_read_only_attribute(tmp_path): path.chmod(stat.S_IREAD | stat.S_IWRITE) +@pytest.mark.skipif(os.name == "nt", reason="POSIX checks through the parent descriptor") +def test_access_makes_a_plain_faccessat(tmp_path, monkeypatch): + # Without faccessat2, libc emulates AT_SYMLINK_NOFOLLOW from mode bits. + _seed(tmp_path) + calls = [] + real_access = os.access + + def access(path, mode, **kwargs): + calls.append(kwargs) + return real_access(path, mode, **kwargs) + + monkeypatch.setattr(os, "access", access) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {access}) + monkeypatch.setattr(os, "supports_follow_symlinks", os.supports_follow_symlinks - {real_access}) + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK) + assert len(calls) == 1 + assert "dir_fd" in calls[0] and "follow_symlinks" not in calls[0] + + def test_access_of_a_missing_entry_raises(tmp_path): with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): files.access("missing", os.R_OK) From 7d825c60c6f6be1ea64cf3b7da433c86fef54391 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 11:20:58 +0000 Subject: [PATCH 08/18] fix(file-helper): refuse unprotectable private creates, pin the inode during cleanup - create_private_bytes refuses a stream-qualified Windows leaf: a named NTFS stream shares its base file's security descriptor - the Windows create refuses a volume without FILE_PERSISTENT_ACLS (FAT, exFAT) before writing, removing the empty file through its handle - POSIX cleanup runs while a descriptor still holds the created inode, so a replacement cannot reuse its number and pass the identity check; a duplicate keeps it held across the final close - stat of the root no longer follows a link swapped in for it - the macOS ACL binding moves to _file_handles with the other native primitives - tests: named-stream refusal, ACL-less volume, inode pinned at the identity check, root replaced by a link, and a FIFO swapped in after open_rewrite's preflight that only the descriptor check refuses Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- design/file-helper.md | 23 +++-- src/specify_cli/_file_handles.py | 64 +++++++++++- src/specify_cli/file_helper.py | 76 ++++++-------- tests/test_file_helper_rewrite.py | 165 ++++++++++++++++++++++++++++-- 4 files changed, 262 insertions(+), 66 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 5dd7c43757..838f4e6244 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -248,7 +248,9 @@ descriptor-relative or change their documented concurrency limitations. walk: allowed contained links, including a leaf link, are resolved, and the resolved entry itself is not followed. The entry is queried relative to the anchored parent hierarchy, so a parent swapped after resolution cannot - redirect it. Missing entries raise `FileNotFoundError`. It is a + redirect it. The root itself is queried without following a link, so a root + replaced by a link after construction is not followed. Missing entries raise + `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. - `access(path, mode)` answers `os.access` for an existing entry found and @@ -301,13 +303,18 @@ descriptor-relative or change their documented concurrency limitations. with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security descriptor naming the current user as owner with a protected DACL granting only that user full access, so the content is never readable under an - inherited ACL. A failure after creation removes only the file this call - created: POSIX unlinks the name only while it still has the created file's - identity, checked immediately before the unlink rather than atomically with - it (an identity never read leaves the name in place), and Windows marks the - open handle for deletion. If that removal or the close fails, the original - exception is kept and carries a note naming the file. A Windows close failure - after a complete write leaves the file and says so in the note. + inherited ACL. It refuses a stream-qualified leaf (`file:stream`), since a + named NTFS stream shares its base file's security descriptor, and, before any + content is written, a volume without `FILE_PERSISTENT_ACLS` (FAT, exFAT), + which would drop the descriptor. A failure after creation removes only the + file this call created: POSIX unlinks the name only while it still has the + created file's identity, checked immediately before the unlink rather than + atomically with it (an identity never read leaves the name in place), with + the created inode held open until the check is done so its number cannot be + reused by a replacement; Windows marks the open handle for deletion. If that + removal or the close fails, the original exception is kept and carries a note + naming the file. A Windows close failure after a complete write leaves the + file and says so in the note. - `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 diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 1f655b3635..5641f0ceca 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -441,6 +441,39 @@ def _windows_stat(handle: int) -> os.stat_result: os.close(fd) +def _has_inherited_allow_entry(fd: int) -> bool: + """Whether a macOS file's ACL has an allow entry; deny entries grant nothing.""" + import ctypes + + libc = ctypes.CDLL(None, use_errno=True) + libc.acl_get_fd_np.restype = ctypes.c_void_p + libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] + libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] + libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] + libc.acl_free.argtypes = [ctypes.c_void_p] + acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED + if not acl: + code = ctypes.get_errno() + # No ACL, or a filesystem that cannot hold one. + if code in (errno.ENOENT, errno.ENOTSUP, errno.EOPNOTSUPP): + return False + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") + try: + entry = ctypes.c_void_p() + tag = ctypes.c_int() + which = 0 # ACL_FIRST_ENTRY, then ACL_NEXT_ENTRY + while libc.acl_get_entry(acl, which, ctypes.byref(entry)) == 0: + which = -1 + if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: + code = ctypes.get_errno() + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") + if tag.value == 1: # ACL_EXTENDED_ALLOW + return True + return False + finally: + libc.acl_free(acl) + + @contextmanager def windows_read_fd(handle: int) -> Iterator[int]: """Read the validated object through an independently owned duplicate.""" @@ -515,6 +548,7 @@ def _windows_creation_attributes() -> int: _TOKEN_USER = 1 _ERROR_INSUFFICIENT_BUFFER = 122 _SDDL_REVISION_1 = 1 +_FILE_PERSISTENT_ACLS = 0x8 def _windows_create_private_fd(path: Path) -> int: @@ -522,7 +556,9 @@ def _windows_create_private_fd(path: Path) -> int: The owner and protected access-control list are set by the call that creates the file, and nothing is shared until it closes, so the content is - never readable under an inherited list. Returns a binary CRT descriptor. + never readable under an inherited list. A volume that does not persist + access-control lists would drop that list, so the empty file is removed and + the call refused. Returns a binary CRT descriptor. """ import ctypes import msvcrt @@ -546,6 +582,7 @@ def _windows_create_private_fd(path: Path) -> int: finally: kernel.LocalFree(descriptor) try: + _require_persistent_acls(kernel, handle, path) return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) except BaseException as error: # No descriptor reaches the caller, so remove the empty file here. With @@ -567,6 +604,25 @@ class FileDispositionInfo(ctypes.Structure): raise +def _require_persistent_acls(kernel, handle: int, path: Path) -> None: + """Refuse a volume that drops security descriptors, such as FAT or exFAT.""" + import ctypes + from ctypes import wintypes + + flags = wintypes.DWORD() + if not kernel.GetVolumeInformationByHandleW( + handle, None, 0, None, None, ctypes.byref(flags), None, 0, + ): + error = ctypes.WinError(ctypes.get_last_error()) + error.add_note(f"Could not check that the volume holding {path} keeps access-control lists") + raise error + if not flags.value & _FILE_PERSISTENT_ACLS: + raise PermissionError( + errno.EACCES, + f"Refusing to write {path}: its volume does not keep access-control lists", + ) + + def _windows_owner_only_sddl() -> str: """The security descriptor, as SDDL, private files are created with.""" sid = _windows_current_user_sid() @@ -639,6 +695,12 @@ class SecurityAttributes(ctypes.Structure): wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, ] kernel.SetFileInformationByHandle.restype = wintypes.BOOL + kernel.GetVolumeInformationByHandleW.argtypes = [ + wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), + ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, + wintypes.DWORD, + ] + kernel.GetVolumeInformationByHandleW.restype = wintypes.BOOL advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [ wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), wintypes.LPVOID, ] diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 963451f603..f36fd9eee2 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -16,10 +16,10 @@ from weakref import finalize from specify_cli._file_handles import ( - _WindowsFileIdentity, _windows_create_private_fd, _windows_delete, - _windows_directory_names, _windows_entry, _windows_file_id, _windows_handle, - _windows_mode, _windows_overwrite_fd, _windows_readlink, _windows_stat, - rename_noreplace, windows_read_fd, + _WindowsFileIdentity, _has_inherited_allow_entry, _windows_create_private_fd, + _windows_delete, _windows_directory_names, _windows_entry, _windows_file_id, + _windows_handle, _windows_mode, _windows_overwrite_fd, _windows_readlink, + _windows_stat, rename_noreplace, windows_read_fd, ) @@ -72,39 +72,6 @@ def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: ) -def _has_inherited_allow_entry(fd: int) -> bool: - """Whether a macOS file's ACL has an allow entry; deny entries grant nothing.""" - import ctypes - - libc = ctypes.CDLL(None, use_errno=True) - libc.acl_get_fd_np.restype = ctypes.c_void_p - libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] - libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] - libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] - libc.acl_free.argtypes = [ctypes.c_void_p] - acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED - if not acl: - code = ctypes.get_errno() - # No ACL, or a filesystem that cannot hold one. - if code in (errno.ENOENT, errno.ENOTSUP, errno.EOPNOTSUPP): - return False - raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") - try: - entry = ctypes.c_void_p() - tag = ctypes.c_int() - which = 0 # ACL_FIRST_ENTRY, then ACL_NEXT_ENTRY - while libc.acl_get_entry(acl, which, ctypes.byref(entry)) == 0: - which = -1 - if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: - code = ctypes.get_errno() - raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") - if tag.value == 1: # ACL_EXTENDED_ALLOW - return True - return False - finally: - libc.acl_free(acl) - - def _full_fsync(fd: int) -> None: """Flush to stable storage; macOS ``fsync`` alone leaves data in the drive cache.""" os.fsync(fd) @@ -513,7 +480,7 @@ def stat(self, path: Path | str) -> os.stat_result: """Return the metadata of an existing entry, resolving only allowed links.""" destination = self._path(path) if destination == self._canonical_root: - return os.stat(destination) + return os.stat(destination, follow_symlinks=False) # Stat through the anchored parent so a swapped ancestor cannot redirect it. if os.name == "nt": parts = destination.relative_to(self._canonical_root).parts @@ -727,6 +694,10 @@ def create_private_bytes(self, path: Path | str, content: bytes) -> None: A failure after creation removes only the file this call created. """ + if os.name == "nt" and ":" in Path(path).name: + # A named NTFS stream shares its base file's security descriptor, so + # the owner-only descriptor would not apply to it. + raise UnsupportedPathError(f"Refusing to create a named stream: {path}") destination = self._path(path, allow_missing=True, follow_leaf=False) try: self._entry_mode(destination) @@ -746,23 +717,34 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: flags |= getattr(os, "O_CLOEXEC", 0) fd = os.open(name, flags, 0o600, dir_fd=directory) created: os.stat_result | None = None + pin: int | None = None try: created = os.fstat(fd) + # Holds the created inode until any cleanup is done, even if the final + # close releases ``fd``, so a replacement cannot reuse its number and + # pass the identity check. + pin = os.dup(fd) _require_owner_only(fd, created, name) _write_all(fd, content) _full_fsync(fd) + closing, fd = fd, -1 + os.close(closing) except BaseException as error: try: - os.close(fd) - except OSError as close_error: - error.add_note(f"Could not close {name}: {close_error}") - _remove_created(directory, name, created, error) - raise - try: - os.close(fd) - except BaseException as error: - _remove_created(directory, name, created, error) + _remove_created(directory, name, created, error) + finally: + if fd >= 0: + try: + os.close(fd) + except OSError as close_error: + error.add_note(f"Could not close {name}: {close_error}") raise + finally: + if pin is not None: + try: + os.close(pin) + except OSError: + pass # A duplicate holds no buffered data. # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. try: parent = os.open( diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index abc6a370de..498537bf82 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -12,7 +12,7 @@ from specify_cli import _file_handles from specify_cli.file_helper import ( - FileHelper, SymlinkDeniedError, UnsupportedPathError, + FileHelper, FileHelperError, SymlinkDeniedError, UnsupportedPathError, ) @@ -522,16 +522,10 @@ def fail(handle, flags): assert (tmp_path / REL).read_bytes() == b"content" -@pytest.mark.parametrize("marked", [True, False, None]) -def test_windows_private_fd_removes_its_file_through_the_handle_if_no_descriptor_is_made( - tmp_path, monkeypatch, marked -): - # Simulates the Windows calls, so this runs everywhere; the test above - # makes the real ones. +def _simulate_windows_create(monkeypatch, calls, *, marked=True, volume_flags=0x8): + """Fake the Windows calls ``_windows_create_private_fd`` makes, so it runs everywhere.""" import ctypes - calls = [] - class Attributes(ctypes.Structure): _fields_ = [("nLength", ctypes.c_ulong), ("descriptor", ctypes.c_void_p), ("inherit", ctypes.c_int)] @@ -541,6 +535,10 @@ def CreateFileW(self, path, access, share, attributes, disposition, flags, templ calls.append(("CreateFileW", access, share, disposition)) return 1234 + def GetVolumeInformationByHandleW(self, handle, *args): + args[4]._obj.value = volume_flags # lpFileSystemFlags + return 1 + def SetFileInformationByHandle(self, handle, kind, info, size): calls.append(("SetFileInformationByHandle", handle, kind, bytes(info._obj))) if marked is None: @@ -559,6 +557,7 @@ def ConvertStringSecurityDescriptorToSecurityDescriptorW(self, *args): return 1 def open_osfhandle(handle, flags): + calls.append(("open_osfhandle", handle)) raise OSError("too many open files") monkeypatch.setattr( @@ -569,18 +568,44 @@ def open_osfhandle(handle, flags): monkeypatch.setattr(ctypes, "WinError", lambda code=None: OSError(code, "denied"), raising=False) monkeypatch.setitem(sys.modules, "msvcrt", types.SimpleNamespace(open_osfhandle=open_osfhandle)) monkeypatch.setattr(os, "O_BINARY", 0x8000, raising=False) + + +@pytest.mark.parametrize("marked", [True, False, None]) +def test_windows_private_fd_removes_its_file_through_the_handle_if_no_descriptor_is_made( + tmp_path, monkeypatch, marked +): + # Simulates the Windows calls, so this runs everywhere; the test above + # makes the real ones. + calls = [] + _simulate_windows_create(monkeypatch, calls, marked=marked) with pytest.raises(OSError, match="too many open files") as raised: _file_handles._windows_create_private_fd(tmp_path / "file") delete, create_new = 0x00010000, 1 access, share, disposition = calls[0][1:] assert access & delete and share == 0 and disposition == create_new # FileDispositionInfo with DeleteFile set, before the handle closes. - assert calls[1:] == [("SetFileInformationByHandle", 1234, 4, b"\x01"), ("CloseHandle", 1234)] + assert calls[1:] == [ + ("open_osfhandle", 1234), + ("SetFileInformationByHandle", 1234, 4, b"\x01"), + ("CloseHandle", 1234), + ] # If it cannot be marked, the error names the empty file so it can be deleted. noted = any(str(tmp_path / "file") in note for note in getattr(raised.value, "__notes__", [])) assert noted is not bool(marked) +def test_windows_private_fd_refuses_a_volume_without_persistent_acls(tmp_path, monkeypatch): + # FAT and exFAT accept the security descriptor but do not keep it. + calls = [] + _simulate_windows_create(monkeypatch, calls, volume_flags=0) + with pytest.raises(PermissionError, match="does not keep access-control lists"): + _file_handles._windows_create_private_fd(tmp_path / "file") + # Refused before a descriptor exists; the empty file is removed through its handle. + assert [call[0] for call in calls] == [ + "CreateFileW", "SetFileInformationByHandle", "CloseHandle", + ] + + @pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path): (tmp_path / "parent").mkdir() @@ -870,3 +895,123 @@ def test_stat_refuses_a_junctioned_parent(tmp_path): ) with FileHelper(project) as files, pytest.raises(UnsupportedPathError): files.stat(REL) + + +@pytest.mark.skipif(sys.platform != "win32", reason="NTFS named streams") +def test_windows_create_private_bytes_refuses_a_named_stream(tmp_path): + # A stream shares its base file's security descriptor, so it cannot be owner-only. + path = _seed(tmp_path, b"base") + with FileHelper(tmp_path) as files, pytest.raises(FileHelperError): + files.create_private_bytes(REL + ":backup", b"secret") + assert path.read_bytes() == b"base" + with pytest.raises(FileNotFoundError): + open(f"{path}:backup", "rb").close() + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_does_not_follow_a_root_replaced_by_a_symlink(tmp_path): + root = tmp_path / "root" + root.mkdir() + other = tmp_path / "other" + other.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.symlink_to(other, target_is_directory=True) + assert stat.S_ISLNK(files.stat(".").st_mode) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_nonregular_leaf_swapped_in_after_preflight(tmp_path, monkeypatch): + # A FIFO with a reader opens for writing, so only the descriptor check can refuse it. + path = _seed(tmp_path) + real_open = os.open + original = FileHelper._overwrite_descriptor + leaf: list[int] = [] + readers: list[int] = [] + + def open_(name, flags, *args, **kwargs): + fd = real_open(name, flags, *args, **kwargs) + if os.fspath(name) == "file": + leaf.append(fd) + return fd + + @contextmanager + def swap_first(self, destination, **kwargs): + path.unlink() + os.mkfifo(path) + readers.append(real_open(path, os.O_RDONLY | os.O_NONBLOCK)) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + entered = False + try: + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + entered = True + finally: + for fd in readers: + os.close(fd) + monkeypatch.undo() + assert not entered + assert len(leaf) == 1 + with pytest.raises(OSError) as raised: + os.fstat(leaf[0]) + assert raised.value.errno == errno.EBADF + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("step", ["write", "fsync", "close"]) +def test_posix_create_private_bytes_keeps_the_inode_pinned_during_cleanup( + tmp_path, monkeypatch, step +): + # Once nothing holds the created inode its number can be reused, and a + # replacement could then pass the identity check and be removed. + (tmp_path / "parent").mkdir() + real_open, real_dup, real_close, real_stat = os.open, os.dup, os.close, os.stat + real_step = {"write": os.write, "fsync": os.fsync, "close": real_close}[step] + pinned: set[int] = set() + leaf: list[int] = [] + pinned_at_check: list[bool] = [] + + def open_(name, flags, *args, **kwargs): + fd = real_open(name, flags, *args, **kwargs) + if os.fspath(name) == "file": + leaf.append(fd) + pinned.add(fd) + return fd + + def dup(fd): + copy = real_dup(fd) + if fd in pinned: + pinned.add(copy) + return copy + + def close(fd): + pinned.discard(fd) + real_close(fd) + if step == "close" and leaf and fd == leaf[0]: + raise OSError("disk full") + + def fail(fd, *args): + if leaf and fd == leaf[0]: + raise OSError("disk full") + return real_step(fd, *args) + + def stat_(name, *args, **kwargs): + if os.fspath(name) == "file" and kwargs.get("dir_fd") is not None: + pinned_at_check.append(bool(pinned)) + return real_stat(name, *args, **kwargs) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "dup", dup) + monkeypatch.setattr(os, "stat", stat_) + monkeypatch.setattr(os, "close", close) + if step != "close": + monkeypatch.setattr(os, step, fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert pinned_at_check == [True] + assert not (tmp_path / REL).exists() From e5c0597698d7ff67d161b946c12ec044f6ea3357 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 16:03:04 +0000 Subject: [PATCH 09/18] fix(file-helper): refuse a private create owned by another user Also report PowerShell's stderr when the Windows ACL test cannot read the descriptor. Co-Authored-By: Claude Sonnet 5.5 Assisted-by: Claude Code (model: claude-sonnet-5-5, autonomous) Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- src/specify_cli/file_helper.py | 10 +++++++++- tests/test_file_helper_rewrite.py | 13 ++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index a8789cfe9c..9643474d26 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -52,7 +52,8 @@ def _remove_created( def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: """Refuse a new, still-empty file that someone other than its owner can open. - Group or other mode bits mean the filesystem ignored the creation mode. On + Group or other mode bits mean the filesystem ignored the creation mode, and a + different owner means it mapped ownership. On macOS, a parent's inheritable ACEs are added to a new file whatever its mode, and they cannot be withheld from a directory-relative create, so such a file is refused before any content reaches it. NFSv4-style inherited ACLs on other @@ -64,6 +65,13 @@ def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: f"Filesystem did not create {name} owner-only " f"(mode {stat.S_IMODE(info.st_mode):o})", ) + # A mapped or fixed-ownership filesystem can give the file to another user, + # who could then read the private content however tight its mode is. + if hasattr(os, "geteuid") and info.st_uid != os.geteuid(): + raise PermissionError( + errno.EACCES, + f"Filesystem created {name} owned by uid {info.st_uid}, not the caller", + ) if sys.platform == "darwin" and _has_inherited_allow_entry(fd): raise PermissionError( errno.EACCES, diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 498537bf82..27b149cf1a 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -297,6 +297,16 @@ def test_create_private_bytes_is_owner_only(tmp_path): assert stat.S_IMODE((tmp_path / REL).stat().st_mode) & 0o077 == 0 +@pytest.mark.skipif(os.name == "nt", reason="POSIX ownership") +def test_create_private_bytes_refuses_a_file_owned_by_another_user(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + monkeypatch.setattr(os, "geteuid", lambda: os.stat(tmp_path).st_uid + 1) + with FileHelper(tmp_path) as files, pytest.raises(PermissionError) as raised: + files.create_private_bytes(REL, b"private") + assert "owned by uid" in str(raised.value) + assert not (tmp_path / REL).exists() + + def test_create_private_bytes_needs_an_existing_parent(tmp_path): with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): files.create_private_bytes(REL, b"content") @@ -614,8 +624,9 @@ def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path) result = subprocess.run( ["powershell", "-NoProfile", "-Command", f"(Get-Acl -LiteralPath '{tmp_path / REL}').Sddl"], - check=True, capture_output=True, text=True, + capture_output=True, text=True, ) + assert result.returncode == 0, result.stderr sddl = result.stdout.strip() sid = _file_handles._windows_current_user_sid() assert f"O:{sid}" in sddl From 6e9eb8448b6b6f37b65c263ec42a3cdf174159e6 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 16:16:37 +0000 Subject: [PATCH 10/18] fix(file-helper): name a replaced partial file instead of skipping it silently When cleanup after a failed private create finds that another writer has replaced the leaf, leave it and add a note naming it to the raised error. Document the stat-to-unlink window as an accepted residual race: POSIX has no unlink-if-inode, and both calls already share the directory descriptor with the created inode pinned. The Windows ACL test now prefers pwsh and drops PSModulePath, so Windows PowerShell does not try to load PowerShell 7's Microsoft.PowerShell.Security for Get-Acl. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- design/file-helper.md | 5 ++++- src/specify_cli/file_helper.py | 19 ++++++++++++++++--- tests/test_file_helper_rewrite.py | 15 ++++++++++++--- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index af163aec8a..5614c98ea6 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -317,7 +317,10 @@ descriptor-relative or change their documented concurrency limitations. created file's identity, checked immediately before the unlink rather than atomically with it (an identity never read leaves the name in place), with the created inode held open until the check is done so its number cannot be - reused by a replacement; Windows marks the open handle for deletion. If that + reused by a replacement. A name that already holds another file is left, and + the note names it; a replacement swapped in between the check and the unlink + is an accepted residual race, since POSIX has no unlink-if-identity primitive. + Windows marks the open handle for deletion. If that removal or the close fails, the original exception is kept and carries a note naming the file. A Windows close failure after a complete write leaves the file and says so in the note. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 9643474d26..117ef5c65c 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -37,14 +37,27 @@ def _remove_created( directory: int, name: str, created: os.stat_result | None, error: BaseException ) -> None: - """Unlink ``name`` if it still has the created file's identity (best effort).""" + """Unlink ``name`` if it still has the created file's identity (best effort). + + A name that now holds a different file is left in place and named in a note + on ``error``, so the caller learns that cleanup did not happen. + """ if created is None: error.add_note(f"Left {name}, which may be empty; delete it before retrying") return try: current = os.stat(name, dir_fd=directory, follow_symlinks=False) - if (current.st_dev, current.st_ino) == (created.st_dev, created.st_ino): - os.unlink(name, dir_fd=directory) + if (current.st_dev, current.st_ino) != (created.st_dev, created.st_ino): + error.add_note( + f"Left {name}: another writer replaced the partial file, so it was not removed" + ) + return + # Accepted residual race: POSIX has no unlink-if-inode, so a writer that + # swaps the leaf between this stat and the unlink loses its file. Both + # calls go through the same directory descriptor with nothing between + # them, and the caller pins the created inode so its number cannot be + # reused by a replacement that would then pass the check above. + os.unlink(name, dir_fd=directory) except OSError as cleanup_error: error.add_note(f"Could not remove partial file {name}: {cleanup_error}") diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 27b149cf1a..47c8882620 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -2,6 +2,7 @@ import errno import os +import shutil import stat import subprocess import sys @@ -420,10 +421,14 @@ def replace_then_fail(fd): return real_fsync(fd) monkeypatch.setattr(os, "fsync", replace_then_fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: files.create_private_bytes(REL, b"content") monkeypatch.undo() assert (tmp_path / REL).read_bytes() == b"someone else's" + # The caller is told the name was left, rather than cleanup failing silently. + assert any( + "Left file" in note and "not removed" in note for note in raised.value.__notes__ + ) @pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") @@ -621,10 +626,14 @@ def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path) (tmp_path / "parent").mkdir() with FileHelper(tmp_path) as files: files.create_private_bytes(REL, b"content") + # A step's PowerShell 7 puts its own module paths in PSModulePath, and Windows + # PowerShell then fails to load Microsoft.PowerShell.Security for Get-Acl. + # Prefer pwsh, and let either shell rebuild its default module path. + env = {key: value for key, value in os.environ.items() if key.upper() != "PSMODULEPATH"} result = subprocess.run( - ["powershell", "-NoProfile", "-Command", + [shutil.which("pwsh") or "powershell", "-NoProfile", "-NonInteractive", "-Command", f"(Get-Acl -LiteralPath '{tmp_path / REL}').Sddl"], - capture_output=True, text=True, + capture_output=True, text=True, env=env, ) assert result.returncode == 0, result.stderr sddl = result.stdout.strip() From e097fe7b19a9c83a37363e56e5ec908da8e45827 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 16:22:32 +0000 Subject: [PATCH 11/18] fix(file-helper): note a moved partial file and report a failed final close Cleanup that finds nothing at the created name now says the partial file may have been moved, instead of reporting a removal failure, and a replaced name's note says the partial file may remain elsewhere. After a complete write, the pinned duplicate is the file's last descriptor, so a failure closing it now raises with a note rather than being discarded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- design/file-helper.md | 5 ++- src/specify_cli/file_helper.py | 48 ++++++++++++++-------- tests/test_file_helper_rewrite.py | 67 +++++++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 17 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 5614c98ea6..cc8f05634c 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -318,7 +318,10 @@ descriptor-relative or change their documented concurrency limitations. atomically with it (an identity never read leaves the name in place), with the created inode held open until the check is done so its number cannot be reused by a replacement. A name that already holds another file is left, and - the note names it; a replacement swapped in between the check and the unlink + the note names it; a name found empty gets a note that the partial file may + have been moved rather than a removal failure. A failed close of that held + descriptor after a complete write raises, leaving the file and saying so in a + note. A replacement swapped in between the check and the unlink is an accepted residual race, since POSIX has no unlink-if-identity primitive. Windows marks the open handle for deletion. If that removal or the close fails, the original exception is kept and carries a note diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 117ef5c65c..d36928cfd3 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -47,11 +47,22 @@ def _remove_created( return try: current = os.stat(name, dir_fd=directory, follow_symlinks=False) - if (current.st_dev, current.st_ino) != (created.st_dev, created.st_ino): - error.add_note( - f"Left {name}: another writer replaced the partial file, so it was not removed" - ) - return + except FileNotFoundError: + error.add_note( + f"Found nothing at {name} to remove: the partial file was moved or deleted " + "by another process and may still exist elsewhere" + ) + return + except OSError as cleanup_error: + error.add_note(f"Could not remove partial file {name}: {cleanup_error}") + return + if (current.st_dev, current.st_ino) != (created.st_dev, created.st_ino): + error.add_note( + f"Left {name}: another writer replaced the partial file, so it was not removed; " + "the partial file may still exist under another name" + ) + return + try: # Accepted residual race: POSIX has no unlink-if-inode, so a writer that # swaps the leaf between this stat and the unlink loses its file. Both # calls go through the same directory descriptor with nothing between @@ -769,18 +780,23 @@ def _posix_create_private(directory: int, name: str, content: bytes) -> None: try: _remove_created(directory, name, created, error) finally: - if fd >= 0: - try: - os.close(fd) - except OSError as close_error: - error.add_note(f"Could not close {name}: {close_error}") + for descriptor in (fd, -1 if pin is None else pin): + if descriptor >= 0: + try: + os.close(descriptor) + except OSError as close_error: + error.add_note(f"Could not close {name}: {close_error}") + raise + # The duplicate is now the file's last descriptor, so its close is the + # one that reports a deferred write error (NFS, for example). + try: + os.close(pin) + except OSError as close_error: + close_error.add_note( + f"Wrote and flushed {name}, but closing it failed; check its content " + "before relying on it" + ) raise - finally: - if pin is not None: - try: - os.close(pin) - except OSError: - pass # A duplicate holds no buffered data. # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. try: parent = os.open( diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 47c8882620..55bf60e73a 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -795,6 +795,73 @@ def fstat(fd): assert any("delete it before retrying" in note for note in raised.value.__notes__) +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("replaced", [False, True]) +def test_posix_create_private_bytes_notes_a_partial_file_moved_before_cleanup( + tmp_path, monkeypatch, replaced +): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def move_then_fail(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + (tmp_path / REL).rename(tmp_path / "parent" / "moved") + if replaced: + (tmp_path / REL).write_bytes(b"someone else's") + raise OSError("disk full") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", move_then_fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + notes = raised.value.__notes__ + # Neither case is a removal failure, and both say the partial file may remain. + assert not any("Could not remove" in note for note in notes) + assert any("may still exist" in note for note in notes) + assert (tmp_path / "parent" / "moved").exists() + if replaced: + assert (tmp_path / REL).read_bytes() == b"someone else's" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_reports_a_failed_close_of_the_last_descriptor( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_open, real_dup, real_close = os.open, os.dup, os.close + leaf: list[int] = [] + duplicates: list[int] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def dup(fd): + copy_ = real_dup(fd) + if fd in leaf: + duplicates.append(copy_) + return copy_ + + def close(fd): + real_close(fd) + if fd in duplicates: + duplicates.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "dup", dup) + monkeypatch.setattr(os, "close", close) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="Input/output") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("check its content" in note for note in raised.value.__notes__) + # The write completed, so the file is left for the caller to inspect. + assert (tmp_path / REL).read_bytes() == b"content" + + @pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") def test_posix_create_private_bytes_keeps_the_write_error_when_close_also_fails( tmp_path, monkeypatch From a53bb54bc9eb03ea024c9465b2dc72d0ed74cad9 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 16:37:54 +0000 Subject: [PATCH 12/18] test(file-helper): compare the Windows private-file ACL by resolved SID With PSModulePath fixed, Get-Acl now runs on the runner, which showed the ACL is right (owner and one protected full-control entry for the user) but SDDL abbreviates the built-in Administrator's SID to "LA", so the string match failed. Read the owner, protection flag and access rules as SIDs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- tests/test_file_helper_rewrite.py | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 55bf60e73a..1cb726390a 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -630,18 +630,26 @@ def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path) # PowerShell then fails to load Microsoft.PowerShell.Security for Get-Acl. # Prefer pwsh, and let either shell rebuild its default module path. env = {key: value for key, value in os.environ.items() if key.upper() != "PSMODULEPATH"} + # SDDL abbreviates well-known accounts (the built-in Administrator is "LA"), + # so compare resolved SIDs rather than the descriptor string. + script = ( + f"$acl = Get-Acl -LiteralPath '{tmp_path / REL}'; " + "$sid = [System.Security.Principal.SecurityIdentifier]; " + "$acl.GetOwner($sid).Value; " + "$acl.AreAccessRulesProtected; " + "$acl.GetAccessRules($true, $true, $sid) | ForEach-Object { " + "\"$($_.IdentityReference.Value) $($_.AccessControlType) $($_.FileSystemRights)\" }" + ) result = subprocess.run( - [shutil.which("pwsh") or "powershell", "-NoProfile", "-NonInteractive", "-Command", - f"(Get-Acl -LiteralPath '{tmp_path / REL}').Sddl"], + [shutil.which("pwsh") or "powershell", "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, env=env, ) assert result.returncode == 0, result.stderr - sddl = result.stdout.strip() + owner, protected, *rules = result.stdout.strip().splitlines() sid = _file_handles._windows_current_user_sid() - assert f"O:{sid}" in sddl - dacl = sddl.split("D:", 1)[1] - assert dacl.startswith("P") - assert dacl.count("(") == 1 and f";;;{sid})" in dacl + assert owner == sid + assert protected == "True" + assert rules == [f"{sid} Allow FullControl"] # Review regressions From 59728c402e539556d1606956b674682fa0558d97 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 22:10:48 +0000 Subject: [PATCH 13/18] feat(file-helper): add rewrite_descriptor and document the owner refusal - FileHelper.rewrite_descriptor(fd, content) replaces an open file's content from offset 0, truncates after writing and flushes with the same write loop and F_FULLFSYNC policy as create_private_bytes, so a caller's in-place rewrite does not carry its own copy of either - design/file-helper.md documents it, and that create_private_bytes also refuses a file the filesystem gave to another uid - tests: replace from any offset, flush after writing, a write making no progress, and which F_FULLFSYNC errors are tolerated Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- design/file-helper.md | 17 +++++++-- src/specify_cli/file_helper.py | 16 ++++++++ tests/test_file_helper_rewrite.py | 61 +++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 4 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index cc8f05634c..73c8b17c7d 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -296,10 +296,12 @@ descriptor-relative or change their documented concurrency limitations. returning. It shares `create_bytes`'s policy walk, no-follow `lstat` preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` relative to the anchored parent. Before any content is written, it refuses - (removing the still-empty file) when the file came out with group or other - mode bits, which means the filesystem ignored the mode, or, on macOS, with - inherited ACL allow entries, which a directory-relative create cannot - withhold (inherited deny entries are accepted). Linux default ACLs are + (removing the still-empty file, with `PermissionError`) when the file came + out with group or other mode bits, which means the filesystem ignored the + mode; when it is owned by a uid other than the caller's effective uid, which + means the filesystem mapped ownership (some network and container mounts); + or, on macOS, with inherited ACL allow entries, which a directory-relative + create cannot withhold (inherited deny entries are accepted). Linux default ACLs are bounded by the mask the mode sets. NFSv4-style inherited ACLs on other systems are not inspected. It writes and `fsync`s through that one descriptor, adding `F_FULLFSYNC` on macOS where the filesystem supports it, @@ -378,6 +380,13 @@ descriptor-relative or change their documented concurrency limitations. `closefd=False`. Writing, truncating, flushing and any rollback belong to the caller; nothing is written or truncated by the helper. There is no newline translation on either platform. +- `rewrite_descriptor(fd, content)` (static) replaces the whole content of an + open writable descriptor, such as one from `open_rewrite`: it seeks to offset + 0, writes every byte, truncates to the new length after writing, then + `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. It + shares that write loop and flush policy with `create_private_bytes`, so a + caller's in-place rewrite and its private backup have the same durability. + A failure can leave partial content; restoring it is the caller's job. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. Recursive enumeration and each removal use anchored diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index d36928cfd3..b5788862d0 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -897,6 +897,22 @@ def open_rewrite(self, path: Path | str) -> Iterator[int]: os.set_blocking(fd, True) yield fd + @staticmethod + def rewrite_descriptor(fd: int, content: bytes) -> None: + """Replace everything in the open file ``fd`` with ``content``, flushed to disk. + + For a descriptor from ``open_rewrite``. It writes from offset 0 whatever + the current offset, truncates after writing (so the old bytes' space is + reused rather than freed first), then ``fsync``s, adding ``F_FULLFSYNC`` + on macOS where the filesystem supports it: the same write and flush that + ``create_private_bytes`` uses. A failure can leave partial content; + restoring it is the caller's job. + """ + os.lseek(fd, 0, os.SEEK_SET) + _write_all(fd, content) + os.ftruncate(fd, len(content)) + _full_fsync(fd) + @contextmanager def _overwrite_descriptor(self, destination: Path, *, create: bool = True) -> Iterator[int]: """Anchor the resolved hierarchy before opening a non-truncating leaf.""" diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 1cb726390a..2e374402f7 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1110,3 +1110,64 @@ def stat_(name, *args, **kwargs): monkeypatch.undo() assert pinned_at_check == [True] assert not (tmp_path / REL).exists() + + +def test_rewrite_descriptor_replaces_and_truncates_from_any_offset(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + inode = target.stat().st_ino + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + os.lseek(fd, 0, os.SEEK_END) + FileHelper.rewrite_descriptor(fd, b"short\n") + assert target.read_bytes() == b"short\n" + assert target.stat().st_ino == inode + + +def test_rewrite_descriptor_flushes_after_writing(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + seen = [] + real_fsync = os.fsync + + def fsync(fd): + seen.append(os.fstat(fd).st_size) + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + FileHelper.rewrite_descriptor(fd, b"newer\n") + assert seen == [len(b"newer\n")] + + +def test_rewrite_descriptor_raises_when_a_write_makes_no_progress(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + monkeypatch.setattr(os, "write", lambda fd, data: 0) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + with pytest.raises(OSError, match="no progress"): + FileHelper.rewrite_descriptor(fd, b"new\n") + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") +@pytest.mark.parametrize("code, raises", [(errno.ENOTSUP, False), (errno.EIO, True)]) +def test_rewrite_descriptor_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): + import fcntl + + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + real_fcntl = fcntl.fcntl + + def fail(fd, command, *args): + if command == fcntl.F_FULLFSYNC: + raise OSError(code, os.strerror(code)) + return real_fcntl(fd, command, *args) + + monkeypatch.setattr(fcntl, "fcntl", fail) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + if raises: + with pytest.raises(OSError): + FileHelper.rewrite_descriptor(fd, b"new\n") + else: + FileHelper.rewrite_descriptor(fd, b"new\n") + if not raises: + assert target.read_bytes() == b"new\n" From 22b4adb4c344b39735a0dc97574e943dbd809b88 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 20 Nov 2026 22:32:14 +0000 Subject: [PATCH 14/18] fix(file-helper): refuse an append-mode descriptor in rewrite_descriptor - an O_APPEND descriptor ignores the seek, so the truncate that follows cut the new bytes off; it is now refused with EINVAL before anything is written, and the contract is limited to open_rewrite descriptors - tests: the append-mode refusal (fails before the change), short writes retried by rewrite_descriptor and create_private_bytes, and a short write followed by an error removing the private file Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioDHJd7GtWMKZNgrHC --- design/file-helper.md | 10 +++--- src/specify_cli/file_helper.py | 19 +++++++---- tests/test_file_helper_rewrite.py | 57 +++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+), 10 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 73c8b17c7d..b35937e9cb 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -380,10 +380,12 @@ descriptor-relative or change their documented concurrency limitations. `closefd=False`. Writing, truncating, flushing and any rollback belong to the caller; nothing is written or truncated by the helper. There is no newline translation on either platform. -- `rewrite_descriptor(fd, content)` (static) replaces the whole content of an - open writable descriptor, such as one from `open_rewrite`: it seeks to offset - 0, writes every byte, truncates to the new length after writing, then - `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. It +- `rewrite_descriptor(fd, content)` (static) replaces the whole content of a + descriptor returned by `open_rewrite`: it seeks to offset 0, writes every + byte (retrying short writes), truncates to the new length after writing, then + `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. An + append-mode descriptor is refused (`EINVAL`) before anything is written, + since its writes ignore the seek and the truncate would cut them off. It shares that write loop and flush policy with `create_private_bytes`, so a caller's in-place rewrite and its private backup have the same durability. A failure can leave partial content; restoring it is the caller's job. diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index b5788862d0..fbf99d3902 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -901,13 +901,20 @@ def open_rewrite(self, path: Path | str) -> Iterator[int]: def rewrite_descriptor(fd: int, content: bytes) -> None: """Replace everything in the open file ``fd`` with ``content``, flushed to disk. - For a descriptor from ``open_rewrite``. It writes from offset 0 whatever - the current offset, truncates after writing (so the old bytes' space is - reused rather than freed first), then ``fsync``s, adding ``F_FULLFSYNC`` - on macOS where the filesystem supports it: the same write and flush that - ``create_private_bytes`` uses. A failure can leave partial content; - restoring it is the caller's job. + Only for a descriptor from ``open_rewrite``. It writes from offset 0 + whatever the current offset, truncates after writing (so the old bytes' + space is reused rather than freed first), then ``fsync``s, adding + ``F_FULLFSYNC`` on macOS where the filesystem supports it: the same + write and flush that ``create_private_bytes`` uses. An append-mode + descriptor is refused before anything is written, since its writes + ignore the seek and the truncate would then cut them off. A failure can + leave partial content; restoring it is the caller's job. """ + if os.name != "nt": + import fcntl + + if fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_APPEND: + raise OSError(errno.EINVAL, "Refusing to rewrite through an append-mode descriptor") os.lseek(fd, 0, os.SEEK_SET) _write_all(fd, content) os.ftruncate(fd, len(content)) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 2e374402f7..bf8e4297dd 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1171,3 +1171,60 @@ def fail(fd, command, *args): FileHelper.rewrite_descriptor(fd, b"new\n") if not raises: assert target.read_bytes() == b"new\n" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX append-mode descriptors") +def test_rewrite_descriptor_refuses_an_append_mode_descriptor(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"original bytes") + fd = os.open(target, os.O_WRONLY | os.O_APPEND) + try: + with pytest.raises(OSError, match="append-mode"): + FileHelper.rewrite_descriptor(fd, b"new") + finally: + os.close(fd) + assert target.read_bytes() == b"original bytes" + + +def _short_writes(monkeypatch, fail_after=None): + """Make ``os.write`` accept at most 3 bytes a call, optionally failing after some calls.""" + real_write = os.write + calls = [] + + def write(fd, data): + calls.append(fd) + if fail_after is not None and len(calls) > fail_after: + raise OSError(errno.EIO, "I/O error") + return real_write(fd, bytes(data[:3])) + + monkeypatch.setattr(os, "write", write) + return calls + + +def test_rewrite_descriptor_retries_short_writes(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + calls = _short_writes(monkeypatch) + FileHelper.rewrite_descriptor(fd, b"replacement\n") + monkeypatch.undo() + assert len(calls) > 1 + assert target.read_bytes() == b"replacement\n" + + +def test_create_private_bytes_retries_short_writes(tmp_path, monkeypatch): + calls = _short_writes(monkeypatch) + with FileHelper(tmp_path) as helper: + helper.create_private_bytes("backup", b"private content\n") + monkeypatch.undo() + assert len(calls) > 1 + assert (tmp_path / "backup").read_bytes() == b"private content\n" + + +def test_create_private_bytes_removes_its_file_after_a_short_write_then_an_error(tmp_path, monkeypatch): + _short_writes(monkeypatch, fail_after=1) + with FileHelper(tmp_path) as helper: + with pytest.raises(OSError, match="I/O error"): + helper.create_private_bytes("backup", b"private content\n") + monkeypatch.undo() + assert not (tmp_path / "backup").exists() From 4ed8dcf803b82219b887a2c6cfda65415fe7c748 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 27 Nov 2026 11:08:46 +0000 Subject: [PATCH 15/18] refactor(file-helper): narrow to stat, open_rewrite and rewrite_descriptor Per review, this PR now carries only the public operations an in-place rewrite needs. create_private_bytes (with its POSIX and Windows owner-only creation code), access and canonical_root move to the follow-up branch feat/file-helper-owner-only-create, stacked on this one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioyE1BXnL4WnQRCgJu --- design/file-helper.md | 59 +-- src/specify_cli/_file_handles.py | 215 -------- src/specify_cli/file_helper.py | 222 +------- tests/test_file_helper_rewrite.py | 842 +----------------------------- 4 files changed, 10 insertions(+), 1328 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b35937e9cb..e33af0ee6a 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -259,16 +259,6 @@ descriptor-relative or change their documented concurrency limitations. `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. -- `access(path, mode)` answers `os.access` for an existing entry found and - anchored as `stat` finds it; the policy walk refuses or resolves a leaf link. - POSIX checks relative to the anchored parent descriptor with a plain - `faccessat` (no `AT_SYMLINK_NOFOLLOW`, which libc emulates from mode bits - where `faccessat2` is missing); Windows pins the parent hierarchy first. It - uses the real user and group ids, so it also reports a read-only filesystem - or a file owned by someone else, which mode bits miss. It is advisory, like - `stat`. -- `canonical_root` is the root with OS and link aliases resolved, fixed on - construction; it is the base that resolved operation paths share. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. @@ -291,44 +281,6 @@ descriptor-relative or change their documented concurrency limitations. 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. -- `create_private_bytes(path, content)` exclusively creates a file only the - current user can open, with existing parents, and flushes it before - returning. It shares `create_bytes`'s policy walk, no-follow `lstat` - preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` - relative to the anchored parent. Before any content is written, it refuses - (removing the still-empty file, with `PermissionError`) when the file came - out with group or other mode bits, which means the filesystem ignored the - mode; when it is owned by a uid other than the caller's effective uid, which - means the filesystem mapped ownership (some network and container mounts); - or, on macOS, with inherited ACL allow entries, which a directory-relative - create cannot withhold (inherited deny entries are accepted). Linux default ACLs are - bounded by the mask the mode sets. NFSv4-style inherited ACLs on other - systems are not inspected. It writes and `fsync`s through that one - descriptor, adding `F_FULLFSYNC` on macOS where the filesystem supports it, - then flushes the parent best effort through a readable descriptor opened - from the anchor (search-only and `O_PATH` anchors reject `fsync`); a - parent that cannot be flushed does not fail the call. Windows creates the leaf - with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security - descriptor naming the current user as owner with a protected DACL granting - only that user full access, so the content is never readable under an - inherited ACL. It refuses a stream-qualified leaf (`file:stream`), since a - named NTFS stream shares its base file's security descriptor, and, before any - content is written, a volume without `FILE_PERSISTENT_ACLS` (FAT, exFAT), - which would drop the descriptor. A failure after creation removes only the - file this call created: POSIX unlinks the name only while it still has the - created file's identity, checked immediately before the unlink rather than - atomically with it (an identity never read leaves the name in place), with - the created inode held open until the check is done so its number cannot be - reused by a replacement. A name that already holds another file is left, and - the note names it; a name found empty gets a note that the partial file may - have been moved rather than a removal failure. A failed close of that held - descriptor after a complete write raises, leaving the file and saying so in a - note. A replacement swapped in between the check and the unlink - is an accepted residual race, since POSIX has no unlink-if-identity primitive. - Windows marks the open handle for deletion. If that - removal or the close fails, the original exception is kept and carries a note - naming the file. A Windows close failure after a complete write leaves the - file and says so in the note. - `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 @@ -385,9 +337,7 @@ descriptor-relative or change their documented concurrency limitations. byte (retrying short writes), truncates to the new length after writing, then `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. An append-mode descriptor is refused (`EINVAL`) before anything is written, - since its writes ignore the seek and the truncate would cut them off. It - shares that write loop and flush policy with `create_private_bytes`, so a - caller's in-place rewrite and its private backup have the same durability. + since its writes ignore the seek and the truncate would cut them off. A failure can leave partial content; restoring it is the caller's job. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established @@ -524,10 +474,9 @@ 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. -On Windows, exclusive creation (including `create_private_bytes`), text -overwrite and `open_rewrite` still open their leaf by pathname after pinning the -parent hierarchy, and `stat` queries its leaf the same way. Attribute-only reparse updates -can redirect those opens; they do not have the read path's parent-relative +On Windows, exclusive creation, text overwrite and `open_rewrite` still open +their leaf by pathname after pinning the parent hierarchy, and `stat` queries +its leaf the same way. Attribute-only reparse updates can redirect those opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 5641f0ceca..cbf6cbd50b 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -3,7 +3,6 @@ from collections.abc import Iterator from contextlib import contextmanager import errno -import functools import os import secrets import stat @@ -441,39 +440,6 @@ def _windows_stat(handle: int) -> os.stat_result: os.close(fd) -def _has_inherited_allow_entry(fd: int) -> bool: - """Whether a macOS file's ACL has an allow entry; deny entries grant nothing.""" - import ctypes - - libc = ctypes.CDLL(None, use_errno=True) - libc.acl_get_fd_np.restype = ctypes.c_void_p - libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] - libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] - libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] - libc.acl_free.argtypes = [ctypes.c_void_p] - acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED - if not acl: - code = ctypes.get_errno() - # No ACL, or a filesystem that cannot hold one. - if code in (errno.ENOENT, errno.ENOTSUP, errno.EOPNOTSUPP): - return False - raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") - try: - entry = ctypes.c_void_p() - tag = ctypes.c_int() - which = 0 # ACL_FIRST_ENTRY, then ACL_NEXT_ENTRY - while libc.acl_get_entry(acl, which, ctypes.byref(entry)) == 0: - which = -1 - if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: - code = ctypes.get_errno() - raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") - if tag.value == 1: # ACL_EXTENDED_ALLOW - return True - return False - finally: - libc.acl_free(acl) - - @contextmanager def windows_read_fd(handle: int) -> Iterator[int]: """Read the validated object through an independently owned duplicate.""" @@ -536,184 +502,3 @@ def _windows_creation_attributes() -> int: os.close(fd) os.unlink(probe) return 0x1 if readonly else 0 - - -_GENERIC_WRITE = 0x40000000 -_DELETE = 0x00010000 -_CREATE_NEW = 1 -_FILE_ATTRIBUTE_NORMAL = 0x80 -_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 -_FILE_DISPOSITION_INFO = 4 -_TOKEN_QUERY = 0x8 -_TOKEN_USER = 1 -_ERROR_INSUFFICIENT_BUFFER = 122 -_SDDL_REVISION_1 = 1 -_FILE_PERSISTENT_ACLS = 0x8 - - -def _windows_create_private_fd(path: Path) -> int: - """Create ``path`` owned by, and only accessible to, the current user. - - The owner and protected access-control list are set by the call that - creates the file, and nothing is shared until it closes, so the content is - never readable under an inherited list. A volume that does not persist - access-control lists would drop that list, so the empty file is removed and - the call refused. Returns a binary CRT descriptor. - """ - import ctypes - import msvcrt - from ctypes import wintypes - - kernel, advapi, attributes_type = _windows_security_api() - descriptor = ctypes.c_void_p() - if not advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( - _windows_owner_only_sddl(), _SDDL_REVISION_1, ctypes.byref(descriptor), None, - ): - raise ctypes.WinError(ctypes.get_last_error()) - try: - attributes = attributes_type(ctypes.sizeof(attributes_type), descriptor, False) - # DELETE lets a later failure remove the file through its own handle. - handle = kernel.CreateFileW( - str(path), _GENERIC_WRITE | _DELETE, 0, ctypes.byref(attributes), _CREATE_NEW, - _FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT, None, - ) - if handle is None or handle == wintypes.HANDLE(-1).value: - raise ctypes.WinError(ctypes.get_last_error()) - finally: - kernel.LocalFree(descriptor) - try: - _require_persistent_acls(kernel, handle, path) - return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) - except BaseException as error: - # No descriptor reaches the caller, so remove the empty file here. With - # no sharing, nothing else could have opened, renamed or replaced it. - class FileDispositionInfo(ctypes.Structure): - _fields_ = [("DeleteFile", wintypes.BOOLEAN)] - - try: - disposition = FileDispositionInfo(True) - if not kernel.SetFileInformationByHandle( - handle, _FILE_DISPOSITION_INFO, ctypes.byref(disposition), - ctypes.sizeof(disposition), - ): - raise ctypes.WinError(ctypes.get_last_error()) - except Exception as cleanup_error: - error.add_note(f"Could not remove empty file {path}: {cleanup_error}") - finally: - kernel.CloseHandle(handle) - raise - - -def _require_persistent_acls(kernel, handle: int, path: Path) -> None: - """Refuse a volume that drops security descriptors, such as FAT or exFAT.""" - import ctypes - from ctypes import wintypes - - flags = wintypes.DWORD() - if not kernel.GetVolumeInformationByHandleW( - handle, None, 0, None, None, ctypes.byref(flags), None, 0, - ): - error = ctypes.WinError(ctypes.get_last_error()) - error.add_note(f"Could not check that the volume holding {path} keeps access-control lists") - raise error - if not flags.value & _FILE_PERSISTENT_ACLS: - raise PermissionError( - errno.EACCES, - f"Refusing to write {path}: its volume does not keep access-control lists", - ) - - -def _windows_owner_only_sddl() -> str: - """The security descriptor, as SDDL, private files are created with.""" - sid = _windows_current_user_sid() - return f"O:{sid}D:P(A;;FA;;;{sid})" - - -@functools.lru_cache(maxsize=1) -def _windows_current_user_sid() -> str: - import ctypes - from ctypes import wintypes - - kernel, advapi, _ = _windows_security_api() - token = wintypes.HANDLE() - if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)): - raise ctypes.WinError(ctypes.get_last_error()) - try: - size = wintypes.DWORD() - if not advapi.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(size)): - code = ctypes.get_last_error() - if code != _ERROR_INSUFFICIENT_BUFFER: - raise ctypes.WinError(code) - buffer = ctypes.create_string_buffer(size.value) - if not advapi.GetTokenInformation( - token, _TOKEN_USER, buffer, size, ctypes.byref(size), - ): - raise ctypes.WinError(ctypes.get_last_error()) - # TOKEN_USER starts with SID_AND_ATTRIBUTES, whose first field is the SID. - sid = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0] - text = wintypes.LPWSTR() - if not advapi.ConvertSidToStringSidW(sid, ctypes.byref(text)): - raise ctypes.WinError(ctypes.get_last_error()) - try: - value = text.value - finally: - kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) - finally: - kernel.CloseHandle(token) - if not value or not value.startswith("S-"): - raise OSError(errno.EINVAL, "Could not read the current user's security identifier") - return value - - -@functools.lru_cache(maxsize=1) -def _windows_security_api(): - """kernel32 and advapi32 with private prototypes, and SECURITY_ATTRIBUTES.""" - import ctypes - from ctypes import wintypes - - class SecurityAttributes(ctypes.Structure): - _fields_ = [ - ("nLength", wintypes.DWORD), - ("lpSecurityDescriptor", ctypes.c_void_p), - ("bInheritHandle", wintypes.BOOL), - ] - - kernel = ctypes.WinDLL("kernel32", use_last_error=True) - advapi = ctypes.WinDLL("advapi32", use_last_error=True) - kernel.LocalFree.argtypes = [ctypes.c_void_p] - kernel.LocalFree.restype = ctypes.c_void_p - kernel.CloseHandle.argtypes = [wintypes.HANDLE] - kernel.CloseHandle.restype = wintypes.BOOL - kernel.GetCurrentProcess.argtypes = [] - kernel.GetCurrentProcess.restype = wintypes.HANDLE - kernel.CreateFileW.argtypes = [ - wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, - ctypes.POINTER(SecurityAttributes), wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE, - ] - kernel.CreateFileW.restype = wintypes.HANDLE - kernel.SetFileInformationByHandle.argtypes = [ - wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, - ] - kernel.SetFileInformationByHandle.restype = wintypes.BOOL - kernel.GetVolumeInformationByHandleW.argtypes = [ - wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), - ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, - wintypes.DWORD, - ] - kernel.GetVolumeInformationByHandleW.restype = wintypes.BOOL - advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [ - wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), wintypes.LPVOID, - ] - advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL - advapi.OpenProcessToken.argtypes = [ - wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE), - ] - advapi.OpenProcessToken.restype = wintypes.BOOL - advapi.GetTokenInformation.argtypes = [ - wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, - ctypes.POINTER(wintypes.DWORD), - ] - advapi.GetTokenInformation.restype = wintypes.BOOL - advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)] - advapi.ConvertSidToStringSidW.restype = wintypes.BOOL - return kernel, advapi, SecurityAttributes diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index fbf99d3902..6e9130ee81 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -16,10 +16,9 @@ from weakref import finalize from specify_cli._file_handles import ( - _WindowsFileIdentity, _has_inherited_allow_entry, _windows_create_private_fd, - _windows_delete, _windows_directory_names, _windows_entry, _windows_file_id, - _windows_handle, _windows_mode, _windows_overwrite_fd, _windows_readlink, - _windows_stat, rename_noreplace, windows_read_fd, + _WindowsFileIdentity, _windows_delete, _windows_directory_names, _windows_entry, + _windows_file_id, _windows_handle, _windows_mode, _windows_overwrite_fd, + _windows_readlink, _windows_stat, rename_noreplace, windows_read_fd, ) @@ -34,76 +33,6 @@ _POSIX_OPEN = os.open -def _remove_created( - directory: int, name: str, created: os.stat_result | None, error: BaseException -) -> None: - """Unlink ``name`` if it still has the created file's identity (best effort). - - A name that now holds a different file is left in place and named in a note - on ``error``, so the caller learns that cleanup did not happen. - """ - if created is None: - error.add_note(f"Left {name}, which may be empty; delete it before retrying") - return - try: - current = os.stat(name, dir_fd=directory, follow_symlinks=False) - except FileNotFoundError: - error.add_note( - f"Found nothing at {name} to remove: the partial file was moved or deleted " - "by another process and may still exist elsewhere" - ) - return - except OSError as cleanup_error: - error.add_note(f"Could not remove partial file {name}: {cleanup_error}") - return - if (current.st_dev, current.st_ino) != (created.st_dev, created.st_ino): - error.add_note( - f"Left {name}: another writer replaced the partial file, so it was not removed; " - "the partial file may still exist under another name" - ) - return - try: - # Accepted residual race: POSIX has no unlink-if-inode, so a writer that - # swaps the leaf between this stat and the unlink loses its file. Both - # calls go through the same directory descriptor with nothing between - # them, and the caller pins the created inode so its number cannot be - # reused by a replacement that would then pass the check above. - os.unlink(name, dir_fd=directory) - except OSError as cleanup_error: - error.add_note(f"Could not remove partial file {name}: {cleanup_error}") - - -def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: - """Refuse a new, still-empty file that someone other than its owner can open. - - Group or other mode bits mean the filesystem ignored the creation mode, and a - different owner means it mapped ownership. On - macOS, a parent's inheritable ACEs are added to a new file whatever its mode, - and they cannot be withheld from a directory-relative create, so such a file - is refused before any content reaches it. NFSv4-style inherited ACLs on other - systems are not inspected. - """ - if stat.S_IMODE(info.st_mode) & 0o077: - raise PermissionError( - errno.EACCES, - f"Filesystem did not create {name} owner-only " - f"(mode {stat.S_IMODE(info.st_mode):o})", - ) - # A mapped or fixed-ownership filesystem can give the file to another user, - # who could then read the private content however tight its mode is. - if hasattr(os, "geteuid") and info.st_uid != os.geteuid(): - raise PermissionError( - errno.EACCES, - f"Filesystem created {name} owned by uid {info.st_uid}, not the caller", - ) - if sys.platform == "darwin" and _has_inherited_allow_entry(fd): - raise PermissionError( - errno.EACCES, - f"Refusing to write {name}: its directory's inheritable ACL entries allow " - "others access", - ) - - def _full_fsync(fd: int) -> None: """Flush to stable storage; macOS ``fsync`` alone leaves data in the drive cache.""" os.fsync(fd) @@ -475,43 +404,6 @@ def _require_directory(path: Path) -> None: if not stat.S_ISDIR(path.stat().st_mode): raise NotADirectoryError(path) - @property - def canonical_root(self) -> Path: - """``root`` with OS and link aliases resolved, as fixed on construction.""" - return self._canonical_root - - def access(self, path: Path | str, mode: int) -> bool: - """Return whether ``os.access`` grants ``mode`` on an existing entry. - - The entry is found and anchored as ``stat`` finds it, so a leaf link is - refused or resolved by the normal policy walk; a leaf swapped for a link - after that walk is followed. Like ``os.access``, the answer uses the - real user and group ids and is advisory: act through a descriptor and - handle its errors. - """ - destination = self._path(path) - if destination == self._canonical_root: - return os.access(destination, mode) - if os.name == "nt": - # Pin the hierarchy as ``stat`` does; Windows ``os.access`` has no ``dir_fd``. - parts = destination.relative_to(self._canonical_root).parts - with ExitStack() as stack: - parent = stack.enter_context(_windows_handle( - self._canonical_root, directory=True, traverse=True, - )) - for part in parts[:-1]: - parent = stack.enter_context(_windows_handle( - Path(part), directory=True, parent=parent, traverse=True, - )) - return os.access(destination, mode) - unsupported = "Anchored access check is unsupported on this platform" - if os.access not in os.supports_dir_fd: - raise OSError(errno.ENOTSUP, unsupported) - with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: - # No ``follow_symlinks=False``: the walk already handled a leaf link, - # and without ``faccessat2`` libc emulates that flag from mode bits. - return os.access(destination.name, mode, dir_fd=directory) - def stat(self, path: Path | str) -> os.stat_result: """Return the metadata of an existing entry, resolving only allowed links.""" destination = self._path(path) @@ -736,111 +628,6 @@ def create_text( ) -> None: self.create_bytes(path, content.encode(encoding), mode=mode) - def create_private_bytes(self, path: Path | str, content: bytes) -> None: - """Exclusively create a file only the current user can open, flushed to disk. - - A failure after creation removes only the file this call created. - """ - if os.name == "nt" and ":" in Path(path).name: - # A named NTFS stream shares its base file's security descriptor, so - # the owner-only descriptor would not apply to it. - raise UnsupportedPathError(f"Refusing to create a named stream: {path}") - destination = self._path(path, allow_missing=True, follow_leaf=False) - try: - self._entry_mode(destination) - except FileNotFoundError: - pass - else: - raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(destination)) - with self._creation_directory(destination.parent) as directory: - if isinstance(directory, Path): - self._windows_create_private(directory / destination.name, content) - else: - self._posix_create_private(directory, destination.name, content) - - @staticmethod - def _posix_create_private(directory: int, name: str, content: bytes) -> None: - flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) - flags |= getattr(os, "O_CLOEXEC", 0) - fd = os.open(name, flags, 0o600, dir_fd=directory) - created: os.stat_result | None = None - pin: int | None = None - try: - created = os.fstat(fd) - # Holds the created inode until any cleanup is done, even if the final - # close releases ``fd``, so a replacement cannot reuse its number and - # pass the identity check. - pin = os.dup(fd) - _require_owner_only(fd, created, name) - _write_all(fd, content) - _full_fsync(fd) - closing, fd = fd, -1 - os.close(closing) - except BaseException as error: - try: - _remove_created(directory, name, created, error) - finally: - for descriptor in (fd, -1 if pin is None else pin): - if descriptor >= 0: - try: - os.close(descriptor) - except OSError as close_error: - error.add_note(f"Could not close {name}: {close_error}") - raise - # The duplicate is now the file's last descriptor, so its close is the - # one that reports a deferred write error (NFS, for example). - try: - os.close(pin) - except OSError as close_error: - close_error.add_note( - f"Wrote and flushed {name}, but closing it failed; check its content " - "before relying on it" - ) - raise - # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. - try: - parent = os.open( - ".", os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_CLOEXEC", 0), - dir_fd=directory, - ) - except OSError: - return - try: - _full_fsync(parent) - except OSError: - pass - finally: - try: - os.close(parent) - except OSError: - pass - - @staticmethod - def _windows_create_private(path: Path, content: bytes) -> None: - fd = _windows_create_private_fd(path) - try: - _write_all(fd, content) - _full_fsync(fd) - except BaseException as error: - import msvcrt - - # The handle shares nothing, so it can only name the created file. - try: - _windows_delete(msvcrt.get_osfhandle(fd)) - except Exception as cleanup_error: - error.add_note(f"Could not remove partial file {path}: {cleanup_error}") - try: - os.close(fd) - except OSError as close_error: - error.add_note(f"Could not close {path}: {close_error}") - raise - try: - os.close(fd) - except OSError as error: - # The handle is gone, so it can no longer remove the file. - error.add_note(f"{path} was written and flushed but may need deleting before a retry") - raise - def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Atomically create/replace a file, preserving any allowed leaf link.""" destination = self._path(path, allow_missing=True) @@ -904,8 +691,7 @@ def rewrite_descriptor(fd: int, content: bytes) -> None: Only for a descriptor from ``open_rewrite``. It writes from offset 0 whatever the current offset, truncates after writing (so the old bytes' space is reused rather than freed first), then ``fsync``s, adding - ``F_FULLFSYNC`` on macOS where the filesystem supports it: the same - write and flush that ``create_private_bytes`` uses. An append-mode + ``F_FULLFSYNC`` on macOS where the filesystem supports it. An append-mode descriptor is refused before anything is written, since its writes ignore the seek and the truncate would then cut them off. A failure can leave partial content; restoring it is the caller's job. diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index bf8e4297dd..ac67fccb1b 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1,19 +1,16 @@ -"""Public in-place byte rewrite, owner-only creation and stat on FileHelper.""" +"""Public in-place byte rewrite and stat on FileHelper.""" import errno import os -import shutil import stat import subprocess import sys -import types from contextlib import contextmanager import pytest -from specify_cli import _file_handles from specify_cli.file_helper import ( - FileHelper, FileHelperError, SymlinkDeniedError, UnsupportedPathError, + FileHelper, SymlinkDeniedError, UnsupportedPathError, ) @@ -78,94 +75,6 @@ def test_stat_refuses_a_path_outside_the_root(tmp_path): files.stat("../outside") -# access and canonical_root - - -def test_access_grants_an_accessible_entry(tmp_path): - _seed(tmp_path) - with FileHelper(tmp_path) as files: - assert files.access(REL, os.R_OK | os.W_OK) - assert files.access("parent", os.X_OK) - assert files.access(tmp_path, os.W_OK) - - -@pytest.mark.skipif( - os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), - reason="needs POSIX permissions enforced for the current user", -) -def test_access_refuses_what_the_mode_denies(tmp_path): - path = _seed(tmp_path) - path.chmod(0o444) - try: - with FileHelper(tmp_path) as files: - assert files.access(REL, os.R_OK) - assert not files.access(REL, os.W_OK) - finally: - path.chmod(0o644) - - -@pytest.mark.skipif(os.name != "nt", reason="the read-only attribute is Windows-only") -def test_access_reports_the_windows_read_only_attribute(tmp_path): - path = _seed(tmp_path) - path.chmod(stat.S_IREAD) - try: - with FileHelper(tmp_path) as files: - assert not files.access(REL, os.W_OK) - finally: - path.chmod(stat.S_IREAD | stat.S_IWRITE) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX checks through the parent descriptor") -def test_access_makes_a_plain_faccessat(tmp_path, monkeypatch): - # Without faccessat2, libc emulates AT_SYMLINK_NOFOLLOW from mode bits. - _seed(tmp_path) - calls = [] - real_access = os.access - - def access(path, mode, **kwargs): - calls.append(kwargs) - return real_access(path, mode, **kwargs) - - monkeypatch.setattr(os, "access", access) - monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {access}) - monkeypatch.setattr(os, "supports_follow_symlinks", os.supports_follow_symlinks - {real_access}) - with FileHelper(tmp_path) as files: - assert files.access(REL, os.R_OK) - assert len(calls) == 1 - assert "dir_fd" in calls[0] and "follow_symlinks" not in calls[0] - - -def test_access_of_a_missing_entry_raises(tmp_path): - with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): - files.access("missing", os.R_OK) - - -def test_access_refuses_a_symlink_unless_allowed(tmp_path): - _symlinks_available(tmp_path) - path = _seed(tmp_path) - (tmp_path / "link").symlink_to(path) - with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): - files.access("link", os.R_OK) - with FileHelper(tmp_path, allow_symlinks=True) as files: - assert files.access("link", os.R_OK) - - -def test_access_refuses_a_path_outside_the_root(tmp_path): - with FileHelper(tmp_path) as files, pytest.raises(ValueError): - files.access("../outside", os.R_OK) - - -def test_canonical_root_resolves_a_root_alias(tmp_path): - _symlinks_available(tmp_path) - real = tmp_path / "real" - real.mkdir() - alias = tmp_path / "alias" - alias.symlink_to(real, target_is_directory=True) - with FileHelper(alias) as files: - assert files.root == alias - assert files.canonical_root == real.resolve() - - # open_rewrite @@ -278,380 +187,6 @@ def test_open_rewrite_refuses_a_symlinked_leaf_unless_allowed(tmp_path): assert path.read_bytes() == b"ab23456789" -# create_private_bytes - - -def test_create_private_bytes_creates_exclusively(tmp_path): - (tmp_path / "parent").mkdir() - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"first") - with pytest.raises(FileExistsError): - files.create_private_bytes(REL, b"second") - assert (tmp_path / REL).read_bytes() == b"first" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") -def test_create_private_bytes_is_owner_only(tmp_path): - (tmp_path / "parent").mkdir() - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - assert stat.S_IMODE((tmp_path / REL).stat().st_mode) & 0o077 == 0 - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX ownership") -def test_create_private_bytes_refuses_a_file_owned_by_another_user(tmp_path, monkeypatch): - (tmp_path / "parent").mkdir() - monkeypatch.setattr(os, "geteuid", lambda: os.stat(tmp_path).st_uid + 1) - with FileHelper(tmp_path) as files, pytest.raises(PermissionError) as raised: - files.create_private_bytes(REL, b"private") - assert "owned by uid" in str(raised.value) - assert not (tmp_path / REL).exists() - - -def test_create_private_bytes_needs_an_existing_parent(tmp_path): - with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): - files.create_private_bytes(REL, b"content") - assert not (tmp_path / "parent").exists() - - -def test_create_private_bytes_refuses_a_dangling_link(tmp_path): - _symlinks_available(tmp_path) - (tmp_path / "parent").mkdir() - (tmp_path / REL).symlink_to(tmp_path / "target") - with FileHelper(tmp_path, allow_symlinks=True) as files, pytest.raises(FileExistsError): - files.create_private_bytes(REL, b"content") - assert not (tmp_path / "target").exists() - - -@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") -def test_create_private_bytes_refuses_a_symlinked_parent(tmp_path): - outside = tmp_path / "outside" - outside.mkdir() - project = tmp_path / "project" - project.mkdir() - (project / "parent").symlink_to(outside) - with FileHelper(project) as files, pytest.raises(SymlinkDeniedError): - files.create_private_bytes(REL, b"secret") - assert not list(outside.iterdir()) - - -@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") -def test_create_private_bytes_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): - outside = tmp_path / "outside" - outside.mkdir() - parent = tmp_path / "parent" - parent.mkdir() - original = FileHelper._creation_directory - - @contextmanager - def swap_first(self, directory): - parent.rename(tmp_path / "moved") - parent.symlink_to(outside, target_is_directory=True) - with original(self, directory) as anchored: - yield anchored - - monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) - with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: - files.create_private_bytes(REL, b"secret") - assert raised.value.errno in _NOFOLLOW_REFUSALS - assert not list(outside.iterdir()) - - -@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") -def test_create_private_bytes_refuses_a_junctioned_parent(tmp_path): - outside = tmp_path / "outside" - outside.mkdir() - project = tmp_path / "project" - project.mkdir() - subprocess.run( - ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], - check=True, capture_output=True, - ) - with FileHelper(project) as files, pytest.raises(UnsupportedPathError): - files.create_private_bytes(REL, b"secret") - assert not list(outside.iterdir()) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -@pytest.mark.parametrize("step", ["write", "fsync", "close"]) -def test_posix_create_private_bytes_uses_one_descriptor_and_removes_a_partial_file( - tmp_path, monkeypatch, step -): - # Reopening the file by name could block on a FIFO swapped in for it. - (tmp_path / "parent").mkdir() - real_open, real_step = os.open, getattr(os, step) - leaf: list[int] = [] - live: set[int] = set() - - def open_(path, flags, *args, **kwargs): - fd = real_open(path, flags, *args, **kwargs) - if os.fspath(path) == "file": - leaf.append(fd) - live.add(fd) - return fd - - def fail(fd, *args): - if fd not in live: - return real_step(fd, *args) - if step == "close": - # Its number may be reused once closed. - live.discard(fd) - real_step(fd) - raise OSError("disk full") - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, step, fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert len(leaf) == 1 - assert not (tmp_path / REL).exists() - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_keeps_a_replacement_it_did_not_create(tmp_path, monkeypatch): - (tmp_path / "parent").mkdir() - real_fsync = os.fsync - - def replace_then_fail(fd): - if stat.S_ISREG(os.fstat(fd).st_mode): - (tmp_path / REL).unlink() - (tmp_path / REL).write_bytes(b"someone else's") - raise OSError("disk full") - return real_fsync(fd) - - monkeypatch.setattr(os, "fsync", replace_then_fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert (tmp_path / REL).read_bytes() == b"someone else's" - # The caller is told the name was left, rather than cleanup failing silently. - assert any( - "Left file" in note and "not removed" in note for note in raised.value.__notes__ - ) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_flushes_the_file_and_its_directory(tmp_path, monkeypatch): - (tmp_path / "parent").mkdir() - real_open, real_fsync, real_creation = os.open, os.fsync, FileHelper._creation_directory - leaf: list[int] = [] - pinned: list[int] = [] - synced: list[tuple[int, bool]] = [] - - def open_(path, flags, *args, **kwargs): - fd = real_open(path, flags, *args, **kwargs) - if os.fspath(path) == "file": - leaf.append(fd) - return fd - - @contextmanager - def creation_directory(self, directory): - with real_creation(self, directory) as anchored: - pinned.append(anchored) - yield anchored - - def fsync(fd): - synced.append((fd, stat.S_ISDIR(os.fstat(fd).st_mode))) - return real_fsync(fd) - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, "fsync", fsync) - monkeypatch.setattr(FileHelper, "_creation_directory", creation_directory) - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert len(leaf) == 1 and (leaf[0], False) in synced - # The pinned descriptor may be O_PATH, which fsync rejects, so a readable one is used. - directories = [fd for fd, is_dir in synced if is_dir] - assert len(directories) == 1 and directories[0] not in pinned - assert (tmp_path / REL).read_bytes() == b"content" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_succeeds_when_the_directory_cannot_be_flushed( - tmp_path, monkeypatch -): - (tmp_path / "parent").mkdir() - real_fsync = os.fsync - - def fsync(fd): - if stat.S_ISDIR(os.fstat(fd).st_mode): - raise OSError(errno.EBADF, "Bad file descriptor") - return real_fsync(fd) - - monkeypatch.setattr(os, "fsync", fsync) - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert (tmp_path / REL).read_bytes() == b"content" - - -@pytest.mark.skipif(os.name != "nt", reason="Windows creation path") -def test_windows_create_private_bytes_removes_a_partial_file(tmp_path, monkeypatch): - (tmp_path / "parent").mkdir() - real_fsync = os.fsync - created: list[int] = [] - real_create = _file_handles._windows_create_private_fd - - def create(path): - fd = real_create(path) - created.append(fd) - return fd - - def fsync(fd): - if fd in created: - raise OSError("disk full") - return real_fsync(fd) - - from specify_cli import file_helper - - monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) - monkeypatch.setattr(os, "fsync", fsync) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert not (tmp_path / REL).exists() - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - assert (tmp_path / REL).read_bytes() == b"content" - - -@pytest.mark.skipif(sys.platform != "win32", reason="Windows creation path") -def test_windows_create_private_bytes_leaves_no_file_if_no_descriptor_is_made( - tmp_path, monkeypatch -): - import msvcrt - - def fail(handle, flags): - raise OSError("too many open files") - - (tmp_path / "parent").mkdir() - monkeypatch.setattr(msvcrt, "open_osfhandle", fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="too many open files"): - files.create_private_bytes(REL, b"content") - assert not (tmp_path / REL).exists() - monkeypatch.undo() - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - assert (tmp_path / REL).read_bytes() == b"content" - - -def _simulate_windows_create(monkeypatch, calls, *, marked=True, volume_flags=0x8): - """Fake the Windows calls ``_windows_create_private_fd`` makes, so it runs everywhere.""" - import ctypes - - class Attributes(ctypes.Structure): - _fields_ = [("nLength", ctypes.c_ulong), ("descriptor", ctypes.c_void_p), - ("inherit", ctypes.c_int)] - - class Kernel: - def CreateFileW(self, path, access, share, attributes, disposition, flags, template): - calls.append(("CreateFileW", access, share, disposition)) - return 1234 - - def GetVolumeInformationByHandleW(self, handle, *args): - args[4]._obj.value = volume_flags # lpFileSystemFlags - return 1 - - def SetFileInformationByHandle(self, handle, kind, info, size): - calls.append(("SetFileInformationByHandle", handle, kind, bytes(info._obj))) - if marked is None: - raise ctypes.ArgumentError("bad argument") - return int(marked) - - def CloseHandle(self, handle): - calls.append(("CloseHandle", handle)) - return 1 - - def LocalFree(self, pointer): - return None - - class Advapi: - def ConvertStringSecurityDescriptorToSecurityDescriptorW(self, *args): - return 1 - - def open_osfhandle(handle, flags): - calls.append(("open_osfhandle", handle)) - raise OSError("too many open files") - - monkeypatch.setattr( - _file_handles, "_windows_security_api", lambda: (Kernel(), Advapi(), Attributes) - ) - monkeypatch.setattr(_file_handles, "_windows_owner_only_sddl", lambda: "O:S-1-0D:P") - monkeypatch.setattr(ctypes, "get_last_error", lambda: 5, raising=False) - monkeypatch.setattr(ctypes, "WinError", lambda code=None: OSError(code, "denied"), raising=False) - monkeypatch.setitem(sys.modules, "msvcrt", types.SimpleNamespace(open_osfhandle=open_osfhandle)) - monkeypatch.setattr(os, "O_BINARY", 0x8000, raising=False) - - -@pytest.mark.parametrize("marked", [True, False, None]) -def test_windows_private_fd_removes_its_file_through_the_handle_if_no_descriptor_is_made( - tmp_path, monkeypatch, marked -): - # Simulates the Windows calls, so this runs everywhere; the test above - # makes the real ones. - calls = [] - _simulate_windows_create(monkeypatch, calls, marked=marked) - with pytest.raises(OSError, match="too many open files") as raised: - _file_handles._windows_create_private_fd(tmp_path / "file") - delete, create_new = 0x00010000, 1 - access, share, disposition = calls[0][1:] - assert access & delete and share == 0 and disposition == create_new - # FileDispositionInfo with DeleteFile set, before the handle closes. - assert calls[1:] == [ - ("open_osfhandle", 1234), - ("SetFileInformationByHandle", 1234, 4, b"\x01"), - ("CloseHandle", 1234), - ] - # If it cannot be marked, the error names the empty file so it can be deleted. - noted = any(str(tmp_path / "file") in note for note in getattr(raised.value, "__notes__", [])) - assert noted is not bool(marked) - - -def test_windows_private_fd_refuses_a_volume_without_persistent_acls(tmp_path, monkeypatch): - # FAT and exFAT accept the security descriptor but do not keep it. - calls = [] - _simulate_windows_create(monkeypatch, calls, volume_flags=0) - with pytest.raises(PermissionError, match="does not keep access-control lists"): - _file_handles._windows_create_private_fd(tmp_path / "file") - # Refused before a descriptor exists; the empty file is removed through its handle. - assert [call[0] for call in calls] == [ - "CreateFileW", "SetFileInformationByHandle", "CloseHandle", - ] - - -@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") -def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path): - (tmp_path / "parent").mkdir() - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"content") - # A step's PowerShell 7 puts its own module paths in PSModulePath, and Windows - # PowerShell then fails to load Microsoft.PowerShell.Security for Get-Acl. - # Prefer pwsh, and let either shell rebuild its default module path. - env = {key: value for key, value in os.environ.items() if key.upper() != "PSMODULEPATH"} - # SDDL abbreviates well-known accounts (the built-in Administrator is "LA"), - # so compare resolved SIDs rather than the descriptor string. - script = ( - f"$acl = Get-Acl -LiteralPath '{tmp_path / REL}'; " - "$sid = [System.Security.Principal.SecurityIdentifier]; " - "$acl.GetOwner($sid).Value; " - "$acl.AreAccessRulesProtected; " - "$acl.GetAccessRules($true, $true, $sid) | ForEach-Object { " - "\"$($_.IdentityReference.Value) $($_.AccessControlType) $($_.FileSystemRights)\" }" - ) - result = subprocess.run( - [shutil.which("pwsh") or "powershell", "-NoProfile", "-NonInteractive", "-Command", script], - capture_output=True, text=True, env=env, - ) - assert result.returncode == 0, result.stderr - owner, protected, *rules = result.stdout.strip().splitlines() - sid = _file_handles._windows_current_user_sid() - assert owner == sid - assert protected == "True" - assert rules == [f"{sid} Allow FullControl"] - - # Review regressions @@ -676,27 +211,6 @@ def swap_first(self, directory, **kwargs): assert raised.value.errno in _NOFOLLOW_REFUSALS -@pytest.mark.skipif(os.name == "nt", reason="POSIX anchors through parent descriptors") -def test_access_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): - path = _seed(tmp_path, b"inside") - outside = tmp_path / "outside" - outside.mkdir() - (outside / "file").write_bytes(b"outside") - original = FileHelper._posix_directory - - @contextmanager - def swap_first(self, directory, **kwargs): - path.parent.rename(tmp_path / "moved") - path.parent.symlink_to(outside, target_is_directory=True) - with original(self, directory, **kwargs) as anchored: - yield anchored - - monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) - with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: - files.access(REL, os.R_OK) - assert raised.value.errno in _NOFOLLOW_REFUSALS - - def test_stat_of_the_root(tmp_path): with FileHelper(tmp_path) as files: assert files.stat(tmp_path).st_ino == tmp_path.stat().st_ino @@ -709,274 +223,6 @@ def test_open_rewrite_yields_a_blocking_descriptor(tmp_path): assert os.get_blocking(fd) -@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") -def test_create_private_bytes_refuses_a_directory_with_inheritable_acl_entries(tmp_path): - parent = tmp_path / "parent" - parent.mkdir() - subprocess.run( - ["chmod", "+a", "everyone allow read,file_inherit", str(parent)], - check=True, capture_output=True, - ) - (parent / "plain").write_bytes(b"") - inherited = subprocess.run( - ["ls", "-le", str(parent / "plain")], check=True, capture_output=True, text=True, - ).stdout - if "everyone" not in inherited: - pytest.skip("filesystem did not apply the inheritable ACE") - with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="inheritable ACL entries allow"): - files.create_private_bytes(REL, b"secret") - assert not (tmp_path / REL).exists() - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") -def test_create_private_bytes_refuses_a_filesystem_that_ignores_the_mode(tmp_path, monkeypatch): - (tmp_path / "parent").mkdir() - real_fstat = os.fstat - - def fstat(fd): - info = real_fstat(fd) - if stat.S_ISREG(info.st_mode): - values = list(info) - values[0] = stat.S_IFREG | 0o777 - return os.stat_result(values) - return info - - monkeypatch.setattr(os, "fstat", fstat) - with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="owner-only"): - files.create_private_bytes(REL, b"secret") - monkeypatch.undo() - assert not (tmp_path / REL).exists() - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_notes_a_partial_file_it_could_not_remove( - tmp_path, monkeypatch -): - (tmp_path / "parent").mkdir() - real_fsync, real_unlink = os.fsync, os.unlink - - def fsync(fd): - if stat.S_ISREG(os.fstat(fd).st_mode): - raise OSError(errno.ENOSPC, "No space left") - return real_fsync(fd) - - def unlink(path, *args, **kwargs): - if os.fspath(path) == "file": - raise PermissionError(errno.EACCES, "denied") - return real_unlink(path, *args, **kwargs) - - monkeypatch.setattr(os, "fsync", fsync) - monkeypatch.setattr(os, "unlink", unlink) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert any("Could not remove partial file" in note for note in raised.value.__notes__) - assert (tmp_path / REL).exists() - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_never_removes_a_name_it_could_not_identify( - tmp_path, monkeypatch -): - (tmp_path / "parent").mkdir() - real_fstat = os.fstat - leaf: list[int] = [] - real_open = os.open - - def open_(path, flags, *args, **kwargs): - fd = real_open(path, flags, *args, **kwargs) - if os.fspath(path) == "file": - leaf.append(fd) - return fd - - def fstat(fd): - if fd in leaf: - raise OSError(errno.EIO, "fstat failed") - return real_fstat(fd) - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, "fstat", fstat) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="fstat failed") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert (tmp_path / REL).exists() - assert any("delete it before retrying" in note for note in raised.value.__notes__) - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -@pytest.mark.parametrize("replaced", [False, True]) -def test_posix_create_private_bytes_notes_a_partial_file_moved_before_cleanup( - tmp_path, monkeypatch, replaced -): - (tmp_path / "parent").mkdir() - real_fsync = os.fsync - - def move_then_fail(fd): - if stat.S_ISREG(os.fstat(fd).st_mode): - (tmp_path / REL).rename(tmp_path / "parent" / "moved") - if replaced: - (tmp_path / REL).write_bytes(b"someone else's") - raise OSError("disk full") - return real_fsync(fd) - - monkeypatch.setattr(os, "fsync", move_then_fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - notes = raised.value.__notes__ - # Neither case is a removal failure, and both say the partial file may remain. - assert not any("Could not remove" in note for note in notes) - assert any("may still exist" in note for note in notes) - assert (tmp_path / "parent" / "moved").exists() - if replaced: - assert (tmp_path / REL).read_bytes() == b"someone else's" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_reports_a_failed_close_of_the_last_descriptor( - tmp_path, monkeypatch -): - (tmp_path / "parent").mkdir() - real_open, real_dup, real_close = os.open, os.dup, os.close - leaf: list[int] = [] - duplicates: list[int] = [] - - def open_(path, flags, *args, **kwargs): - fd = real_open(path, flags, *args, **kwargs) - if os.fspath(path) == "file": - leaf.append(fd) - return fd - - def dup(fd): - copy_ = real_dup(fd) - if fd in leaf: - duplicates.append(copy_) - return copy_ - - def close(fd): - real_close(fd) - if fd in duplicates: - duplicates.remove(fd) - raise OSError(errno.EIO, "Input/output error") - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, "dup", dup) - monkeypatch.setattr(os, "close", close) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="Input/output") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert any("check its content" in note for note in raised.value.__notes__) - # The write completed, so the file is left for the caller to inspect. - assert (tmp_path / REL).read_bytes() == b"content" - - -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -def test_posix_create_private_bytes_keeps_the_write_error_when_close_also_fails( - tmp_path, monkeypatch -): - (tmp_path / "parent").mkdir() - real_open, real_write, real_close = os.open, os.write, os.close - leaf: list[int] = [] - - def open_(path, flags, *args, **kwargs): - fd = real_open(path, flags, *args, **kwargs) - if os.fspath(path) == "file": - leaf.append(fd) - return fd - - def write(fd, data): - if fd in leaf: - raise OSError(errno.ENOSPC, "No space left") - return real_write(fd, data) - - def close(fd): - real_close(fd) - if fd in leaf: - leaf.remove(fd) - raise OSError(errno.EIO, "Input/output error") - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, "write", write) - monkeypatch.setattr(os, "close", close) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert any("Could not close" in note for note in raised.value.__notes__) - assert not (tmp_path / REL).exists() - - -@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") -def test_create_private_bytes_accepts_inherited_deny_only_acl_entries(tmp_path): - parent = tmp_path / "parent" - parent.mkdir() - subprocess.run( - ["chmod", "+a", "everyone deny delete,file_inherit", str(parent)], - check=True, capture_output=True, - ) - try: - with FileHelper(tmp_path) as files: - files.create_private_bytes(REL, b"secret") - assert (tmp_path / REL).read_bytes() == b"secret" - finally: - subprocess.run(["chmod", "-RN", str(parent)], check=False, capture_output=True) - - -@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") -@pytest.mark.parametrize(("code", "raises"), [(errno.ENOTSUP, False), (errno.EINVAL, False), - (errno.EIO, True)]) -def test_create_private_bytes_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): - import fcntl - - (tmp_path / "parent").mkdir() - real_fcntl = fcntl.fcntl - - def fail(fd, command, *args): - if command == fcntl.F_FULLFSYNC and stat.S_ISREG(os.fstat(fd).st_mode): - raise OSError(code, os.strerror(code)) - return real_fcntl(fd, command, *args) - - monkeypatch.setattr(fcntl, "fcntl", fail) - with FileHelper(tmp_path) as files: - if raises: - with pytest.raises(OSError) as raised: - files.create_private_bytes(REL, b"content") - assert raised.value.errno == code - else: - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert (tmp_path / REL).exists() is not raises - - -def test_windows_create_private_notes_a_close_failure_after_a_complete_write( - tmp_path, monkeypatch -): - # Drives the Windows branch with a real descriptor so it runs everywhere. - from specify_cli import file_helper - - target = tmp_path / "file" - real_close = os.close - opened: list[int] = [] - - def create(path): - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) - opened.append(fd) - return fd - - def close(fd): - real_close(fd) - if fd in opened: - opened.remove(fd) - raise OSError(errno.EIO, "Input/output error") - - monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) - monkeypatch.setattr(os, "close", close) - with pytest.raises(OSError, match="Input/output error") as raised: - FileHelper._windows_create_private(target, b"content") - monkeypatch.undo() - assert any("may need deleting" in note for note in raised.value.__notes__) - assert target.read_bytes() == b"content" - - @pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") def test_stat_refuses_a_junctioned_parent(tmp_path): outside = tmp_path / "outside" @@ -992,17 +238,6 @@ def test_stat_refuses_a_junctioned_parent(tmp_path): files.stat(REL) -@pytest.mark.skipif(sys.platform != "win32", reason="NTFS named streams") -def test_windows_create_private_bytes_refuses_a_named_stream(tmp_path): - # A stream shares its base file's security descriptor, so it cannot be owner-only. - path = _seed(tmp_path, b"base") - with FileHelper(tmp_path) as files, pytest.raises(FileHelperError): - files.create_private_bytes(REL + ":backup", b"secret") - assert path.read_bytes() == b"base" - with pytest.raises(FileNotFoundError): - open(f"{path}:backup", "rb").close() - - @pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") def test_stat_does_not_follow_a_root_replaced_by_a_symlink(tmp_path): root = tmp_path / "root" @@ -1056,62 +291,6 @@ def swap_first(self, destination, **kwargs): assert raised.value.errno == errno.EBADF -@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") -@pytest.mark.parametrize("step", ["write", "fsync", "close"]) -def test_posix_create_private_bytes_keeps_the_inode_pinned_during_cleanup( - tmp_path, monkeypatch, step -): - # Once nothing holds the created inode its number can be reused, and a - # replacement could then pass the identity check and be removed. - (tmp_path / "parent").mkdir() - real_open, real_dup, real_close, real_stat = os.open, os.dup, os.close, os.stat - real_step = {"write": os.write, "fsync": os.fsync, "close": real_close}[step] - pinned: set[int] = set() - leaf: list[int] = [] - pinned_at_check: list[bool] = [] - - def open_(name, flags, *args, **kwargs): - fd = real_open(name, flags, *args, **kwargs) - if os.fspath(name) == "file": - leaf.append(fd) - pinned.add(fd) - return fd - - def dup(fd): - copy = real_dup(fd) - if fd in pinned: - pinned.add(copy) - return copy - - def close(fd): - pinned.discard(fd) - real_close(fd) - if step == "close" and leaf and fd == leaf[0]: - raise OSError("disk full") - - def fail(fd, *args): - if leaf and fd == leaf[0]: - raise OSError("disk full") - return real_step(fd, *args) - - def stat_(name, *args, **kwargs): - if os.fspath(name) == "file" and kwargs.get("dir_fd") is not None: - pinned_at_check.append(bool(pinned)) - return real_stat(name, *args, **kwargs) - - monkeypatch.setattr(os, "open", open_) - monkeypatch.setattr(os, "dup", dup) - monkeypatch.setattr(os, "stat", stat_) - monkeypatch.setattr(os, "close", close) - if step != "close": - monkeypatch.setattr(os, step, fail) - with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): - files.create_private_bytes(REL, b"content") - monkeypatch.undo() - assert pinned_at_check == [True] - assert not (tmp_path / REL).exists() - - def test_rewrite_descriptor_replaces_and_truncates_from_any_offset(tmp_path): target = tmp_path / "file.txt" target.write_bytes(b"a much longer original\n") @@ -1211,20 +390,3 @@ def test_rewrite_descriptor_retries_short_writes(tmp_path, monkeypatch): assert len(calls) > 1 assert target.read_bytes() == b"replacement\n" - -def test_create_private_bytes_retries_short_writes(tmp_path, monkeypatch): - calls = _short_writes(monkeypatch) - with FileHelper(tmp_path) as helper: - helper.create_private_bytes("backup", b"private content\n") - monkeypatch.undo() - assert len(calls) > 1 - assert (tmp_path / "backup").read_bytes() == b"private content\n" - - -def test_create_private_bytes_removes_its_file_after_a_short_write_then_an_error(tmp_path, monkeypatch): - _short_writes(monkeypatch, fail_after=1) - with FileHelper(tmp_path) as helper: - with pytest.raises(OSError, match="I/O error"): - helper.create_private_bytes("backup", b"private content\n") - monkeypatch.undo() - assert not (tmp_path / "backup").exists() From dc6a02e447c656325121ee0c757d03f4101eb083 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 27 Nov 2026 11:09:34 +0000 Subject: [PATCH 16/18] docs(file-helper): note POSIX may clear setuid/setgid on rewrite open_rewrite keeps identity, owner, permission bits, ACL and hard links, but a write or truncate through it may clear the set-user-ID and set-group-ID bits, as any unprivileged POSIX write does. Keep that OS behaviour rather than restoring them, say so in the design and docstrings, and add a test comparing the result with a plain write to an identical file (skipped where the bits do not stick). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioyE1BXnL4WnQRCgJu --- design/file-helper.md | 19 ++++++++++++------- src/specify_cli/file_helper.py | 12 ++++++++---- tests/test_file_helper_rewrite.py | 30 ++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 11 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index e33af0ee6a..81059fcf23 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -323,9 +323,12 @@ descriptor-relative or change their documented concurrency limitations. the attributes of an existing file. - `open_rewrite(path)` is a context manager yielding a blocking, binary, writable descriptor on an existing regular file at offset 0, for in-place byte - rewrites that must keep the file's identity, owner, mode, ACL and hard links. - It uses `overwrite_text`'s anchored, non-truncating open, but never creates: - POSIX omits `O_CREAT` and Windows does not fall back to creation, so a leaf + rewrites that must keep the file's identity, owner, permission bits, ACL and + hard links. POSIX may clear the set-user-ID and set-group-ID bits when the + caller writes or truncates through it, as for any unprivileged write; the + helper keeps that OS behaviour and does not restore them. It uses + `overwrite_text`'s anchored, non-truncating open, but never creates: POSIX + omits `O_CREAT` and Windows does not fall back to creation, so a leaf removed after resolution raises `FileNotFoundError`. The opened file type is checked with `fstat` before the descriptor is yielded. The helper closes the descriptor on exit, so callers must not close it; wrap it with @@ -337,8 +340,10 @@ descriptor-relative or change their documented concurrency limitations. byte (retrying short writes), truncates to the new length after writing, then `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. An append-mode descriptor is refused (`EINVAL`) before anything is written, - since its writes ignore the seek and the truncate would cut them off. - A failure can leave partial content; restoring it is the caller's job. + since its writes ignore the seek and the truncate would cut them off. Like + any write, it may clear the set-user-ID and set-group-ID bits on POSIX, and + they are not restored. A failure can leave partial content; restoring it is + the caller's job. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. Recursive enumeration and each removal use anchored @@ -476,8 +481,8 @@ under concurrent renames, nor does parent anchoring make every leaf preflight atomic with the subsequent open. On Windows, exclusive creation, text overwrite and `open_rewrite` still open their leaf by pathname after pinning the parent hierarchy, and `stat` queries -its leaf the same way. Attribute-only reparse updates can redirect those opens; they do not have the read path's parent-relative -handle protection. +its leaf the same way. Attribute-only reparse updates can redirect those +opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. Existing safe-write mechanisms informed this helper, but existing shared diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 6e9130ee81..0efa91d5db 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -671,8 +671,10 @@ def open_rewrite(self, path: Path | str) -> Iterator[int]: The descriptor starts at offset 0 and the helper closes it on exit, so the caller must not close it (wrap it with ``os.fdopen(fd, "wb", closefd=False)``). - The caller owns writing, truncating and flushing; owner, mode and links are - unchanged. + The caller owns writing, truncating and flushing; owner, permission bits + and links are unchanged. On POSIX, the caller's write or truncate may clear + the set-user-ID and set-group-ID bits, as any unprivileged write does; the + helper keeps that behaviour and does not restore them. """ destination = self._path(path) self._require_file(destination) @@ -693,8 +695,10 @@ def rewrite_descriptor(fd: int, content: bytes) -> None: space is reused rather than freed first), then ``fsync``s, adding ``F_FULLFSYNC`` on macOS where the filesystem supports it. An append-mode descriptor is refused before anything is written, since its writes - ignore the seek and the truncate would then cut them off. A failure can - leave partial content; restoring it is the caller's job. + ignore the seek and the truncate would then cut them off. On POSIX the + write may clear the set-user-ID and set-group-ID bits; they are not + restored. A failure can leave partial content; restoring it is the + caller's job. """ if os.name != "nt": import fcntl diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index ac67fccb1b..ef45c5b26c 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -100,6 +100,36 @@ def test_open_rewrite_keeps_the_mode(tmp_path): assert stat.S_IMODE(path.stat().st_mode) == before +@pytest.mark.skipif(os.name == "nt", reason="POSIX set-user-ID and set-group-ID bits") +def test_open_rewrite_leaves_setid_clearing_to_the_os(tmp_path): + # POSIX lets a write by a process without privilege clear these bits. The + # helper keeps that behaviour rather than restoring them: its result must + # match a plain write to an identical file, with permission bits unchanged. + path = _seed(tmp_path) + control = tmp_path / "control" + control.write_bytes(path.read_bytes()) + for target in (path, control): + target.chmod(0o6750) + before = stat.S_IMODE(path.stat().st_mode) + if not before & (stat.S_ISUID | stat.S_ISGID): + pytest.skip("The filesystem did not keep the set-user-ID or set-group-ID bit") + assert stat.S_IMODE(control.stat().st_mode) == before + + fd = os.open(control, os.O_WRONLY) + try: + os.write(fd, b"new") + os.ftruncate(fd, 3) + finally: + os.close(fd) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + FileHelper.rewrite_descriptor(fd, b"new") + + after = stat.S_IMODE(path.stat().st_mode) + assert path.read_bytes() == b"new" + assert after & 0o777 == before & 0o777 + assert after == stat.S_IMODE(control.stat().st_mode) + + def test_open_rewrite_closes_the_descriptor(tmp_path): _seed(tmp_path) with FileHelper(tmp_path) as files: From 176fc3b949c558ee9916f0a23ca401af033f82e6 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Mon, 30 Nov 2026 19:52:51 +0000 Subject: [PATCH 17/18] style(file-helper): drop the blank line at the end of the rewrite tests Assisted-by: Claude Code (model: claude-sonnet-5-5, autonomous) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_015w5Wip5PpXMSG3HJrb1isp --- tests/test_file_helper_rewrite.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index ef45c5b26c..b708710d36 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -419,4 +419,3 @@ def test_rewrite_descriptor_retries_short_writes(tmp_path, monkeypatch): monkeypatch.undo() assert len(calls) > 1 assert target.read_bytes() == b"replacement\n" - From 6673e8826c855b8ef2f3df8e40e2bb9b97bbf014 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 15:28:35 +0000 Subject: [PATCH 18/18] docs(file-helper): state that stat's parent-swap protection is POSIX-only On Windows stat pins the parent hierarchy but still queries the leaf by absolute pathname, so a swapped parent is not excluded there. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5Wis5eYDaa6BYVgrpvL8 --- design/file-helper.md | 12 +++++++----- src/specify_cli/file_helper.py | 10 ++++++++-- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 81059fcf23..9244ca8bc5 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -252,11 +252,13 @@ descriptor-relative or change their documented concurrency limitations. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. - `stat(path)` returns the metadata of an existing entry after the normal policy walk: allowed contained links, including a leaf link, are resolved, and the - resolved entry itself is not followed. The entry is queried relative to the - anchored parent hierarchy, so a parent swapped after resolution cannot - redirect it. The root itself is queried without following a link, so a root - replaced by a link after construction is not followed. Missing entries raise - `FileNotFoundError`. It is a + resolved entry itself is not followed. On POSIX the entry is queried relative + to the anchored parent hierarchy, so a parent swapped after resolution cannot + redirect it. On Windows the parent hierarchy is pinned but the leaf is still + queried by absolute pathname, so that protection does not apply there (see + Safety limits and migration). The root itself is queried without following a + link, so a root replaced by a link after construction is not followed. + Missing entries raise `FileNotFoundError`. It is a point-in-time query, not an anchor: callers that act on the result must re-check identity on the descriptor they act through. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 0efa91d5db..dbe4935705 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -405,11 +405,17 @@ def _require_directory(path: Path) -> None: raise NotADirectoryError(path) def stat(self, path: Path | str) -> os.stat_result: - """Return the metadata of an existing entry, resolving only allowed links.""" + """Return the metadata of an existing entry, resolving only allowed links. + + On POSIX the leaf is queried relative to the anchored parent, so a + parent swapped after resolution cannot redirect it. On Windows the + parent hierarchy is pinned but the leaf is queried by absolute + pathname, so that protection does not apply there. + """ destination = self._path(path) if destination == self._canonical_root: return os.stat(destination, follow_symlinks=False) - # Stat through the anchored parent so a swapped ancestor cannot redirect it. + # Pin the parent hierarchy; only the POSIX path below queries the leaf through it. if os.name == "nt": parts = destination.relative_to(self._canonical_root).parts with ExitStack() as stack: