From 073af65a7af25323d87a82a3bcab7b51f5ba4cac Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 19 Nov 2026 17:26:25 +0000 Subject: [PATCH 01/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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/27] 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 282180412b2390c130dd3e6edcf24f59eca6d8e7 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 27 Nov 2026 11:17:50 +0000 Subject: [PATCH 17/27] feat(file-helper): add owner-only create, access and canonical_root Restores the work split out of #5493 (commit 4ed8dcf8) so it can be reviewed separately: create_private_bytes with its POSIX and Windows owner-only creation, access and canonical_root, with their tests and design text. Stacked on feat/file-helper-public-rewrite-create. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioyE1BXnL4WnQRCgJu --- design/file-helper.md | 63 ++- src/specify_cli/_file_handles.py | 215 ++++++++ src/specify_cli/file_helper.py | 222 +++++++- tests/test_file_helper_rewrite.py | 842 +++++++++++++++++++++++++++++- 4 files changed, 1330 insertions(+), 12 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 81059fcf23..66d5a83574 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -259,6 +259,16 @@ 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. @@ -281,6 +291,44 @@ 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 @@ -342,8 +390,10 @@ descriptor-relative or change their documented concurrency limitations. append-mode descriptor is refused (`EINVAL`) before anything is written, 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. + they are not restored. 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 @@ -479,10 +529,11 @@ 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, 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. +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. Existing safe-write mechanisms informed this helper, but existing shared diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index cbf6cbd50b..5641f0ceca 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 @@ -440,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.""" @@ -502,3 +536,184 @@ 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 0efa91d5db..08137d3daf 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, _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, ) @@ -33,6 +34,76 @@ _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) @@ -404,6 +475,43 @@ 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) @@ -628,6 +736,111 @@ 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) @@ -693,7 +906,8 @@ 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. An append-mode + ``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. On POSIX the write may clear the set-user-ID and set-group-ID bits; they are not diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index ef45c5b26c..af9d62c325 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1,16 +1,19 @@ -"""Public in-place byte rewrite and stat on FileHelper.""" +"""Public in-place byte rewrite, owner-only creation 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, SymlinkDeniedError, UnsupportedPathError, + FileHelper, FileHelperError, SymlinkDeniedError, UnsupportedPathError, ) @@ -75,6 +78,94 @@ 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 @@ -217,6 +308,380 @@ 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 @@ -241,6 +706,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 @@ -253,6 +739,274 @@ 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" @@ -268,6 +1022,17 @@ 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" @@ -321,6 +1086,62 @@ 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") @@ -420,3 +1241,20 @@ 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 264c7e95eed935a3f9d0c36d7ede0fa74415e690 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Fri, 27 Nov 2026 11:48:33 +0000 Subject: [PATCH 18/27] fix(file-helper): validate the root in access and scope its claims access() on the root now queries it through a no-follow descriptor, so a missing root raises FileNotFoundError and a root replaced by a symlink is refused instead of followed. On Windows the root goes through the same non-reparse handle walk as other entries. Docs: access() describes the Windows os.access limit (existence and read-only attribute, not the DACL), the safety-limits paragraph lists access() with stat(), and create_private_bytes cleanup is described as best effort, since the identity check is not atomic with the unlink. Tests: missing and symlink-replaced root (both fail before the change), the root itself, a Windows parent junctioned after resolution, and apostrophes escaped in the PowerShell ACL test path. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WioyE1BXnL4WnQRCgJu --- design/file-helper.md | 20 +++++++----- src/specify_cli/file_helper.py | 18 ++++++++--- tests/test_file_helper_rewrite.py | 54 ++++++++++++++++++++++++++++++- 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 66d5a83574..56ddb95ef3 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -263,10 +263,14 @@ descriptor-relative or change their documented concurrency limitations. 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`. + where `faccessat2` is missing); Windows pins the parent hierarchy first. The + root is queried through a no-follow descriptor (POSIX) or a non-reparse + handle (Windows), so a missing root raises and a root replaced by a link is + refused. On POSIX 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. + On Windows, `os.access` checks only existence and the read-only attribute, + not the DACL, so `W_OK` can be granted where the DACL denies writing. 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 @@ -314,8 +318,8 @@ descriptor-relative or change their documented concurrency limitations. 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 + which would drop the descriptor. A failure after creation removes the file + this call created, best effort: 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 @@ -531,8 +535,8 @@ 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 +the parent hierarchy, and `stat` and `access` query their leaf the same way. +Attribute-only reparse updates can redirect those opens and queries; 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 08137d3daf..454f5fb3a1 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -486,14 +486,14 @@ def access(self, path: Path | str, mode: int) -> bool: 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. + real user and group ids on POSIX; on Windows it reflects only existence + and the read-only attribute, not the DACL. It 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``. + # The root's own handle refuses a root since replaced by a reparse point. parts = destination.relative_to(self._canonical_root).parts with ExitStack() as stack: parent = stack.enter_context(_windows_handle( @@ -507,6 +507,11 @@ def access(self, path: Path | str, mode: int) -> bool: unsupported = "Anchored access check is unsupported on this platform" if os.access not in os.supports_dir_fd: raise OSError(errno.ENOTSUP, unsupported) + if destination == self._canonical_root: + # Query the root through a no-follow descriptor, so a missing root raises + # and a root since replaced by a link is refused rather than followed. + with self._posix_directory(destination, unsupported_message=unsupported) as root: + return os.access(".", mode, dir_fd=root) 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. @@ -739,7 +744,10 @@ def create_text( 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. + A failure after creation removes the file this call created, best effort: + the name is unlinked only if it still has the created file's identity, but + that check is not atomic with the unlink, so a file another process swaps + in between the two can be removed instead. """ if os.name == "nt" and ":" in Path(path).name: # A named NTFS stream shares its base file's security descriptor, so diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index af9d62c325..d1f9614c4d 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -663,7 +663,7 @@ def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path) # 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}'; " + f"$acl = Get-Acl -LiteralPath '{str(tmp_path / REL).replace(chr(39), chr(39) * 2)}'; " "$sid = [System.Security.Principal.SecurityIdentifier]; " "$acl.GetOwner($sid).Value; " "$acl.AreAccessRulesProtected; " @@ -727,6 +727,58 @@ def swap_first(self, directory, **kwargs): assert raised.value.errno in _NOFOLLOW_REFUSALS +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_access_is_not_redirected_by_a_parent_junctioned_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._path + + def swap_after(self, *args, **kwargs): + resolved = original(self, *args, **kwargs) + path.parent.rename(tmp_path / "moved") + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(path.parent), str(outside)], + check=True, capture_output=True, + ) + return resolved + + monkeypatch.setattr(FileHelper, "_path", swap_after) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.access(REL, os.R_OK) + assert raised.value.errno == errno.ELOOP + + +@pytest.mark.skipif(os.name == "nt", reason="the retained root handle withholds delete sharing") +def test_access_of_a_missing_root_raises(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.rmdir() + with pytest.raises(FileNotFoundError): + files.access(".", os.R_OK) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_access_refuses_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) + with pytest.raises(OSError) as raised: + files.access(".", os.R_OK) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + +def test_access_of_the_root(tmp_path): + with FileHelper(tmp_path) as files: + assert files.access(".", os.R_OK) + + 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 a795171b41df8b563bb4432b54ec96edad96e2aa Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Mon, 30 Nov 2026 19:17:12 +0000 Subject: [PATCH 19/27] fix(file-helper): check root access without requiring search permission access() on the root now checks the root entry by path after confirming it is still the established root (missing raises, a link or a different directory is refused), instead of resolving "." under a descriptor, which also needed search permission. Adds a regression for a readable root without search permission. 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 --- src/specify_cli/file_helper.py | 13 +++++++++---- tests/test_file_helper_rewrite.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 454f5fb3a1..82b08d9145 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -508,10 +508,15 @@ def access(self, path: Path | str, mode: int) -> bool: if os.access not in os.supports_dir_fd: raise OSError(errno.ENOTSUP, unsupported) if destination == self._canonical_root: - # Query the root through a no-follow descriptor, so a missing root raises - # and a root since replaced by a link is refused rather than followed. - with self._posix_directory(destination, unsupported_message=unsupported) as root: - return os.access(".", mode, dir_fd=root) + # Check the entry itself, not ``.`` under a descriptor, which would also + # need search permission. A missing root raises; one replaced by a link + # or another directory is refused rather than followed. + current = os.stat(destination, follow_symlinks=False) + if stat.S_ISLNK(current.st_mode): + raise OSError(errno.ELOOP, "The root was replaced by a link", str(destination)) + if not os.path.samestat(self._root_stat, current): + raise FileHelperError(f"Established root changed: {destination}") + return os.access(destination, mode) 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. diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index d1f9614c4d..8e7bf7938a 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -779,6 +779,22 @@ def test_access_of_the_root(tmp_path): assert files.access(".", os.R_OK) +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX permission bits and an unprivileged user", +) +def test_access_of_a_readable_root_without_search_permission(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.chmod(0o444) + try: + assert files.access(".", os.R_OK) is os.access(root, os.R_OK) + assert files.access(".", os.R_OK) + finally: + root.chmod(0o755) + + 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 070e0f608c4aa44fe4297faa27708df54ab11801 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Mon, 30 Nov 2026 20:59:18 +0000 Subject: [PATCH 20/27] fix(file-helper): document the POSIX root access window and test a swapped root 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 --- design/file-helper.md | 10 +++++++--- src/specify_cli/file_helper.py | 4 +++- tests/test_file_helper_rewrite.py | 11 +++++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 56ddb95ef3..488514aaa3 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -264,9 +264,13 @@ descriptor-relative or change their documented concurrency limitations. 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. The - root is queried through a no-follow descriptor (POSIX) or a non-reparse - handle (Windows), so a missing root raises and a root replaced by a link is - refused. On POSIX it uses the real user and group ids, so it also reports a + root is checked against the one established on construction: on POSIX by + path, after a no-follow `lstat` shows it is still that directory, and on + Windows through a non-reparse handle. A missing root raises and a root + replaced by a link or another directory is refused. The POSIX root check is + not atomic, since querying `.` under a descriptor would also need search + permission: a root swapped for a link after the check can be answered for its + target. On POSIX 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. On Windows, `os.access` checks only existence and the read-only attribute, not the DACL, so `W_OK` can be granted where the DACL denies writing. It is diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 82b08d9145..720d1202a5 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -488,7 +488,9 @@ def access(self, path: Path | str, mode: int) -> bool: after that walk is followed. Like ``os.access``, the answer uses the real user and group ids on POSIX; on Windows it reflects only existence and the read-only attribute, not the DACL. It is advisory: act through a - descriptor and handle its errors. + descriptor and handle its errors. On POSIX the root is checked by path + after confirming it is still the established root, so a root swapped for + a link in between can be answered for its target. """ destination = self._path(path) if os.name == "nt": diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 8e7bf7938a..a5374f5b57 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -89,6 +89,17 @@ def test_access_grants_an_accessible_entry(tmp_path): assert files.access(tmp_path, os.W_OK) +@pytest.mark.skipif(os.name == "nt", reason="the retained root handle withholds delete sharing") +def test_access_refuses_a_root_replaced_by_another_directory(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.mkdir() + with pytest.raises(FileHelperError): + files.access(".", os.R_OK) + + @pytest.mark.skipif( os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), reason="needs POSIX permissions enforced for the current user", From d09eca2f4b751a1c7711d69f0abccfd43f2fb91f Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 16:34:07 +0000 Subject: [PATCH 21/27] fix(file-helper): check the Windows DACL in access() On Windows os.access reads only existence and the read-only attribute, so access() granted W_OK on a directory whose access-control list denies creating files or subdirectories, and a preflight built on it passed where the operation itself would fail part-way. access() now also opens the anchored leaf (the root by path, checked against the established root) with the rights the mode stands for: R_OK read or list, W_OK write and append or add file and subdirectory, X_OK execute or traverse. A denied open answers False; a sharing violation answers True, since Windows checks sharing only after access. Native Windows tests deny add-file rights on a directory, a root and write on a file, confirm a real create fails for the elevated CI user, and check that an exclusively held file is not reported as denied. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- design/file-helper.md | 10 +++- src/specify_cli/_file_handles.py | 66 +++++++++++++++++++++++ src/specify_cli/file_helper.py | 19 +++++-- tests/test_file_helper_rewrite.py | 90 +++++++++++++++++++++++++++++++ 4 files changed, 178 insertions(+), 7 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 488514aaa3..208381892a 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -273,8 +273,14 @@ descriptor-relative or change their documented concurrency limitations. target. On POSIX 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. On Windows, `os.access` checks only existence and the read-only attribute, - not the DACL, so `W_OK` can be granted where the DACL denies writing. It is - advisory, like `stat`. + so the entry's DACL is also asked: the leaf is opened relative to its pinned + parent (the root by path, then checked to be the established root) with the + rights `mode` stands for, the same bits for files and directories: `R_OK` + read data or list, `W_OK` write and append data or add file and + subdirectory, `X_OK` execute or traverse. A denied open answers `False`; a + sharing violation means another program holds the entry open, after access + was granted, so it answers `True`. This covers deny entries, group entries + and privileges as a real open would. 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_handles.py b/src/specify_cli/_file_handles.py index 5641f0ceca..c938f749be 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -120,6 +120,72 @@ def _windows_entry(parent: int, name: str, *, deleting: bool = False) -> Iterato _windows_api().CloseHandle(handle) +_ERROR_ACCESS_DENIED = 5 +_ERROR_SHARING_VIOLATION = 32 + + +def windows_access_rights(mode: int) -> int: + """The file or directory rights an ``os.access`` mode asks for. + + ``R_OK`` is read data or list directory, ``W_OK`` write and append data or + add file and subdirectory, ``X_OK`` execute or traverse: the bits are the + same for both kinds. + """ + rights = 0x1 if mode & os.R_OK else 0 + if mode & os.W_OK: + rights |= 0x2 | 0x4 + if mode & os.X_OK: + rights |= 0x20 + return rights + + +def windows_grants( + rights: int, *, parent: int | None = None, name: str | None = None, + path: Path | None = None, expected: int | None = None, +) -> bool: + """Whether the access-control list of an entry grants ``rights`` to this process. + + The entry is ``name`` opened relative to the ``parent`` handle, or ``path`` + opened by name, which must have the same identity as the ``expected`` + handle. Opening with exactly those rights is the check Windows makes for a + real open, so it covers deny entries, groups and privileges that a reading + of the mode bits or the read-only attribute misses. Another program holding + the entry open is not a denial: Windows checks sharing only after access. + """ + kernel = _windows_api() + try: + if name is not None and parent is not None: + handle = _open_windows_child( + parent, name, directory=None, access=rights, sharing=0x7, allow_reparse=True, + ) + elif path is not None and expected is not None: + import ctypes + from ctypes import wintypes + + # FILE_READ_ATTRIBUTES, for the identity check below. + handle = kernel.CreateFileW( + str(path), rights | 0x80, 0x7, None, 3, # OPEN_EXISTING + 0x00200000 | 0x02000000, None, # OPEN_REPARSE_POINT | BACKUP_SEMANTICS + ) + if handle == wintypes.HANDLE(-1).value: + raise ctypes.WinError(ctypes.get_last_error()) + else: + raise ValueError("Pass parent and name, or path and expected") + except OSError as error: + code = getattr(error, "winerror", None) + if code == _ERROR_ACCESS_DENIED: + return False + if code == _ERROR_SHARING_VIOLATION: + return True + raise + try: + if path is not None and _windows_file_id(handle) != _windows_file_id(expected): + raise OSError(errno.ESTALE, "The entry was replaced during the access check", str(path)) + finally: + kernel.CloseHandle(handle) + return True + + def _windows_mode(handle: int) -> int: import ctypes diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 720d1202a5..2523d0104f 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -19,7 +19,7 @@ _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, + _windows_stat, rename_noreplace, windows_access_rights, windows_grants, windows_read_fd, ) @@ -486,8 +486,10 @@ def access(self, path: Path | str, mode: int) -> bool: 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 on POSIX; on Windows it reflects only existence - and the read-only attribute, not the DACL. It is advisory: act through a + real user and group ids on POSIX. On Windows it also asks the entry's + DACL, by opening it with the rights ``mode`` stands for, since + ``os.access`` there reads only existence and the read-only attribute. + It is advisory: act through a descriptor and handle its errors. On POSIX the root is checked by path after confirming it is still the established root, so a root swapped for a link in between can be answered for its target. @@ -498,14 +500,21 @@ def access(self, path: Path | str, mode: int) -> bool: # The root's own handle refuses a root since replaced by a reparse point. parts = destination.relative_to(self._canonical_root).parts with ExitStack() as stack: - parent = stack.enter_context(_windows_handle( + root = 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) + if not os.access(destination, mode): + return False + rights = windows_access_rights(mode) + if not rights: + return True + if not parts: + return windows_grants(rights, path=destination, expected=root) + return windows_grants(rights, parent=parent, name=parts[-1]) unsupported = "Anchored access check is unsupported on this platform" if os.access not in os.supports_dir_fd: raise OSError(errno.ENOTSUP, unsupported) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index a5374f5b57..a496869e2f 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1337,3 +1337,93 @@ def test_create_private_bytes_removes_its_file_after_a_short_write_then_an_error helper.create_private_bytes("backup", b"private content\n") monkeypatch.undo() assert not (tmp_path / "backup").exists() + + +# Windows access-control lists in access() + + +def test_windows_access_rights_map_each_mode_bit(): + assert _file_handles.windows_access_rights(os.F_OK) == 0 + assert _file_handles.windows_access_rights(os.R_OK) == 0x1 + assert _file_handles.windows_access_rights(os.W_OK) == 0x2 | 0x4 + assert _file_handles.windows_access_rights(os.X_OK) == 0x20 + assert _file_handles.windows_access_rights(os.R_OK | os.W_OK | os.X_OK) == 0x27 + + +def _current_sid() -> str: + return _file_handles._windows_current_user_sid() + + +@contextmanager +def _denied(path, rights): + """Deny the current user ``rights`` (icacls letters) on ``path`` for the block.""" + sid = _current_sid() + + def icacls(*args): + result = subprocess.run( + ["icacls", str(path), *args], capture_output=True, text=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + icacls("/deny", f"*{sid}:({rights})") + try: + yield + finally: + icacls("/remove:d", f"*{sid}") + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_access_reports_a_directory_whose_acl_denies_creating_entries(tmp_path): + directory = tmp_path / "parent" + directory.mkdir() + with FileHelper(tmp_path) as files: + assert files.access("parent", os.W_OK | os.X_OK) + with _denied(directory, "WD,AD"): + # The deny entry bites even for the elevated CI user. + with pytest.raises(PermissionError): + (directory / "new").write_bytes(b"x") + with pytest.raises(PermissionError): + (directory / "sub").mkdir() + assert os.access(directory, os.W_OK) # what access() used to answer + assert not files.access("parent", os.W_OK) + assert not files.access("parent", os.W_OK | os.X_OK) + assert files.access("parent", os.R_OK | os.X_OK) + assert files.access("parent", os.F_OK) + assert files.access("parent", os.W_OK) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_access_reports_a_file_whose_acl_denies_writing(tmp_path): + path = _seed(tmp_path) + with FileHelper(tmp_path) as files, _denied(path, "WD"): + with pytest.raises(PermissionError): + path.open("r+b").close() + assert not files.access(REL, os.W_OK) + assert files.access(REL, os.R_OK) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_access_reports_a_root_whose_acl_denies_creating_entries(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + assert files.access(".", os.W_OK) + with _denied(root, "WD,AD"): + assert not files.access(".", os.W_OK) + assert files.access(".", os.R_OK) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows sharing modes") +def test_access_does_not_report_a_file_another_program_holds_open_as_denied(tmp_path): + import _winapi + + path = _seed(tmp_path) + # No sharing at all, as an editor or scanner holding the file can. + handle = _winapi.CreateFile( + str(path), _winapi.GENERIC_READ, 0, 0, _winapi.OPEN_EXISTING, 0, 0, + ) + try: + with FileHelper(tmp_path) as files: + assert files.access(REL, os.W_OK) + finally: + _winapi.CloseHandle(handle) From 2a8d5e37f895c56bac2616a54168a5197f3464ff Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 16:38:16 +0000 Subject: [PATCH 22/27] fix(file-helper): reopen the root without backup intent, map more refusals Review of the DACL check in access(): - the root was opened by path with FILE_FLAG_BACKUP_SEMANTICS, which skips the DACL when backup or restore privileges are enabled; it is now reopened through its pinned handle with NtCreateFile and no backup intent, as the helper's own creates open it, so the identity check is no longer needed - a write-protected medium (19), a share that refuses the access (65) and an entry removed meanwhile now answer False instead of raising; other errors still raise - the docstring says the DACL asked about a leaf link is the link's own - tests cover each error mapping, the probe's handle being closed, the reopen, and no longer let a failed icacls cleanup hide a test failure Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- design/file-helper.md | 18 +++++--- src/specify_cli/_file_handles.py | 69 +++++++++++++--------------- src/specify_cli/file_helper.py | 16 +++---- tests/test_file_helper_rewrite.py | 74 ++++++++++++++++++++++++++++++- 4 files changed, 122 insertions(+), 55 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 208381892a..5db31857d5 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -273,13 +273,17 @@ descriptor-relative or change their documented concurrency limitations. target. On POSIX 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. On Windows, `os.access` checks only existence and the read-only attribute, - so the entry's DACL is also asked: the leaf is opened relative to its pinned - parent (the root by path, then checked to be the established root) with the - rights `mode` stands for, the same bits for files and directories: `R_OK` - read data or list, `W_OK` write and append data or add file and - subdirectory, `X_OK` execute or traverse. A denied open answers `False`; a - sharing violation means another program holds the entry open, after access - was granted, so it answers `True`. This covers deny entries, group entries + so the entry's DACL is also asked: the leaf is opened with `NtCreateFile` + relative to its pinned parent (the root reopened through its own pinned + handle), as itself rather than through a link, without backup intent, and + with the rights `mode` stands for, the same bits for files and directories: + `R_OK` read data or list, `W_OK` write and append data or add file and + subdirectory, `X_OK` execute or traverse. `W_OK` therefore needs both add + rights on a directory, since callers create files and subdirectories alike. + Access denied, a write-protected medium and a share that refuses the access + answer `False`, as does an entry removed meanwhile; a sharing violation + means another program holds the entry open, after access was granted, so it + answers `True`; other errors raise. This covers deny entries, group entries and privileges as a real open would. 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. diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index c938f749be..1f23146de2 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -56,10 +56,17 @@ class _WindowsFileIdentity(NamedTuple): def _open_windows_child( parent: int, name: str, *, directory: bool | None, access: int, - sharing: int, allow_reparse: bool = False, + sharing: int, allow_reparse: bool = False, reopen: bool = False, ) -> int: - """Open one component relative to an already validated directory handle.""" - if PureWindowsPath(name).parts != (name,) or PureWindowsPath(name).anchor or name == ".." or "\0" in name: + """Open one component relative to an already validated directory handle. + + With ``reopen``, ``name`` must be empty and ``parent``'s own object is + opened again. + """ + if reopen: + if name: + raise ValueError(f"A reopen takes no name: {name!r}") + elif PureWindowsPath(name).parts != (name,) or PureWindowsPath(name).anchor or name == ".." or "\0" in name: raise ValueError(f"Expected a single relative Windows path component: {name!r}") encoded_length = len(name.encode("utf-16-le", errors="surrogatepass")) if encoded_length > 65532: @@ -120,7 +127,9 @@ def _windows_entry(parent: int, name: str, *, deleting: bool = False) -> Iterato _windows_api().CloseHandle(handle) -_ERROR_ACCESS_DENIED = 5 +# Open failures that mean the rights are not available: access denied, a +# write-protected medium, a share that denies the access. +_ACCESS_REFUSALS = {5, 19, 65} _ERROR_SHARING_VIOLATION = 32 @@ -139,50 +148,32 @@ def windows_access_rights(mode: int) -> int: return rights -def windows_grants( - rights: int, *, parent: int | None = None, name: str | None = None, - path: Path | None = None, expected: int | None = None, -) -> bool: - """Whether the access-control list of an entry grants ``rights`` to this process. +def windows_grants(parent: int, name: str, rights: int) -> bool: + """Whether ``name`` under the ``parent`` handle can be opened with ``rights``. - The entry is ``name`` opened relative to the ``parent`` handle, or ``path`` - opened by name, which must have the same identity as the ``expected`` - handle. Opening with exactly those rights is the check Windows makes for a - real open, so it covers deny entries, groups and privileges that a reading - of the mode bits or the read-only attribute misses. Another program holding - the entry open is not a denial: Windows checks sharing only after access. + An empty ``name`` asks about ``parent`` itself. The entry is opened as + itself, not followed if it is a link, and without backup intent, so the + answer is the one Windows gives a real open: deny entries, group entries + and privileges count, which a reading of the read-only attribute misses. + Another program holding the entry open is not a refusal, since Windows + checks sharing only after access; nor is an entry removed meanwhile, which + answers ``False`` like ``os.access``. """ - kernel = _windows_api() try: - if name is not None and parent is not None: - handle = _open_windows_child( - parent, name, directory=None, access=rights, sharing=0x7, allow_reparse=True, - ) - elif path is not None and expected is not None: - import ctypes - from ctypes import wintypes - - # FILE_READ_ATTRIBUTES, for the identity check below. - handle = kernel.CreateFileW( - str(path), rights | 0x80, 0x7, None, 3, # OPEN_EXISTING - 0x00200000 | 0x02000000, None, # OPEN_REPARSE_POINT | BACKUP_SEMANTICS - ) - if handle == wintypes.HANDLE(-1).value: - raise ctypes.WinError(ctypes.get_last_error()) - else: - raise ValueError("Pass parent and name, or path and expected") + handle = _open_windows_child( + parent, name, directory=None, access=rights, sharing=0x7, allow_reparse=True, + reopen=not name, + ) + except FileNotFoundError: + return False except OSError as error: code = getattr(error, "winerror", None) - if code == _ERROR_ACCESS_DENIED: + if code in _ACCESS_REFUSALS: return False if code == _ERROR_SHARING_VIOLATION: return True raise - try: - if path is not None and _windows_file_id(handle) != _windows_file_id(expected): - raise OSError(errno.ESTALE, "The entry was replaced during the access check", str(path)) - finally: - kernel.CloseHandle(handle) + _windows_api().CloseHandle(handle) return True diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 2523d0104f..b3c5e50593 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -485,10 +485,11 @@ def access(self, path: Path | str, mode: int) -> bool: 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 on POSIX. On Windows it also asks the entry's - DACL, by opening it with the rights ``mode`` stands for, since - ``os.access`` there reads only existence and the read-only attribute. + after that walk is followed (on Windows, the DACL asked is the link's + own). Like ``os.access``, the answer uses the real user and group ids + on POSIX. On Windows it also asks the entry's DACL, by opening it with + the rights ``mode`` stands for, since ``os.access`` there reads only + existence and the read-only attribute. It is advisory: act through a descriptor and handle its errors. On POSIX the root is checked by path after confirming it is still the established root, so a root swapped for @@ -500,7 +501,7 @@ def access(self, path: Path | str, mode: int) -> bool: # The root's own handle refuses a root since replaced by a reparse point. parts = destination.relative_to(self._canonical_root).parts with ExitStack() as stack: - root = parent = stack.enter_context(_windows_handle( + parent = stack.enter_context(_windows_handle( self._canonical_root, directory=True, traverse=True, )) for part in parts[:-1]: @@ -512,9 +513,8 @@ def access(self, path: Path | str, mode: int) -> bool: rights = windows_access_rights(mode) if not rights: return True - if not parts: - return windows_grants(rights, path=destination, expected=root) - return windows_grants(rights, parent=parent, name=parts[-1]) + # An empty name asks about the pinned root itself. + return windows_grants(parent, parts[-1] if parts else "", rights) unsupported = "Anchored access check is unsupported on this platform" if os.access not in os.supports_dir_fd: raise OSError(errno.ENOTSUP, unsupported) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index a496869e2f..8998e1a51e 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1350,6 +1350,77 @@ def test_windows_access_rights_map_each_mode_bit(): assert _file_handles.windows_access_rights(os.R_OK | os.W_OK | os.X_OK) == 0x27 +def _windows_open_failing(monkeypatch, error): + """Make the DACL probe's open raise ``error``, recording what it was asked.""" + calls = [] + + def open_child(parent, name, **kwargs): + calls.append((parent, name, kwargs)) + raise error + + monkeypatch.setattr(_file_handles, "_open_windows_child", open_child) + return calls + + +def _winerror(exc_type, code): + error = exc_type(errno.EACCES, "refused") + error.winerror = code + return error + + +@pytest.mark.parametrize("code", [5, 19, 65]) +def test_windows_grants_answers_false_when_the_open_is_refused(monkeypatch, code): + # 5: access denied, 19: write-protected medium, 65: share denies the access. + calls = _windows_open_failing(monkeypatch, _winerror(PermissionError, code)) + assert _file_handles.windows_grants(7, "leaf", 0x6) is False + assert calls == [(7, "leaf", { + "directory": None, "access": 0x6, "sharing": 0x7, "allow_reparse": True, + "reopen": False, + })] + + +def test_windows_grants_answers_true_for_a_sharing_violation(monkeypatch): + _windows_open_failing(monkeypatch, _winerror(PermissionError, 32)) + assert _file_handles.windows_grants(7, "leaf", 0x6) is True + + +def test_windows_grants_answers_false_for_an_entry_removed_meanwhile(monkeypatch): + _windows_open_failing(monkeypatch, FileNotFoundError(errno.ENOENT, "gone")) + assert _file_handles.windows_grants(7, "leaf", 0x1) is False + + +def test_windows_grants_raises_any_other_failure(monkeypatch): + error = _winerror(OSError, 1450) # ERROR_NO_SYSTEM_RESOURCES + _windows_open_failing(monkeypatch, error) + with pytest.raises(OSError) as raised: + _file_handles.windows_grants(7, "leaf", 0x1) + assert raised.value is error + + +def test_windows_grants_closes_the_probe_handle(monkeypatch): + closed = [] + monkeypatch.setattr(_file_handles, "_open_windows_child", lambda *args, **kwargs: 99) + monkeypatch.setattr( + _file_handles, "_windows_api", + lambda: types.SimpleNamespace(CloseHandle=closed.append), + ) + assert _file_handles.windows_grants(7, "", 0x20) is True + assert closed == [99] + + +def test_windows_grants_reopens_the_parent_for_an_empty_name(monkeypatch): + calls = _windows_open_failing(monkeypatch, _winerror(PermissionError, 5)) + assert _file_handles.windows_grants(7, "", 0x6) is False + assert calls[0][1] == "" and calls[0][2]["reopen"] is True + + +def test_open_windows_child_reopen_takes_no_name(): + with pytest.raises(ValueError, match="takes no name"): + _file_handles._open_windows_child( + 7, "leaf", directory=None, access=0x80, sharing=0x7, reopen=True, + ) + + def _current_sid() -> str: return _file_handles._windows_current_user_sid() @@ -1369,7 +1440,8 @@ def icacls(*args): try: yield finally: - icacls("/remove:d", f"*{sid}") + # Not asserted: a failed cleanup must not hide the test's own failure. + subprocess.run(["icacls", str(path), "/remove:d", f"*{sid}"], capture_output=True, check=False) @pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") From e6ce251f18e3d70307d0aeeddabc71b7b33df8e9 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 16:46:37 +0000 Subject: [PATCH 23/27] test(file-helper): show access() ignores backup privileges, narrow not-found Second review of the DACL check in access(): - a native test enables SeBackupPrivilege and SeRestorePrivilege, shows an open with backup semantics then skips the root's deny entry, and checks that a real create still fails and access() agrees, so going back to the by-path root open fails it - only file-not-found and path-not-found answer False; a lost share or a bad name, which Python also raises as FileNotFoundError, now raises - the icacls cleanup is asserted when the test body passed, and only skipped from masking a failure when it did not Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- src/specify_cli/_file_handles.py | 6 ++- tests/test_file_helper_rewrite.py | 89 +++++++++++++++++++++++++++++-- 2 files changed, 89 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 1f23146de2..90ff1830bf 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -164,10 +164,12 @@ def windows_grants(parent: int, name: str, rights: int) -> bool: parent, name, directory=None, access=rights, sharing=0x7, allow_reparse=True, reopen=not name, ) - except FileNotFoundError: - return False except OSError as error: code = getattr(error, "winerror", None) + # File or path not found: removed meanwhile. A lost share or a bad name, + # which Python also raises as FileNotFoundError, still raises. + if isinstance(error, FileNotFoundError) and code in (None, 2, 3): + return False if code in _ACCESS_REFUSALS: return False if code == _ERROR_SHARING_VIOLATION: diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index 8998e1a51e..5a6ffce622 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1384,11 +1384,24 @@ def test_windows_grants_answers_true_for_a_sharing_violation(monkeypatch): assert _file_handles.windows_grants(7, "leaf", 0x6) is True -def test_windows_grants_answers_false_for_an_entry_removed_meanwhile(monkeypatch): - _windows_open_failing(monkeypatch, FileNotFoundError(errno.ENOENT, "gone")) +@pytest.mark.parametrize("code", [None, 2, 3]) +def test_windows_grants_answers_false_for_an_entry_removed_meanwhile(monkeypatch, code): + error = FileNotFoundError(errno.ENOENT, "gone") + if code is not None: + error.winerror = code + _windows_open_failing(monkeypatch, error) assert _file_handles.windows_grants(7, "leaf", 0x1) is False +def test_windows_grants_raises_a_lost_share(monkeypatch): + # ERROR_BAD_NETPATH also arrives as FileNotFoundError, but is not an answer. + error = FileNotFoundError(errno.ENOENT, "The network path was not found") + error.winerror = 53 + _windows_open_failing(monkeypatch, error) + with pytest.raises(FileNotFoundError): + _file_handles.windows_grants(7, "leaf", 0x1) + + def test_windows_grants_raises_any_other_failure(monkeypatch): error = _winerror(OSError, 1450) # ERROR_NO_SYSTEM_RESOURCES _windows_open_failing(monkeypatch, error) @@ -1439,9 +1452,11 @@ def icacls(*args): icacls("/deny", f"*{sid}:({rights})") try: yield - finally: - # Not asserted: a failed cleanup must not hide the test's own failure. + except BaseException: + # A failed cleanup must not hide the test's own failure. subprocess.run(["icacls", str(path), "/remove:d", f"*{sid}"], capture_output=True, check=False) + raise + icacls("/remove:d", f"*{sid}") @pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") @@ -1499,3 +1514,69 @@ def test_access_does_not_report_a_file_another_program_holds_open_as_denied(tmp_ assert files.access(REL, os.W_OK) finally: _winapi.CloseHandle(handle) + + +@contextmanager +def _backup_and_restore_privileges(): + """Enable SeBackupPrivilege and SeRestorePrivilege on this process's token for the block.""" + import ctypes + from ctypes import wintypes + + class Luid(ctypes.Structure): + _fields_ = [("low", wintypes.DWORD), ("high", wintypes.LONG)] + + class LuidAndAttributes(ctypes.Structure): + _fields_ = [("luid", Luid), ("attributes", wintypes.DWORD)] + + class TokenPrivileges(ctypes.Structure): + _fields_ = [("count", wintypes.DWORD), ("privileges", LuidAndAttributes * 2)] + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + advapi = ctypes.WinDLL("advapi32", use_last_error=True) + kernel.GetCurrentProcess.restype = wintypes.HANDLE + advapi.OpenProcessToken.argtypes = [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)] + advapi.LookupPrivilegeValueW.argtypes = [wintypes.LPCWSTR, wintypes.LPCWSTR, ctypes.POINTER(Luid)] + advapi.AdjustTokenPrivileges.argtypes = [ + wintypes.HANDLE, wintypes.BOOL, ctypes.POINTER(TokenPrivileges), wintypes.DWORD, + ctypes.POINTER(TokenPrivileges), ctypes.POINTER(wintypes.DWORD), + ] + token = wintypes.HANDLE() + assert advapi.OpenProcessToken(kernel.GetCurrentProcess(), 0x20 | 0x8, ctypes.byref(token)) + try: + wanted = TokenPrivileges(2) + for index, name in enumerate(("SeBackupPrivilege", "SeRestorePrivilege")): + assert advapi.LookupPrivilegeValueW(None, name, ctypes.byref(wanted.privileges[index].luid)) + wanted.privileges[index].attributes = 0x2 # SE_PRIVILEGE_ENABLED + previous = TokenPrivileges() + size = wintypes.DWORD() + ok = advapi.AdjustTokenPrivileges( + token, False, ctypes.byref(wanted), ctypes.sizeof(previous), + ctypes.byref(previous), ctypes.byref(size), + ) + if not ok or ctypes.get_last_error() == 1300: # ERROR_NOT_ALL_ASSIGNED + pytest.skip("this account cannot enable backup and restore privileges") + try: + yield + finally: + advapi.AdjustTokenPrivileges(token, False, ctypes.byref(previous), 0, None, None) + finally: + kernel.CloseHandle(token) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows privileges") +def test_access_ignores_backup_privileges_a_real_create_would_not_use(tmp_path): + import _winapi + + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files, _denied(root, "WD,AD"), _backup_and_restore_privileges(): + # With the privileges enabled, an open with backup semantics skips the DACL... + handle = _winapi.CreateFile( + str(root), 0x2 | 0x4, 0x7, 0, _winapi.OPEN_EXISTING, 0x02000000, 0, + ) + _winapi.CloseHandle(handle) + # ...but creating an entry still fails, and access() agrees with it. + with pytest.raises(PermissionError): + (root / "new").write_bytes(b"x") + assert not files.access(".", os.W_OK) + From 87af6c30166e1c20726767e30f8dea7ed0f86c01 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 17:55:30 +0000 Subject: [PATCH 24/27] style: drop the blank line at the end of the new tests Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- 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 5a6ffce622..c4d0bcfab4 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1579,4 +1579,3 @@ def test_access_ignores_backup_privileges_a_real_create_would_not_use(tmp_path): with pytest.raises(PermissionError): (root / "new").write_bytes(b"x") assert not files.access(".", os.W_OK) - From 23f349df2d6bbcf35dffa235ef7634a2255f3936 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 18:03:43 +0000 Subject: [PATCH 25/27] fix(file-helper): probe the DACL without asking for SYNCHRONIZE Final review of the DACL check in access(): the probe went through the synchronous child open, which also asks for SYNCHRONIZE, so a directory whose list grants add rights but not SYNCHRONIZE answered W_OK False although creating an entry there works. The probe now opens with exactly the mode's rights and no synchronous I/O; a native test denies only SYNCHRONIZE on a directory and checks both a real create and access(). The privilege helper also restores the token before skipping when only one of the two privileges could be enabled. Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- src/specify_cli/_file_handles.py | 14 ++++++++++---- tests/test_file_helper_rewrite.py | 17 +++++++++++++++-- 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 90ff1830bf..ce057a71bc 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -57,11 +57,13 @@ class _WindowsFileIdentity(NamedTuple): def _open_windows_child( parent: int, name: str, *, directory: bool | None, access: int, sharing: int, allow_reparse: bool = False, reopen: bool = False, + synchronous: bool = True, ) -> int: """Open one component relative to an already validated directory handle. With ``reopen``, ``name`` must be empty and ``parent``'s own object is - opened again. + opened again. Without ``synchronous`` the handle is for no I/O, so it asks + for exactly ``access``, not also ``SYNCHRONIZE``. """ if reopen: if name: @@ -99,11 +101,15 @@ def _open_windows_child( ) handle = wintypes.HANDLE() status = abi._IoStatusBlock() - options = 0x00200000 | 0x20 # FILE_OPEN_REPARSE_POINT | FILE_SYNCHRONOUS_IO_NONALERT. + options = 0x00200000 # FILE_OPEN_REPARSE_POINT + if synchronous: + # FILE_SYNCHRONOUS_IO_NONALERT, which needs SYNCHRONIZE. + options |= 0x20 + access |= 0x100000 if directory is not None: options |= 0x1 if directory else 0x40 result = create( - ctypes.byref(handle), access | 0x100000, # SYNCHRONIZE is required for synchronous I/O. + ctypes.byref(handle), access, ctypes.byref(attributes), ctypes.byref(status), None, 0, sharing, 1, options, None, 0, ) @@ -162,7 +168,7 @@ def windows_grants(parent: int, name: str, rights: int) -> bool: try: handle = _open_windows_child( parent, name, directory=None, access=rights, sharing=0x7, allow_reparse=True, - reopen=not name, + reopen=not name, synchronous=False, ) except OSError as error: code = getattr(error, "winerror", None) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index c4d0bcfab4..b3ca901702 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1375,7 +1375,7 @@ def test_windows_grants_answers_false_when_the_open_is_refused(monkeypatch, code assert _file_handles.windows_grants(7, "leaf", 0x6) is False assert calls == [(7, "leaf", { "directory": None, "access": 0x6, "sharing": 0x7, "allow_reparse": True, - "reopen": False, + "reopen": False, "synchronous": False, })] @@ -1479,6 +1479,17 @@ def test_access_reports_a_directory_whose_acl_denies_creating_entries(tmp_path): assert files.access("parent", os.W_OK) +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_access_asks_only_for_the_rights_the_mode_stands_for(tmp_path): + # Creating an entry needs no SYNCHRONIZE on the directory, so access() must + # not ask for it either. + directory = tmp_path / "parent" + directory.mkdir() + with FileHelper(tmp_path) as files, _denied(directory, "S"): + (directory / "new").write_bytes(b"x") + assert files.access("parent", os.W_OK | os.X_OK) + + @pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") def test_access_reports_a_file_whose_acl_denies_writing(tmp_path): path = _seed(tmp_path) @@ -1553,9 +1564,11 @@ class TokenPrivileges(ctypes.Structure): token, False, ctypes.byref(wanted), ctypes.sizeof(previous), ctypes.byref(previous), ctypes.byref(size), ) - if not ok or ctypes.get_last_error() == 1300: # ERROR_NOT_ALL_ASSIGNED + if not ok: pytest.skip("this account cannot enable backup and restore privileges") try: + if ctypes.get_last_error() == 1300: # ERROR_NOT_ALL_ASSIGNED: only one was enabled + pytest.skip("this account cannot enable both backup and restore privileges") yield finally: advapi.AdjustTokenPrivileges(token, False, ctypes.byref(previous), 0, None, None) From ad1c3a72c6748bcd1437723c02a5a5b843c270ee Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Wed, 2 Dec 2026 18:15:10 +0000 Subject: [PATCH 26/27] docs(file-helper): note the DACL probe asks for no SYNCHRONIZE Assisted-by: Claude Code (model: claude-opus-5-5, autonomous) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015w5WipH5YcXwTvNc4qe1CE --- design/file-helper.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 5db31857d5..7fc7ec1f22 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -190,9 +190,10 @@ parent directories throughout link resolution, before classifying child entries or reading link targets. Each child is opened relative to its native parent handle, not by reconstructing an absolute pathname. Metadata and symbolic-link targets are read from opened leaf handles; directory names are enumerated from -the directory handle. Relative native opens request both +the directory handle. Relative native opens that do I/O request both `FILE_SYNCHRONOUS_IO_NONALERT` and `SYNCHRONIZE`, including directories, so -enumeration cannot consume a buffer before a pending directory query completes. +enumeration cannot consume a buffer before a pending directory query completes; +`access()`'s DACL probe does no I/O and requests neither. These accessed directories also require directory-list/read-attribute access. The resolution handles are released after selection; native mutation parents and root ancestry remain retained during @@ -276,7 +277,8 @@ descriptor-relative or change their documented concurrency limitations. so the entry's DACL is also asked: the leaf is opened with `NtCreateFile` relative to its pinned parent (the root reopened through its own pinned handle), as itself rather than through a link, without backup intent, and - with the rights `mode` stands for, the same bits for files and directories: + with exactly the rights `mode` stands for (no `SYNCHRONIZE`), the same bits + for files and directories: `R_OK` read data or list, `W_OK` write and append data or add file and subdirectory, `X_OK` execute or traverse. `W_OK` therefore needs both add rights on a directory, since callers create files and subdirectories alike. From 8ff7317a66963adff757fd2df071f5181174dd90 Mon Sep 17 00:00:00 2001 From: Ed Harrod Date: Thu, 3 Dec 2026 16:48:11 +0000 Subject: [PATCH 27/27] test(file-helper): cover the DACL probe's native arguments and denied rights Add a portable test of the NtCreateFile arguments windows_grants passes (exact rights, no SYNCHRONIZE, named entry and empty-name reopen), native Windows cases denying one right at a time on a directory (WD, AD, RD, X) and RD on a file, and a native case combining a no-sharing hold with a denied write. Assisted-by: Claude Code (model: claude-sonnet-5-5, autonomous) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_015w5Wis5eYDaa6BYVgrpvL8 --- tests/test_file_helper_rewrite.py | 78 +++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py index b3ca901702..cae148dac5 100644 --- a/tests/test_file_helper_rewrite.py +++ b/tests/test_file_helper_rewrite.py @@ -1434,6 +1434,42 @@ def test_open_windows_child_reopen_takes_no_name(): ) +@pytest.mark.parametrize( + ("name", "reopen"), [("leaf", False), ("", True)], ids=["named-entry", "empty-name-reopen"], +) +def test_windows_grants_asks_the_native_open_for_exactly_the_rights(monkeypatch, name, reopen): + import ctypes + + seen = {} + closed = [] + + def create(output, access, attributes, status, allocation, file_attributes, + sharing, disposition, options, ea, ea_length): + seen.update( + access=access, root=attributes._obj.RootDirectory, + attributes=attributes._obj.Attributes, + name=attributes._obj.ObjectName.contents.Buffer, + sharing=sharing, disposition=disposition, options=options, + ) + output._obj.value = 88 + return 0 + + monkeypatch.setattr(ctypes, "WinDLL", lambda *args: types.SimpleNamespace( + NtCreateFile=create, RtlNtStatusToDosError=lambda status: pytest.fail("unexpected error"), + ), raising=False) + monkeypatch.setattr( + _file_handles, "_windows_api", lambda: types.SimpleNamespace(CloseHandle=closed.append), + ) + assert _file_handles.windows_grants(51, name, 0x2 | 0x4) is True + # No SYNCHRONIZE (0x100000) and no synchronous I/O option (0x20): exactly the + # rights, the entry itself (reparse point opened, not followed), shared fully. + assert seen == { + "access": 0x6, "root": 51, "attributes": 0x40, "name": name, + "sharing": 0x7, "disposition": 1, "options": 0x00200000, + } + assert closed == [88] + + def _current_sid() -> str: return _file_handles._windows_current_user_sid() @@ -1500,6 +1536,48 @@ def test_access_reports_a_file_whose_acl_denies_writing(tmp_path): assert files.access(REL, os.R_OK) +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +@pytest.mark.parametrize( + ("denied", "refused"), + [ + ("WD", os.W_OK), ("AD", os.W_OK), ("RD", os.R_OK), ("X", os.X_OK), + ], +) +def test_access_reports_a_directory_denying_a_single_right(tmp_path, denied, refused): + directory = tmp_path / "parent" + directory.mkdir() + with FileHelper(tmp_path) as files, _denied(directory, denied): + for mode in (os.R_OK, os.W_OK, os.X_OK): + assert files.access("parent", mode) is (not mode & refused), (denied, mode) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_access_reports_a_file_whose_acl_denies_reading(tmp_path): + path = _seed(tmp_path) + with FileHelper(tmp_path) as files, _denied(path, "RD"): + assert not files.access(REL, os.R_OK) + assert files.access(REL, os.W_OK) + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows sharing modes") +def test_access_reports_a_held_file_whose_acl_denies_writing(tmp_path): + import _winapi + + path = _seed(tmp_path) + with _denied(path, "WD"): + # Held with no sharing at all, so a probe reaching the sharing check + # would wrongly answer True; the DACL refusal must win. + handle = _winapi.CreateFile( + str(path), _winapi.GENERIC_READ, 0, 0, _winapi.OPEN_EXISTING, 0, 0, + ) + try: + with FileHelper(tmp_path) as files: + assert not files.access(REL, os.W_OK) + assert files.access(REL, os.R_OK) + finally: + _winapi.CloseHandle(handle) + + @pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") def test_access_reports_a_root_whose_acl_denies_creating_entries(tmp_path): root = tmp_path / "root"