From b9324447916ca6ded9350bbcf2c26b707afc50da Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:57:21 -0600 Subject: [PATCH 01/13] Use handle-based text overwrites in FileHelper Anchor resolved overwrite destinations while retaining in-place updates, supported contained links, and native text behavior. Reuse shared Windows handle primitives and add overwrite regression coverage and contract documentation. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 31 +- src/specify_cli/_file_handles.py | 95 +++++ src/specify_cli/file_helper.py | 56 ++- src/specify_cli/workflows/_catalog_cache.py | 59 +-- tests/test_file_handles.py | 103 +++++ tests/test_file_helper_overwrite.py | 410 ++++++++++++++++++++ 6 files changed, 682 insertions(+), 72 deletions(-) create mode 100644 src/specify_cli/_file_handles.py create mode 100644 tests/test_file_handles.py create mode 100644 tests/test_file_helper_overwrite.py diff --git a/design/file-helper.md b/design/file-helper.md index b9dbcddd2f..8f2b33f926 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -150,6 +150,7 @@ helpers for independent project/source/managed boundaries. | Create directory | Reject accessed links before creating parents | Follow contained directory links; reject dangling targets | | Exclusively create file | Reject accessed links | Follow contained parents; reject an existing leaf without opening its target | | Atomic write/upsert | Reject accessed links | Replace the resolved regular-file target and preserve every link | +| Non-atomic text overwrite/upsert | Reject accessed links | Update the resolved regular-file target in place and preserve every link | | Delete leaf link | Reject without mutation | Unlink the link, including dangling, cyclic, or external-target links | | Delete through linked parent | Reject without mutation | Delete the contained target entry, leaving the parent link intact | | Recursive delete | Preflight all descendants and reject any link before mutation | Preflight all descendants; unlink links without traversing their targets | @@ -179,6 +180,15 @@ helpers for independent project/source/managed boundaries. translation match the previous configuration writer. An encoding or I/O failure propagates, and a write failure can leave truncated/partial content. This is not hard-link confinement: a hard-linked alias can observe updates. + After policy resolution, POSIX opens each resolved directory relative to an + already-open parent descriptor with no-follow flags, then opens the leaf + without truncation. Windows pins each resolved directory with non-reparse + handles withholding delete sharing, then opens/creates a non-reparse leaf + without truncation and holds it through text I/O. Both paths check the opened + file type before truncating that same descriptor. An exchanged parent cannot + redirect creation or truncation through a new link. Allowed links are still + resolved by the normal policy walk; the anchored traversal operates on their + resolved target, not on the original link spelling. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. @@ -209,22 +219,29 @@ entries, not reject a whole project for excluded/unrelated links. Preflight detects static policy failures before recursive deletion or parent creation. Atomic writes recheck the original path before replacement, and -deletion rechecks each accessed entry. Portable path checks are **not** a +deletion rechecks each accessed entry. Except for the anchored +`overwrite_text` operation described above, portable path checks are **not** a race-free sandbox: another process can exchange parents or entries between checks and syscalls, and an I/O failure during mutation can leave partial results. Protect against concurrent untrusted mutation separately; descriptor- -relative traversal or platform-specific mechanisms are future work, not a -claim of this API. The helper does not constrain subprocesses or third-party -code. Exclusive creation uses `O_EXCL` and `O_NOFOLLOW` where available. +relative traversal or platform-specific mechanisms for the remaining operations +are future work, not a claim of this API. The helper does not constrain +subprocesses or third-party code. Exclusive creation uses `O_EXCL` and +`O_NOFOLLOW` where available. Existing safe-write mechanisms informed this helper, but existing shared infrastructure warning/skip behavior and development-mode link creation are unchanged. Migrate one owned operation boundary at a time, carrying original paths and an explicit root/policy into the helper before any early resolution. Linked command directories and development-mode registration remain dependent -stages. Non-atomic configuration writes preserve legacy metadata semantics; -portable preflight does not guarantee race-free protection against concurrent -path replacement. +stages. Non-atomic configuration writes preserve legacy metadata semantics. +`overwrite_text` keeps the resolved directory/file objects open, but does not +freeze directory membership on POSIX: an opened directory or file may be +renamed, and the operation continues against that opened object. The trusted +root's OS ancestors remain outside the helper's policy boundary. This is not +a general sandbox against concurrent namespace changes or hard-linked aliases. +Platforms without the required descriptor/handle primitives fail explicitly +rather than falling back to path-based overwrite. Windows path classification and directory-mode reparse rejection have portable regression tests. Native Windows path and junction tests also exist and are diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py new file mode 100644 index 0000000000..90d426dae3 --- /dev/null +++ b/src/specify_cli/_file_handles.py @@ -0,0 +1,95 @@ +"""Windows non-reparse handles for scoped filesystem operations.""" + +import errno +import os +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + + +def _windows_api(): + import ctypes + from ctypes import wintypes + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + kernel.CreateFileW.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.GetFileInformationByHandleEx.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD + ] + kernel.GetFileInformationByHandleEx.restype = wintypes.BOOL + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + kernel.CloseHandle.restype = wintypes.BOOL + return kernel + + +def _open_windows_handle(path: Path, *, directory: bool, overwrite: bool = False) -> int: + import ctypes + from ctypes import wintypes + + class AttributeTagInfo(ctypes.Structure): + _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)] + + kernel = _windows_api() + # Attribute-only directory handles do not prevent renaming; include + # FILE_LIST_DIRECTORY and withhold FILE_SHARE_DELETE for every ancestor. + handle = kernel.CreateFileW( + str(path), + (0x40000000 | 0x80) if overwrite else ((0x80 | 0x1) if directory else 0x80000000), + 0x3, + None, + 4 if overwrite else 3, # OPEN_ALWAYS never truncates an existing file. + 0x00200000 | 0x02000000, + None, + ) + if handle == wintypes.HANDLE(-1).value: + raise ctypes.WinError(ctypes.get_last_error()) + try: + attributes = AttributeTagInfo() + if not kernel.GetFileInformationByHandleEx( + handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes) + ): + raise ctypes.WinError(ctypes.get_last_error()) + if attributes.attributes & 0x400: + raise OSError(errno.ELOOP, "Refusing a reparse-point path", str(path)) + if bool(attributes.attributes & 0x10) != directory: + raise OSError(errno.EINVAL, "Unexpected file type", str(path)) + return handle + except BaseException: + kernel.CloseHandle(handle) + raise + + +@contextmanager +def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: + """Pin a non-reparse path by withholding Windows delete sharing.""" + handle = _open_windows_handle(path, directory=directory) + try: + yield handle + finally: + _windows_api().CloseHandle(handle) + + +@contextmanager +def _windows_overwrite_fd(path: Path) -> Iterator[int]: + """Open/create without truncation and transfer handle ownership to the CRT.""" + import msvcrt + + handle = _open_windows_handle(path, directory=False, overwrite=True) + try: + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) + except BaseException: + _windows_api().CloseHandle(handle) + raise + try: + yield fd + finally: + os.close(fd) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 49441ce494..64fe050204 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -1,16 +1,20 @@ """Scoped filesystem operations; see design/file-helper.md for the contract.""" -from dataclasses import dataclass, field import codecs import errno import os -from pathlib import Path, PurePath, PureWindowsPath import stat import tempfile +from collections.abc import Iterator +from contextlib import ExitStack, contextmanager +from dataclasses import dataclass, field +from pathlib import Path, PurePath, PureWindowsPath from typing import TypeVar +from specify_cli._file_handles import _windows_handle, _windows_overwrite_fd _PathType = TypeVar("_PathType", bound=PurePath) +_OVERWRITE_DIR_FD_SUPPORTED = os.open in os.supports_dir_fd def _strip_extended_length_prefix(path: _PathType) -> _PathType: @@ -217,11 +221,49 @@ def overwrite_text( if destination.exists(): self._require_file(destination) codecs.lookup(encoding) - flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC - flags |= getattr(os, "O_NOFOLLOW", 0) - fd = os.open(destination, flags, 0o666) - with os.fdopen(fd, "w", encoding=encoding) as stream: - stream.write(content) + with self._overwrite_descriptor(destination) as fd: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise UnsupportedPathError(f"Expected a regular file: {destination}") + os.ftruncate(fd, 0) + with os.fdopen(fd, "w", encoding=encoding, closefd=False) as stream: + stream.write(content) + + @contextmanager + def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: + """Anchor the resolved hierarchy before opening a non-truncating leaf.""" + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + if os.name == "nt": + current = self._canonical_root + stack.enter_context(_windows_handle(current, directory=True)) + for part in parts[:-1]: + current = current / part + stack.enter_context(_windows_handle(current, directory=True)) + yield stack.enter_context(_windows_overwrite_fd(destination)) + return + + if not ( + _OVERWRITE_DIR_FD_SUPPORTED + and getattr(os, "O_NOFOLLOW", 0) + and getattr(os, "O_DIRECTORY", 0) + and getattr(os, "O_NONBLOCK", 0) + ): + raise OSError(errno.ENOTSUP, "Scoped text overwrite is unsupported on this platform") + directory_flags = ( + os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + ) + parent = os.open(self._canonical_root, directory_flags) + stack.callback(os.close, parent) + for part in parts[:-1]: + parent = os.open(part, directory_flags, dir_fd=parent) + stack.callback(os.close, parent) + flags = ( + os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK + | getattr(os, "O_CLOEXEC", 0) + ) + fd = os.open(parts[-1], flags, 0o666, dir_fd=parent) + stack.callback(os.close, fd) + yield fd def symlink(self, target: Path | str, path: Path | str) -> None: """Create a link to an existing contained regular file or directory. diff --git a/src/specify_cli/workflows/_catalog_cache.py b/src/specify_cli/workflows/_catalog_cache.py index 5a64609bc0..784e7fb97d 100644 --- a/src/specify_cli/workflows/_catalog_cache.py +++ b/src/specify_cli/workflows/_catalog_cache.py @@ -12,64 +12,7 @@ from typing import Any from uuid import uuid4 - -@contextmanager -def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: - """Pin a non-reparse path by withholding Windows delete sharing.""" - import ctypes - from ctypes import wintypes - - class AttributeTagInfo(ctypes.Structure): - _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)] - - kernel = ctypes.WinDLL("kernel32", use_last_error=True) - create = kernel.CreateFileW - create.argtypes = [ - wintypes.LPCWSTR, - wintypes.DWORD, - wintypes.DWORD, - wintypes.LPVOID, - wintypes.DWORD, - wintypes.DWORD, - wintypes.HANDLE, - ] - create.restype = wintypes.HANDLE - info = kernel.GetFileInformationByHandleEx - info.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD] - info.restype = wintypes.BOOL - close = kernel.CloseHandle - close.argtypes = [wintypes.HANDLE] - close.restype = wintypes.BOOL - - # OPEN_REPARSE_POINT inspects the link itself; BACKUP_SEMANTICS permits - # directory handles. Holding every ancestor without FILE_SHARE_DELETE - # prevents a junction/symlink swap during path-based create/replace. - # Attribute-only handles bypass share checking: include FILE_LIST_DIRECTORY - # with FILE_READ_ATTRIBUTES so even an empty directory cannot be renamed. - handle = create( - str(path), - (0x80 | 0x1) if directory else 0x80000000, - 0x3, - None, - 3, - 0x00200000 | 0x02000000, - None, - ) - if handle == wintypes.HANDLE(-1).value: - raise ctypes.WinError(ctypes.get_last_error()) - try: - attributes = AttributeTagInfo() - if not info(handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes)): - raise ctypes.WinError(ctypes.get_last_error()) - if attributes.attributes & 0x400: - raise OSError( - errno.ELOOP, "Refusing a reparse-point catalog cache path", str(path) - ) - if bool(attributes.attributes & 0x10) != directory: - raise OSError(errno.EINVAL, "Unexpected catalog cache file type", str(path)) - yield handle - finally: - close(handle) +from specify_cli._file_handles import _windows_handle @contextmanager diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py new file mode 100644 index 0000000000..77728c6627 --- /dev/null +++ b/tests/test_file_handles.py @@ -0,0 +1,103 @@ +"""Portable checks of Windows handle flags, validation, and ownership.""" + +import ctypes +import os +import sys +from ctypes import wintypes +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from specify_cli import _file_handles + + +@pytest.fixture +def kernel(monkeypatch): + calls = [] + closed = [] + state = SimpleNamespace(attributes=0, query_ok=True, handle=123) + + def create(*args): + calls.append(args) + return state.handle + + def query(handle, info_class, output, size): + assert handle == 123 and info_class == 9 + output._obj.attributes = state.attributes + return state.query_ok + + api = SimpleNamespace( + CreateFileW=create, + GetFileInformationByHandleEx=query, + CloseHandle=closed.append, + ) + monkeypatch.setattr(_file_handles, "_windows_api", lambda: api) + monkeypatch.setattr(ctypes, "get_last_error", lambda: 5, raising=False) + monkeypatch.setattr(ctypes, "WinError", lambda code: OSError(code, "native error"), raising=False) + return state, calls, closed + + +@pytest.mark.parametrize("directory", [False, True]) +def test_read_handle_retains_existing_access_and_sharing(kernel, directory): + state, calls, closed = kernel + state.attributes = 0x10 if directory else 0 + with _file_handles._windows_handle(Path("path"), directory=directory) as handle: + assert handle == 123 + assert closed == [] + assert calls == [ + ("path", 0x81 if directory else 0x80000000, 0x3, None, 3, 0x02200000, None) + ] + assert closed == [123] + + +@pytest.mark.parametrize("failure", ["reparse", "directory", "query", "open"]) +def test_windows_overwrite_handle_checks_before_transfer(kernel, failure): + state, calls, closed = kernel + if failure == "reparse": + state.attributes = 0x400 + elif failure == "directory": + state.attributes = 0x10 + elif failure == "query": + state.query_ok = False + else: + state.handle = wintypes.HANDLE(-1).value + with pytest.raises(OSError): + _file_handles._open_windows_handle(Path("path"), directory=False, overwrite=True) + assert calls == [("path", 0x40000080, 0x3, None, 4, 0x02200000, None)] + assert closed == ([] if failure == "open" else [123]) + + +@pytest.mark.parametrize("failure", [None, "convert", "body"]) +def test_overwrite_descriptor_ownership_and_binary_mode(kernel, monkeypatch, failure): + state, calls, closed_handles = kernel + closed_fds = [] + + def convert(handle, flags): + assert handle == state.handle + assert flags == os.O_WRONLY | 0x8000 + if failure == "convert": + raise OSError("conversion failed") + return 42 + + monkeypatch.setitem(sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=convert)) + monkeypatch.setattr( + _file_handles, "os", + SimpleNamespace(O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, close=closed_fds.append), + ) + + def run(): + with _file_handles._windows_overwrite_fd(Path("path")) as fd: + assert fd == 42 + assert closed_handles == closed_fds == [] + if failure == "body": + raise OSError("body failed") + + if failure: + with pytest.raises(OSError, match="failed"): + run() + else: + run() + assert calls[0][4] == 4 # OPEN_ALWAYS, never CREATE_ALWAYS. + assert closed_handles == ([123] if failure == "convert" else []) + assert closed_fds == ([] if failure == "convert" else [42]) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py new file mode 100644 index 0000000000..2752a633a5 --- /dev/null +++ b/tests/test_file_helper_overwrite.py @@ -0,0 +1,410 @@ +"""Handle-based non-atomic text overwrite behavior.""" + +import os +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from specify_cli import file_helper +from specify_cli.file_helper import FileHelper, UnsupportedPathError + + +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("existing", [False, True]) +def test_parent_swap_after_validation_does_not_redirect_overwrite( + tmp_path, monkeypatch, allow, existing +): + root = tmp_path / "project" + parent = root / "parent" + parent.mkdir(parents=True) + outside = tmp_path / "outside" + outside.mkdir() + if existing: + (parent / "file").write_text("inside") + (outside / "file").write_text("outside") + try: + probe = root / "probe" + probe.symlink_to(outside, target_is_directory=True) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + original = FileHelper._path + swapped = False + + def swap(self, path, **kwargs): + nonlocal swapped + destination = original(self, path, **kwargs) + if not swapped: + swapped = True + parent.rename(root / "original") + parent.symlink_to(outside, target_is_directory=True) + return destination + + monkeypatch.setattr(FileHelper, "_path", swap) + with pytest.raises(OSError): + FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new") + assert swapped + if existing: + assert (outside / "file").read_text() == "outside" + assert (root / "original/file").read_text() == "inside" + else: + assert not (outside / "file").exists() + assert not (root / "original/file").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative open required") +@pytest.mark.parametrize("kind", ["symlink", "fifo", "directory"]) +def test_leaf_replacement_at_open_is_checked_before_truncation(tmp_path, monkeypatch, kind): + root = tmp_path / "project" + root.mkdir() + leaf = root / "file" + leaf.write_text("original") + outside = tmp_path / "outside" + outside.write_text("outside") + original = os.open + reader = None + + def swap(path, flags, *args, **kwargs): + nonlocal reader + if Path(path).name == "file": + leaf.rename(root / "original") + if kind == "symlink": + leaf.symlink_to(outside) + elif kind == "fifo": + os.mkfifo(leaf) + reader = original(leaf, os.O_RDWR | os.O_NONBLOCK) + else: + leaf.mkdir() + return original(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", swap) + try: + with pytest.raises((OSError, UnsupportedPathError)): + FileHelper(root).overwrite_text("file", "new") + if reader is not None: + with pytest.raises(BlockingIOError): + os.read(reader, 100) + finally: + if reader is not None: + os.close(reader) + assert outside.read_text() == "outside" + assert (root / "original").read_text() == "original" + + +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("encoding", ["utf-8", "utf-16", "cp1252"]) +def test_overwrite_matches_native_text_and_preserves_hardlinks(tmp_path, allow, encoding): + root = tmp_path / "project" + root.mkdir() + reference = root / "reference" + content = "caf\u00e9\nsecond\r\n" + reference.write_text(content, encoding=encoding) + files = FileHelper(root, allow_symlinks=allow) + files.overwrite_text("file", "a longer old value") + path = root / "file" + alias = root / "hardlink" + os.link(path, alias) + before = path.stat() + files.overwrite_text("file", content, encoding=encoding) + assert path.read_bytes() == reference.read_bytes() == alias.read_bytes() + assert path.stat().st_ino == alias.stat().st_ino == before.st_ino + assert path.stat().st_mode == before.st_mode == reference.stat().st_mode + files.overwrite_text("file", "") + assert path.read_bytes() == alias.read_bytes() == b"" + + +@pytest.mark.parametrize("allow", [False, True]) +def test_overwrite_trusted_root_alias_and_contained_link_chains(tmp_path, allow): + root = tmp_path / "project" + directory = root / "directory" + directory.mkdir(parents=True) + trusted = tmp_path / "trusted" + try: + trusted.symlink_to(root, target_is_directory=True) + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + files = FileHelper(trusted, allow_symlinks=allow) + files.overwrite_text(trusted / "directory/file", "old") + if allow: + (root / "parent").symlink_to("directory", target_is_directory=True) + (root / "parent-chain").symlink_to("parent", target_is_directory=True) + (directory / "alias").symlink_to("file") + (directory / "chain").symlink_to("alias") + files.overwrite_text(trusted / "parent-chain/chain", "new") + assert (directory / "file").read_text() == "new" + assert all( + path.is_symlink() + for path in (root / "parent", root / "parent-chain", directory / "alias", directory / "chain") + ) + else: + assert (directory / "file").read_text() == "old" + assert trusted.is_symlink() + + +@pytest.mark.parametrize("allow", [False, True]) +def test_missing_parent_and_invalid_codec_do_not_create_or_truncate(tmp_path, allow): + files = FileHelper(tmp_path, allow_symlinks=allow) + with pytest.raises(FileNotFoundError): + files.overwrite_text("missing/file", "new") + assert not (tmp_path / "missing").exists() + path = tmp_path / "file" + path.write_text("old") + with pytest.raises(LookupError): + files.overwrite_text("file", "new", encoding="not-a-codec") + assert path.read_text() == "old" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor capability required") +@pytest.mark.parametrize("existing", [False, True]) +def test_unsupported_descriptor_backend_fails_without_path_fallback(tmp_path, monkeypatch, existing): + path = tmp_path / "file" + if existing: + path.write_text("old") + monkeypatch.setattr(file_helper, "_OVERWRITE_DIR_FD_SUPPORTED", False) + with pytest.raises(OSError, match="unsupported"): + FileHelper(tmp_path).overwrite_text("file", "new") + if existing: + assert path.read_text() == "old" + else: + assert not path.exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor cleanup required") +@pytest.mark.parametrize("failure", ["open", "fstat", "ftruncate", "fdopen", "write"]) +def test_overwrite_closes_descriptors_on_failure(tmp_path, monkeypatch, failure): + parent = tmp_path / "parent" + parent.mkdir() + (parent / "file").write_text("old") + opened = [] + original = os.open + fstat = os.fstat + + def observe(path, flags, *args, **kwargs): + if failure == "open" and Path(path).name == "file": + raise PermissionError("test failure") + fd = original(path, flags, *args, **kwargs) + opened.append(fd) + return fd + + def fail(*args, **kwargs): + raise OSError("test failure") + + class FailedStream: + def __enter__(self): + return self + + def __exit__(self, *args): + return False + + write = fail + + replacements = {"open": observe} + if failure == "write": + replacements["fdopen"] = lambda *args, **kwargs: FailedStream() + elif failure != "open": + replacements[failure] = fail + monkeypatch.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), **replacements})) + with pytest.raises(OSError, match="test failure"): + FileHelper(tmp_path).overwrite_text("parent/file", "new") + assert opened + for fd in opened: + with pytest.raises(OSError): + fstat(fd) + + +@pytest.mark.parametrize("failed_parent", [None, "parent"]) +def test_windows_overwrite_pins_resolved_hierarchy_until_stream_closes( + tmp_path, monkeypatch, failed_parent +): + parent = tmp_path / "parent" + parent.mkdir() + leaf = parent / "file" + leaf.write_text("old") + events = [] + active = [] + + @contextmanager + def pin(path, *, directory): + assert directory + events.append(("pin", path)) + if path.name == failed_parent: + raise PermissionError("pin failed") + active.append(path) + try: + yield 1 + finally: + assert active.pop() == path + events.append(("unpin", path)) + + @contextmanager + def open_leaf(path): + assert active == [tmp_path, parent] + assert leaf.read_text() == "old" + fd = os.open(path, os.O_WRONLY) + try: + yield fd + assert leaf.read_text() == "new" + assert active == [tmp_path, parent] + finally: + os.close(fd) + events.append(("close", path)) + + monkeypatch.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt"})) + monkeypatch.setattr(file_helper, "_windows_handle", pin) + monkeypatch.setattr(file_helper, "_windows_overwrite_fd", open_leaf) + if failed_parent: + with pytest.raises(PermissionError, match="pin failed"): + FileHelper(tmp_path).overwrite_text("parent/file", "new") + assert leaf.read_text() == "old" + else: + FileHelper(tmp_path).overwrite_text("parent/file", "new") + assert events[-3:] == [("close", leaf), ("unpin", parent), ("unpin", tmp_path)] + assert not active + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows sharing semantics required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_overwrite_holds_every_parent_and_leaf(tmp_path, monkeypatch, existing, allow): + root = tmp_path / "project" + parent = root / "parent" + parent.mkdir(parents=True) + leaf = parent / "file" + if existing: + leaf.write_text("old") + original = os.ftruncate + open_leaf = file_helper._windows_overwrite_fd + attempted = [] + parents_checked = [] + + @contextmanager + def open_while_pinned(path): + 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: + yield fd + + def truncate(fd, length): + for path in (root, parent, leaf): + with pytest.raises(PermissionError): + path.rename(path.with_name(path.name + "-moved")) + attempted.append(path) + return original(fd, length) + + monkeypatch.setattr(os, "ftruncate", truncate) + monkeypatch.setattr(file_helper, "_windows_overwrite_fd", open_while_pinned) + FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new") + assert parents_checked == [root, parent] + assert attempted == [root, parent, leaf] + assert leaf.read_text() == "new" + leaf.rename(parent / "finished") + parent.rename(root / "finished") + root.rename(tmp_path / "finished") + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows reparse semantics required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_leaf_swap_at_open_never_follows_new_link( + tmp_path, monkeypatch, existing, allow +): + root = tmp_path / "project" + root.mkdir() + leaf = root / "file" + outside = tmp_path / "outside" + outside.write_text("outside") + try: + probe = root / "probe" + probe.symlink_to(outside) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + if existing: + leaf.write_text("old") + original = file_helper._windows_overwrite_fd + + @contextmanager + def swap(path): + if existing: + leaf.rename(root / "original") + leaf.symlink_to(outside) + with original(path) as fd: + yield fd + + monkeypatch.setattr(file_helper, "_windows_overwrite_fd", swap) + with pytest.raises(OSError): + FileHelper(root, allow_symlinks=allow).overwrite_text("file", "new") + assert leaf.is_symlink() + assert outside.read_text() == "outside" + if existing: + assert (root / "original").read_text() == "old" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative open required") +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("existing", [False, True]) +def test_parent_swap_at_leaf_open_uses_anchored_directory( + tmp_path, monkeypatch, allow, existing +): + root = tmp_path / "project" + parent = root / "parent" + parent.mkdir(parents=True) + outside = tmp_path / "outside" + outside.mkdir() + if existing: + (parent / "file").write_text("inside") + (outside / "file").write_text("outside") + original = os.open + swapped = False + + def swap(path, flags, *args, **kwargs): + nonlocal swapped + if Path(path).name == "file": + swapped = True + parent.rename(root / "original") + parent.symlink_to(outside, target_is_directory=True) + return original(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", swap) + FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new") + assert swapped + assert (root / "original/file").read_text() == "new" + if existing: + assert (outside / "file").read_text() == "outside" + else: + assert not (outside / "file").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX opened-file rename semantics required") +@pytest.mark.parametrize("allow", [False, True]) +def test_leaf_swap_after_open_keeps_truncation_and_write_on_opened_file( + tmp_path, monkeypatch, allow +): + root = tmp_path / "project" + root.mkdir() + leaf = root / "file" + leaf.write_text("a longer old value") + inode = leaf.stat().st_ino + outside = tmp_path / "outside" + outside.write_text("outside") + original = os.ftruncate + swapped = False + + def swap(fd, length): + nonlocal swapped + swapped = True + leaf.rename(root / "original") + leaf.symlink_to(outside) + return original(fd, length) + + monkeypatch.setattr(os, "ftruncate", swap) + FileHelper(root, allow_symlinks=allow).overwrite_text("file", "new") + assert swapped + assert outside.read_text() == "outside" + assert leaf.is_symlink() + assert (root / "original").read_text() == "new" + assert (root / "original").stat().st_ino == inode From 6f90d1ae13ec89f585642f70048478d3d1dc2476 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:31:35 -0600 Subject: [PATCH 02/13] Preserve overwrite permission semantics across platforms Honor the Windows creation mask, retain access through searchable unreadable POSIX directories, and inject overwrite failures at the shared descriptor boundary. Cover native creation-mask parity and directory permission success and failure cases. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 10 ++- src/specify_cli/_file_handles.py | 9 ++- src/specify_cli/file_helper.py | 3 +- tests/test_file_handles.py | 36 ++++++++++- tests/test_file_helper.py | 2 +- tests/test_file_helper_overwrite.py | 95 +++++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 8 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 8f2b33f926..51ab04aad4 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -181,14 +181,18 @@ helpers for independent project/source/managed boundaries. failure propagates, and a write failure can leave truncated/partial content. This is not hard-link confinement: a hard-linked alias can observe updates. After policy resolution, POSIX opens each resolved directory relative to an - already-open parent descriptor with no-follow flags, then opens the leaf - without truncation. Windows pins each resolved directory with non-reparse - handles withholding delete sharing, then opens/creates a non-reparse leaf + already-open parent descriptor with no-follow flags, using search/path-only + access where supported so unreadable but searchable parents remain usable, + then opens the leaf without truncation. Windows pins each resolved directory + with non-reparse handles withholding delete sharing, then opens/creates a non-reparse leaf without truncation and holds it through text I/O. Both paths check the opened file type before truncating that same descriptor. An exchanged parent cannot redirect creation or truncation through a new link. Allowed links are still resolved by the normal policy walk; the anchored traversal operates on their resolved target, not on the original link spelling. + 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. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 90d426dae3..f704db3aa9 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -39,6 +39,13 @@ class AttributeTagInfo(ctypes.Structure): _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)] kernel = _windows_api() + flags = 0x00200000 | 0x02000000 + if overwrite: + # The CRT exposes no read-only mask query; restore it before opening. + mask = os.umask(0o200) + os.umask(mask) + if mask & 0o200: + flags |= 0x1 # FILE_ATTRIBUTE_READONLY for newly created files. # Attribute-only directory handles do not prevent renaming; include # FILE_LIST_DIRECTORY and withhold FILE_SHARE_DELETE for every ancestor. handle = kernel.CreateFileW( @@ -47,7 +54,7 @@ class AttributeTagInfo(ctypes.Structure): 0x3, None, 4 if overwrite else 3, # OPEN_ALWAYS never truncates an existing file. - 0x00200000 | 0x02000000, + flags, None, ) if handle == wintypes.HANDLE(-1).value: diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 64fe050204..7f15b01c4b 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -250,7 +250,8 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: ): raise OSError(errno.ENOTSUP, "Scoped text overwrite is unsupported on this platform") directory_flags = ( - os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + getattr(os, "O_SEARCH", getattr(os, "O_PATH", os.O_RDONLY)) + | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) ) parent = os.open(self._canonical_root, directory_flags) stack.callback(os.close, parent) diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 77728c6627..4ff39fa767 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -16,7 +16,11 @@ def kernel(monkeypatch): calls = [] closed = [] - state = SimpleNamespace(attributes=0, query_ok=True, handle=123) + state = SimpleNamespace(attributes=0, query_ok=True, handle=123, mask=0) + + def umask(value): + previous, state.mask = state.mask, value + return previous def create(*args): calls.append(args) @@ -33,6 +37,7 @@ def query(handle, info_class, output, size): CloseHandle=closed.append, ) monkeypatch.setattr(_file_handles, "_windows_api", lambda: api) + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{**vars(os), "umask": umask})) monkeypatch.setattr(ctypes, "get_last_error", lambda: 5, raising=False) monkeypatch.setattr(ctypes, "WinError", lambda code: OSError(code, "native error"), raising=False) return state, calls, closed @@ -51,6 +56,30 @@ def test_read_handle_retains_existing_access_and_sharing(kernel, directory): assert closed == [123] +@pytest.mark.parametrize("mask", [0, 0o200, 0o400, 0o600]) +@pytest.mark.parametrize("query_ok", [False, True]) +def test_windows_creation_flags_honor_and_restore_crt_mask(kernel, monkeypatch, mask, query_ok): + state, calls, closed = kernel + state.query_ok = query_ok + current_mask = mask + + def umask(value): + nonlocal current_mask + previous, current_mask = current_mask, value + return previous + + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(umask=umask)) + if query_ok: + handle = _file_handles._open_windows_handle(Path("path"), directory=False, overwrite=True) + assert handle == 123 + else: + with pytest.raises(OSError): + _file_handles._open_windows_handle(Path("path"), directory=False, overwrite=True) + assert current_mask == mask + assert bool(calls[0][5] & 0x1) == bool(mask & 0o200) + assert closed == ([] if query_ok else [123]) + + @pytest.mark.parametrize("failure", ["reparse", "directory", "query", "open"]) def test_windows_overwrite_handle_checks_before_transfer(kernel, failure): state, calls, closed = kernel @@ -83,7 +112,10 @@ def convert(handle, flags): monkeypatch.setitem(sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=convert)) monkeypatch.setattr( _file_handles, "os", - SimpleNamespace(O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, close=closed_fds.append), + SimpleNamespace( + O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, + close=closed_fds.append, umask=lambda value: 0, + ), ) def run(): diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index a04b9e0a34..18268c04c9 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -149,7 +149,7 @@ def test_overwrite_text_io_errors_propagate(root, monkeypatch, allow): def denied(*args, **kwargs): raise PermissionError("denied") - monkeypatch.setattr("specify_cli.file_helper.os.open", denied) + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", denied) with pytest.raises(PermissionError, match="denied"): FileHelper(root, allow_symlinks=allow).overwrite_text("new", "text") assert not (root / "new").exists() diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 2752a633a5..87b4ff89f0 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -115,6 +115,101 @@ def test_overwrite_matches_native_text_and_preserves_hardlinks(tmp_path, allow, assert path.read_bytes() == alias.read_bytes() == b"" +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("restricted", ["root", "parent"]) +def test_searchable_unreadable_directory_retains_native_overwrite_behavior( + tmp_path, existing, allow, restricted +): + root = tmp_path / "project" + parent = root / "parent" + parent.mkdir(parents=True) + native = parent / "native" + leaf = parent / "file" + if existing: + native.write_text("longer old content") + leaf.write_text("longer old content") + directory = root if restricted == "root" else parent + directory.chmod(0o300) + try: + try: + os.listdir(directory) + except PermissionError: + pass + else: + pytest.skip("This process can read directories without read permission") + native.write_text("new\n") + FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new\n") + assert leaf.read_bytes() == native.read_bytes() + assert leaf.stat().st_mode == native.stat().st_mode + finally: + directory.chmod(0o700) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_unsearchable_parent_still_rejects_overwrite(tmp_path, existing, allow): + parent = tmp_path / "parent" + parent.mkdir() + leaf = parent / "file" + native = parent / "native" + if existing: + leaf.write_text("old") + native.write_text("old") + parent.chmod(0o600) + try: + try: + native.write_text("new") + except PermissionError: + pass + else: + pytest.skip("This process can traverse directories without search permission") + with pytest.raises(PermissionError): + FileHelper(tmp_path, allow_symlinks=allow).overwrite_text("parent/file", "new") + finally: + parent.chmod(0o700) + if existing: + assert leaf.read_text() == "old" + else: + assert not leaf.exists() + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows CRT mask semantics required") +@pytest.mark.parametrize("mask", [0, 0o200]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_overwrite_creation_matches_masked_native_creation(tmp_path, mask, allow): + native = tmp_path / "native" + leaf = tmp_path / "file" + existing = tmp_path / "existing" + existing.write_text("longer old content") + before = existing.stat() + previous_mask = os.umask(mask) + try: + native.write_text("caf\u00e9\n") + files = FileHelper(tmp_path, allow_symlinks=allow) + files.overwrite_text("file", "caf\u00e9\n") + files.overwrite_text("existing", "new") + assert leaf.read_bytes() == native.read_bytes() + assert leaf.stat().st_mode == native.stat().st_mode + assert existing.stat().st_mode == before.st_mode + assert existing.stat().st_ino == before.st_ino + assert existing.read_text() == "new" + assert os.umask(mask) == mask + for path in (native, leaf): + if mask & 0o200: + with pytest.raises(PermissionError): + path.write_text("again") + else: + path.write_text("again") + finally: + os.umask(previous_mask) + for path in (native, leaf): + if path.exists(): + path.chmod(0o600) + + @pytest.mark.parametrize("allow", [False, True]) def test_overwrite_trusted_root_alias_and_contained_link_chains(tmp_path, allow): root = tmp_path / "project" From 071a543583e672ae9f5a04a4bc8a97e4ea70f53a Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:42:00 -0600 Subject: [PATCH 03/13] Support search-only directory access on older Darwin builds Use the Darwin kernel search bit when Python does not expose O_SEARCH or O_PATH, and exercise the missing-constant branch for existing and new overwrite destinations. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/specify_cli/file_helper.py | 8 ++++++-- tests/test_file_helper_overwrite.py | 11 ++++++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 7f15b01c4b..80097ff509 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -4,6 +4,7 @@ import errno import os import stat +import sys import tempfile from collections.abc import Iterator from contextlib import ExitStack, contextmanager @@ -249,9 +250,12 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: and getattr(os, "O_NONBLOCK", 0) ): raise OSError(errno.ENOTSUP, "Scoped text overwrite is unsupported on this platform") + directory_access = getattr(os, "O_SEARCH", getattr(os, "O_PATH", None)) + if directory_access is None: + # Older Darwin Python builds omit the kernel's O_EXEC/O_SEARCH bit. + directory_access = 0x40000000 if sys.platform == "darwin" else os.O_RDONLY directory_flags = ( - getattr(os, "O_SEARCH", getattr(os, "O_PATH", os.O_RDONLY)) - | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + directory_access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) ) parent = os.open(self._canonical_root, directory_flags) stack.callback(os.close, parent) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 87b4ff89f0..09c4d74151 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -1,6 +1,7 @@ """Handle-based non-atomic text overwrite behavior.""" import os +import sys from contextlib import contextmanager from pathlib import Path from types import SimpleNamespace @@ -119,9 +120,17 @@ def test_overwrite_matches_native_text_and_preserves_hardlinks(tmp_path, allow, @pytest.mark.parametrize("existing", [False, True]) @pytest.mark.parametrize("allow", [False, True]) @pytest.mark.parametrize("restricted", ["root", "parent"]) +@pytest.mark.parametrize( + "legacy_macos", + [False, pytest.param(True, marks=pytest.mark.skipif(sys.platform != "darwin", reason="Darwin flags"))], +) def test_searchable_unreadable_directory_retains_native_overwrite_behavior( - tmp_path, existing, allow, restricted + tmp_path, monkeypatch, existing, allow, restricted, legacy_macos ): + if legacy_macos: + monkeypatch.setattr(file_helper, "os", SimpleNamespace(**{ + key: value for key, value in vars(os).items() if key not in ("O_SEARCH", "O_PATH", "O_EXEC") + })) root = tmp_path / "project" parent = root / "parent" parent.mkdir(parents=True) From 6bd21403cc0249d6a339a361e2a38cc226eab26d Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:42:59 -0600 Subject: [PATCH 04/13] Match reference encoding in Windows creation-mask tests Compare native creation with the overwrite API's UTF-8 default explicitly, including on Python versions whose Windows locale encoding differs. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper_overwrite.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 09c4d74151..0a45c70e42 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -196,7 +196,7 @@ def test_native_windows_overwrite_creation_matches_masked_native_creation(tmp_pa before = existing.stat() previous_mask = os.umask(mask) try: - native.write_text("caf\u00e9\n") + native.write_text("caf\u00e9\n", encoding="utf-8") files = FileHelper(tmp_path, allow_symlinks=allow) files.overwrite_text("file", "caf\u00e9\n") files.overwrite_text("existing", "new") From e21506c3b9e5ed6c8304ce35ab7468702f6fe3ac Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:03:29 -0600 Subject: [PATCH 05/13] Bound overwrite handles without changing the process mask Let exclusive CRT creation apply Windows creation masks while retaining anchored existing-file opens. Close previous POSIX directory descriptors during traversal and clarify overwrite limitations. Cover interleaved calls, deep paths under low descriptor limits, and Windows creation collisions. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 14 ++- src/specify_cli/_file_handles.py | 33 +++---- src/specify_cli/file_helper.py | 27 ++--- tests/test_file_handles.py | 146 +++++++++++++++++++++++++--- tests/test_file_helper_overwrite.py | 85 +++++++++++++++- 5 files changed, 257 insertions(+), 48 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 51ab04aad4..8c434d0b60 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -183,9 +183,14 @@ helpers for independent project/source/managed boundaries. After policy resolution, POSIX opens each resolved directory relative to an already-open parent descriptor with no-follow flags, using search/path-only access where supported so unreadable but searchable parents remain usable, - then opens the leaf without truncation. Windows pins each resolved directory - with non-reparse handles withholding delete sharing, then opens/creates a non-reparse leaf - without truncation and holds it through text I/O. Both paths check the opened + and closes the previous directory after opening its child. Descriptor usage + stays bounded independently of path depth. It then opens the leaf without + truncation. Windows retains every resolved directory's non-reparse handle, + withholding delete sharing, and opens an existing non-reparse leaf without + truncation. For a missing leaf, it uses exclusive CRT creation so the CRT + applies the process mask without querying or changing it in the helper. A + leaf introduced between these calls causes an explicit creation error. + The opened leaf remains held through text I/O. Both paths check the opened file type before truncating that same descriptor. An exchanged parent cannot redirect creation or truncation through a new link. Allowed links are still resolved by the normal policy walk; the anchored traversal operates on their @@ -223,8 +228,7 @@ entries, not reject a whole project for excluded/unrelated links. Preflight detects static policy failures before recursive deletion or parent creation. Atomic writes recheck the original path before replacement, and -deletion rechecks each accessed entry. Except for the anchored -`overwrite_text` operation described above, portable path checks are **not** a +deletion rechecks each accessed entry. Portable path checks are **not** a race-free sandbox: another process can exchange parents or entries between checks and syscalls, and an I/O failure during mutation can leave partial results. Protect against concurrent untrusted mutation separately; descriptor- diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index f704db3aa9..b72eb453ec 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -39,13 +39,6 @@ class AttributeTagInfo(ctypes.Structure): _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)] kernel = _windows_api() - flags = 0x00200000 | 0x02000000 - if overwrite: - # The CRT exposes no read-only mask query; restore it before opening. - mask = os.umask(0o200) - os.umask(mask) - if mask & 0o200: - flags |= 0x1 # FILE_ATTRIBUTE_READONLY for newly created files. # Attribute-only directory handles do not prevent renaming; include # FILE_LIST_DIRECTORY and withhold FILE_SHARE_DELETE for every ancestor. handle = kernel.CreateFileW( @@ -53,8 +46,8 @@ class AttributeTagInfo(ctypes.Structure): (0x40000000 | 0x80) if overwrite else ((0x80 | 0x1) if directory else 0x80000000), 0x3, None, - 4 if overwrite else 3, # OPEN_ALWAYS never truncates an existing file. - flags, + 3, # OPEN_EXISTING never creates or truncates a file. + 0x00200000 | 0x02000000, None, ) if handle == wintypes.HANDLE(-1).value: @@ -87,15 +80,21 @@ def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: @contextmanager def _windows_overwrite_fd(path: Path) -> Iterator[int]: - """Open/create without truncation and transfer handle ownership to the CRT.""" - import msvcrt - - handle = _open_windows_handle(path, directory=False, overwrite=True) + """Open an existing target, or exclusively create it through the CRT.""" try: - fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) - except BaseException: - _windows_api().CloseHandle(handle) - raise + handle = _open_windows_handle(path, directory=False, overwrite=True) + except FileNotFoundError: + # Exclusive CRT creation applies the process mask without following + # a leaf introduced after the existing-file open. + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o666) + else: + try: + import msvcrt + + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) + except BaseException: + _windows_api().CloseHandle(handle) + raise try: yield fd finally: diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 80097ff509..60039003fb 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -258,17 +258,22 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: directory_access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) ) parent = os.open(self._canonical_root, directory_flags) - stack.callback(os.close, parent) - for part in parts[:-1]: - parent = os.open(part, directory_flags, dir_fd=parent) - stack.callback(os.close, parent) - flags = ( - os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK - | getattr(os, "O_CLOEXEC", 0) - ) - fd = os.open(parts[-1], flags, 0o666, dir_fd=parent) - stack.callback(os.close, fd) - yield fd + try: + for part in parts[:-1]: + child = os.open(part, directory_flags, dir_fd=parent) + os.close(parent) + parent = child + flags = ( + os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK + | getattr(os, "O_CLOEXEC", 0) + ) + fd = os.open(parts[-1], flags, 0o666, dir_fd=parent) + try: + yield fd + finally: + os.close(fd) + finally: + os.close(parent) def symlink(self, target: Path | str, path: Path | str) -> None: """Create a link to an existing contained regular file or directory. diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 4ff39fa767..962e63cd7c 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -3,6 +3,8 @@ import ctypes import os import sys +import threading +from concurrent.futures import ThreadPoolExecutor from ctypes import wintypes from pathlib import Path from types import SimpleNamespace @@ -16,11 +18,10 @@ def kernel(monkeypatch): calls = [] closed = [] - state = SimpleNamespace(attributes=0, query_ok=True, handle=123, mask=0) + state = SimpleNamespace(attributes=0, query_ok=True, handle=123) def umask(value): - previous, state.mask = state.mask, value - return previous + raise AssertionError("Handle operations must not change the process mask") def create(*args): calls.append(args) @@ -58,15 +59,11 @@ def test_read_handle_retains_existing_access_and_sharing(kernel, directory): @pytest.mark.parametrize("mask", [0, 0o200, 0o400, 0o600]) @pytest.mark.parametrize("query_ok", [False, True]) -def test_windows_creation_flags_honor_and_restore_crt_mask(kernel, monkeypatch, mask, query_ok): +def test_existing_windows_overwrite_does_not_query_creation_mask(kernel, monkeypatch, mask, query_ok): state, calls, closed = kernel state.query_ok = query_ok - current_mask = mask - def umask(value): - nonlocal current_mask - previous, current_mask = current_mask, value - return previous + raise AssertionError(f"Existing-file open must not query or change mask {mask:o}") monkeypatch.setattr(_file_handles, "os", SimpleNamespace(umask=umask)) if query_ok: @@ -75,8 +72,7 @@ def umask(value): else: with pytest.raises(OSError): _file_handles._open_windows_handle(Path("path"), directory=False, overwrite=True) - assert current_mask == mask - assert bool(calls[0][5] & 0x1) == bool(mask & 0o200) + assert calls == [("path", 0x40000080, 0x3, None, 3, 0x02200000, None)] assert closed == ([] if query_ok else [123]) @@ -93,7 +89,7 @@ def test_windows_overwrite_handle_checks_before_transfer(kernel, failure): state.handle = wintypes.HANDLE(-1).value with pytest.raises(OSError): _file_handles._open_windows_handle(Path("path"), directory=False, overwrite=True) - assert calls == [("path", 0x40000080, 0x3, None, 4, 0x02200000, None)] + assert calls == [("path", 0x40000080, 0x3, None, 3, 0x02200000, None)] assert closed == ([] if failure == "open" else [123]) @@ -114,7 +110,7 @@ def convert(handle, flags): _file_handles, "os", SimpleNamespace( O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, - close=closed_fds.append, umask=lambda value: 0, + close=closed_fds.append, ), ) @@ -130,6 +126,128 @@ def run(): run() else: run() - assert calls[0][4] == 4 # OPEN_ALWAYS, never CREATE_ALWAYS. + assert calls[0][4] == 3 # OPEN_EXISTING, never CREATE_ALWAYS. assert closed_handles == ([123] if failure == "convert" else []) assert closed_fds == ([] if failure == "convert" else [42]) + + +@pytest.mark.parametrize("mask", [0, 0o200, 0o400, 0o600]) +@pytest.mark.parametrize("body_failure", [False, True]) +def test_missing_windows_leaf_uses_exclusive_crt_creation( + kernel, monkeypatch, mask, body_failure +): + state, calls, closed_handles = kernel + state.handle = wintypes.HANDLE(-1).value + monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) + created = [] + closed_fds = [] + + def create(path, flags, mode): + created.append((path, flags, mode, mode & ~mask)) + return 42 + + def umask(value): + raise AssertionError("Creation must let the CRT apply the mask") + + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{ + **vars(os), "O_BINARY": 0x8000, "open": create, + "close": closed_fds.append, "umask": umask, + })) + + def write(): + with _file_handles._windows_overwrite_fd(Path("new")) as fd: + assert fd == 42 + assert closed_fds == [] + if body_failure: + raise OSError("write failed") + + if body_failure: + with pytest.raises(OSError, match="write failed"): + write() + else: + write() + assert created == [ + (Path("new"), os.O_WRONLY | os.O_CREAT | os.O_EXCL | 0x8000, 0o666, 0o666 & ~mask) + ] + assert calls[0][4] == 3 + assert closed_handles == [] + assert closed_fds == [42] + + +@pytest.mark.parametrize("error", [FileExistsError, PermissionError, FileNotFoundError]) +def test_windows_crt_creation_errors_propagate_without_retry(kernel, monkeypatch, error): + state, calls, closed_handles = kernel + state.handle = wintypes.HANDLE(-1).value + monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) + attempted = [] + closed_fds = [] + + def create(path, flags, mode): + attempted.append(path) + raise error("creation failed") + + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{ + **vars(os), "O_BINARY": 0x8000, "open": create, "close": closed_fds.append, + })) + with pytest.raises(error, match="creation failed"): + with _file_handles._windows_overwrite_fd(Path("new")): + pytest.fail("A failed creation yielded a descriptor") + assert attempted == [Path("new")] + assert len(calls) == 1 + assert closed_handles == closed_fds == [] + + +def test_interleaved_windows_overwrites_do_not_change_process_mask(kernel, monkeypatch): + _, calls, _ = kernel + started = threading.Barrier(2) + first_changed = threading.Event() + second_changed = threading.Event() + first_restored = threading.Event() + local = threading.local() + lock = threading.Lock() + current_mask = 0 + mask_calls = [] + closed = [] + + def umask(value): + nonlocal current_mask + initial = local.mask_calls == 0 + local.mask_calls += 1 + if initial and local.role == "second": + assert first_changed.wait(5) + with lock: + previous, current_mask = current_mask, value + mask_calls.append((local.role, value)) + if initial and local.role == "first": + first_changed.set() + assert second_changed.wait(5) + elif initial: + second_changed.set() + assert first_restored.wait(5) + elif local.role == "first": + first_restored.set() + return previous + + monkeypatch.setitem( + sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=lambda handle, flags: 42) + ) + monkeypatch.setattr( + _file_handles, "os", + SimpleNamespace(O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, close=closed.append, umask=umask), + ) + + def overwrite(role): + local.role = role + local.mask_calls = 0 + started.wait(5) + with _file_handles._windows_overwrite_fd(Path(role)) as fd: + assert fd == 42 + + with ThreadPoolExecutor(max_workers=2) as pool: + futures = [pool.submit(overwrite, role) for role in ("first", "second")] + for future in futures: + future.result(timeout=10) + assert current_mask == 0 + assert mask_calls == [] + assert all(not call[5] & 0x1 for call in calls) + assert closed == [42, 42] diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 0a45c70e42..4350db3cfd 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -1,6 +1,7 @@ """Handle-based non-atomic text overwrite behavior.""" import os +import subprocess import sys from contextlib import contextmanager from pathlib import Path @@ -8,7 +9,7 @@ import pytest -from specify_cli import file_helper +from specify_cli import _file_handles, file_helper from specify_cli.file_helper import FileHelper, UnsupportedPathError @@ -448,6 +449,52 @@ def swap(path): assert (root / "original").read_text() == "old" +@pytest.mark.skipif(os.name != "nt", reason="Native Windows CRT exclusive-create semantics required") +@pytest.mark.parametrize("kind", ["file", "existing-target-link", "missing-target-link"]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_leaf_introduced_before_crt_creation_is_not_followed( + tmp_path, monkeypatch, kind, allow +): + root = tmp_path / "project" + root.mkdir() + leaf = root / "file" + outside = tmp_path / "outside" + if kind != "missing-target-link": + outside.write_text("outside") + if kind != "file": + try: + probe = root / "probe" + probe.symlink_to(outside) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + original = os.open + attempted = [] + + def insert(path, flags, mode): + assert Path(path) == leaf + assert flags & os.O_EXCL and not flags & os.O_TRUNC + attempted.append(path) + if kind == "file": + leaf.write_text("introduced") + else: + leaf.symlink_to(outside) + return original(path, flags, mode) + + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{**vars(os), "open": insert})) + with pytest.raises(OSError): + FileHelper(root, allow_symlinks=allow).overwrite_text("file", "new") + assert attempted == [leaf] + if kind == "missing-target-link": + assert not outside.exists() + else: + assert outside.read_text() == "outside" + if kind == "file": + assert leaf.read_text() == "introduced" + else: + assert leaf.is_symlink() + + @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative open required") @pytest.mark.parametrize("allow", [False, True]) @pytest.mark.parametrize("existing", [False, True]) @@ -512,3 +559,39 @@ def swap(fd, length): assert leaf.is_symlink() assert (root / "original").read_text() == "new" assert (root / "original").stat().st_ino == inode + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor limits required") +@pytest.mark.parametrize("depth", [1, 80]) +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_overwrite_descriptor_usage_is_independent_of_path_depth(tmp_path, depth, existing, allow): + parent = tmp_path + for _ in range(depth): + parent = parent / "d" + parent.mkdir() + if existing: + (parent / "file").write_text("longer old content") + result = subprocess.run( + [ + sys.executable, "-c", + """ +import resource +import sys +from pathlib import Path +from specify_cli.file_helper import FileHelper + +root = Path(sys.argv[1]) +parent = root.joinpath(*(["d"] * int(sys.argv[2]))) +files = FileHelper(root, allow_symlinks=sys.argv[3] == "True") +_, hard = resource.getrlimit(resource.RLIMIT_NOFILE) +resource.setrlimit(resource.RLIMIT_NOFILE, (64, hard)) +(parent / "native").write_text("native") +files.overwrite_text(parent / "file", "new") +assert (parent / "file").read_text() == "new" +""", + str(tmp_path), str(depth), str(allow), + ], + capture_output=True, text=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr From e6e59f42583501ceff765ac9c0ee21b707687015 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:19:43 -0600 Subject: [PATCH 06/13] Keep native no-follow creation while honoring CRT permissions Capture masked Windows creation attributes with an empty private probe in the pinned parent, then exclusively create the destination through a no-follow native handle. Clean up the probe, preserve existing in-place updates, and cover leaf collisions during attribute capture. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 8 ++- src/specify_cli/_file_handles.py | 47 ++++++++++----- tests/test_file_handles.py | 94 ++++++++++++++++++++--------- tests/test_file_helper_overwrite.py | 9 +-- 4 files changed, 109 insertions(+), 49 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 8c434d0b60..49b5a063ed 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -187,9 +187,11 @@ helpers for independent project/source/managed boundaries. stays bounded independently of path depth. It then opens the leaf without truncation. Windows retains every resolved directory's non-reparse handle, withholding delete sharing, and opens an existing non-reparse leaf without - truncation. For a missing leaf, it uses exclusive CRT creation so the CRT - applies the process mask without querying or changing it in the helper. A - leaf introduced between these calls causes an explicit creation error. + truncation. For a missing leaf, an empty, randomly named CRT-created probe + in the pinned parent captures the masked creation attributes without + changing the process mask. The probe is removed before native no-follow + exclusive creation of the destination. A leaf introduced between these + calls causes an explicit creation error. The opened leaf remains held through text I/O. Both paths check the opened file type before truncating that same descriptor. An exchanged parent cannot redirect creation or truncation through a new link. Allowed links are still diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index b72eb453ec..5f8dd02256 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -2,6 +2,8 @@ import errno import os +import secrets +import stat from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path @@ -31,7 +33,9 @@ def _windows_api(): return kernel -def _open_windows_handle(path: Path, *, directory: bool, overwrite: bool = False) -> int: +def _open_windows_handle( + path: Path, *, directory: bool, overwrite: bool = False, create_attributes: int | None = None +) -> int: import ctypes from ctypes import wintypes @@ -46,8 +50,8 @@ class AttributeTagInfo(ctypes.Structure): (0x40000000 | 0x80) if overwrite else ((0x80 | 0x1) if directory else 0x80000000), 0x3, None, - 3, # OPEN_EXISTING never creates or truncates a file. - 0x00200000 | 0x02000000, + 3 if create_attributes is None else 1, # OPEN_EXISTING or CREATE_NEW. + 0x00200000 | 0x02000000 | (create_attributes or 0), None, ) if handle == wintypes.HANDLE(-1).value: @@ -80,22 +84,37 @@ def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: @contextmanager def _windows_overwrite_fd(path: Path) -> Iterator[int]: - """Open an existing target, or exclusively create it through the CRT.""" + """Open/create without following a new leaf or changing the CRT mask.""" try: handle = _open_windows_handle(path, directory=False, overwrite=True) except FileNotFoundError: - # Exclusive CRT creation applies the process mask without following - # a leaf introduced after the existing-file open. - fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o666) - else: - try: - import msvcrt + attributes = _windows_creation_attributes(path.parent) + handle = _open_windows_handle( + path, directory=False, overwrite=True, create_attributes=attributes + ) + try: + import msvcrt - fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) - except BaseException: - _windows_api().CloseHandle(handle) - raise + fd = msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) + except BaseException: + _windows_api().CloseHandle(handle) + raise try: yield fd finally: os.close(fd) + + +def _windows_creation_attributes(parent: Path) -> int: + """Capture CRT-masked permissions using a private, empty creation probe.""" + probe = parent / f".specify-mode-{secrets.token_hex(16)}.tmp" + fd = os.open(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o666) + try: + readonly = not os.fstat(fd).st_mode & stat.S_IWRITE + finally: + try: + os.chmod(probe, 0o600) + finally: + os.close(fd) + os.unlink(probe) + return 0x1 if readonly else 0 diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 962e63cd7c..889f1efd51 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -18,14 +18,14 @@ def kernel(monkeypatch): calls = [] closed = [] - state = SimpleNamespace(attributes=0, query_ok=True, handle=123) + state = SimpleNamespace(attributes=0, query_ok=True, handle=123, handles=None) def umask(value): raise AssertionError("Handle operations must not change the process mask") def create(*args): calls.append(args) - return state.handle + return state.handles.pop(0) if state.handles is not None else state.handle def query(handle, info_class, output, size): assert handle == 123 and info_class == 9 @@ -133,31 +133,70 @@ def run(): @pytest.mark.parametrize("mask", [0, 0o200, 0o400, 0o600]) @pytest.mark.parametrize("body_failure", [False, True]) -def test_missing_windows_leaf_uses_exclusive_crt_creation( - kernel, monkeypatch, mask, body_failure -): - state, calls, closed_handles = kernel - state.handle = wintypes.HANDLE(-1).value - monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) +def test_windows_creation_probe_uses_crt_mask_without_changing_it(monkeypatch, mask, body_failure): created = [] closed_fds = [] + chmods = [] + removed = [] def create(path, flags, mode): - created.append((path, flags, mode, mode & ~mask)) + created.append((path, flags, mode)) return 42 def umask(value): raise AssertionError("Creation must let the CRT apply the mask") + def inspect(fd): + assert fd == 42 + if body_failure: + raise OSError("query failed") + return SimpleNamespace(st_mode=0o666 & ~mask) + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{ **vars(os), "O_BINARY": 0x8000, "open": create, - "close": closed_fds.append, "umask": umask, + "close": closed_fds.append, "umask": umask, "fstat": inspect, + "chmod": lambda path, mode: chmods.append((path, mode)), "unlink": removed.append, })) + monkeypatch.setattr(_file_handles.secrets, "token_hex", lambda size: "a" * (size * 2)) + probe = Path("parent") / f".specify-mode-{'a' * 32}.tmp" + if body_failure: + with pytest.raises(OSError, match="query failed"): + _file_handles._windows_creation_attributes(Path("parent")) + else: + assert _file_handles._windows_creation_attributes(Path("parent")) == ( + 0x1 if mask & 0o200 else 0 + ) + assert created == [(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL | 0x8000, 0o666)] + assert chmods == [(probe, 0o600)] + assert removed == [probe] + assert closed_fds == [42] + + +@pytest.mark.parametrize("attributes", [0, 0x1]) +@pytest.mark.parametrize("body_failure", [False, True]) +def test_missing_windows_leaf_uses_native_no_follow_creation( + kernel, monkeypatch, attributes, body_failure +): + state, calls, closed_handles = kernel + state.handles = [wintypes.HANDLE(-1).value, 123] + monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) + closed_fds = [] + parents = [] + + def probe(parent): + parents.append(parent) + return attributes + + monkeypatch.setattr(_file_handles, "_windows_creation_attributes", probe) + monkeypatch.setattr(_file_handles.os, "O_BINARY", 0x8000, raising=False) + monkeypatch.setattr(_file_handles.os, "close", closed_fds.append) + monkeypatch.setitem( + sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=lambda handle, flags: 42) + ) def write(): - with _file_handles._windows_overwrite_fd(Path("new")) as fd: + with _file_handles._windows_overwrite_fd(Path("parent/new")) as fd: assert fd == 42 - assert closed_fds == [] if body_failure: raise OSError("write failed") @@ -166,35 +205,34 @@ def write(): write() else: write() - assert created == [ - (Path("new"), os.O_WRONLY | os.O_CREAT | os.O_EXCL | 0x8000, 0o666, 0o666 & ~mask) - ] + assert parents == [Path("parent")] assert calls[0][4] == 3 + assert calls[1][4:6] == (1, 0x02200000 | attributes) assert closed_handles == [] assert closed_fds == [42] @pytest.mark.parametrize("error", [FileExistsError, PermissionError, FileNotFoundError]) -def test_windows_crt_creation_errors_propagate_without_retry(kernel, monkeypatch, error): - state, calls, closed_handles = kernel - state.handle = wintypes.HANDLE(-1).value - monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) +def test_windows_native_creation_errors_propagate_without_retry(kernel, monkeypatch, error): + _, _, closed_handles = kernel attempted = [] - closed_fds = [] - def create(path, flags, mode): - attempted.append(path) + def open_handle(path, **kwargs): + attempted.append(kwargs) + if len(attempted) == 1: + raise FileNotFoundError("missing") raise error("creation failed") - monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{ - **vars(os), "O_BINARY": 0x8000, "open": create, "close": closed_fds.append, - })) + monkeypatch.setattr(_file_handles, "_open_windows_handle", open_handle) + monkeypatch.setattr(_file_handles, "_windows_creation_attributes", lambda parent: 0) with pytest.raises(error, match="creation failed"): with _file_handles._windows_overwrite_fd(Path("new")): pytest.fail("A failed creation yielded a descriptor") - assert attempted == [Path("new")] - assert len(calls) == 1 - assert closed_handles == closed_fds == [] + assert attempted == [ + {"directory": False, "overwrite": True}, + {"directory": False, "overwrite": True, "create_attributes": 0}, + ] + assert closed_handles == [] def test_interleaved_windows_overwrites_do_not_change_process_mask(kernel, monkeypatch): diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 4350db3cfd..0649dc4f68 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -213,6 +213,7 @@ def test_native_windows_overwrite_creation_matches_masked_native_creation(tmp_pa path.write_text("again") else: path.write_text("again") + assert {path.name for path in tmp_path.iterdir()} == {"native", "file", "existing"} finally: os.umask(previous_mask) for path in (native, leaf): @@ -452,7 +453,7 @@ def swap(path): @pytest.mark.skipif(os.name != "nt", reason="Native Windows CRT exclusive-create semantics required") @pytest.mark.parametrize("kind", ["file", "existing-target-link", "missing-target-link"]) @pytest.mark.parametrize("allow", [False, True]) -def test_native_windows_leaf_introduced_before_crt_creation_is_not_followed( +def test_native_windows_leaf_introduced_during_mode_probe_is_not_followed( tmp_path, monkeypatch, kind, allow ): root = tmp_path / "project" @@ -472,14 +473,14 @@ def test_native_windows_leaf_introduced_before_crt_creation_is_not_followed( attempted = [] def insert(path, flags, mode): - assert Path(path) == leaf assert flags & os.O_EXCL and not flags & os.O_TRUNC - attempted.append(path) + fd = original(path, flags, mode) + attempted.append(leaf) if kind == "file": leaf.write_text("introduced") else: leaf.symlink_to(outside) - return original(path, flags, mode) + return fd monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{**vars(os), "open": insert})) with pytest.raises(OSError): From b1df37bf69099244c6cfcaf09acc21d734615f24 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 07:54:25 -0600 Subject: [PATCH 07/13] Avoid project delete-right requirements for Windows overwrites Discover CRT-masked creation attributes in independent runtime-owned temporary storage instead of a disposable project sibling. Preserve native no-follow destination creation and cover create/write-without-delete directory ACLs. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 11 ++-- src/specify_cli/_file_handles.py | 30 ++++++---- tests/test_file_handles.py | 93 ++++++++++++++++++++++++++--- tests/test_file_helper_overwrite.py | 41 +++++++++++++ 4 files changed, 149 insertions(+), 26 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 49b5a063ed..0a68a70bdf 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -188,10 +188,13 @@ helpers for independent project/source/managed boundaries. truncation. Windows retains every resolved directory's non-reparse handle, withholding delete sharing, and opens an existing non-reparse leaf without truncation. For a missing leaf, an empty, randomly named CRT-created probe - in the pinned parent captures the masked creation attributes without - changing the process mask. The probe is removed before native no-follow - exclusive creation of the destination. A leaf introduced between these - calls causes an explicit creation error. + in an independently owned runtime temporary directory captures the masked + creation attributes without changing the process mask. This scratch root is + pinned separately, contains no project data, and is removed before native + no-follow exclusive creation of the destination. No disposable sibling is + created in the project, so destination creation does not require project + deletion rights. Runtime temporary-storage failures remain explicit errors. + A leaf introduced between these calls causes an explicit creation error. The opened leaf remains held through text I/O. Both paths check the opened file type before truncating that same descriptor. An exchanged parent cannot redirect creation or truncation through a new link. Allowed links are still diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 5f8dd02256..06e0f86645 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -4,6 +4,7 @@ import os import secrets import stat +import tempfile from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path @@ -88,7 +89,7 @@ def _windows_overwrite_fd(path: Path) -> Iterator[int]: try: handle = _open_windows_handle(path, directory=False, overwrite=True) except FileNotFoundError: - attributes = _windows_creation_attributes(path.parent) + attributes = _windows_creation_attributes() handle = _open_windows_handle( path, directory=False, overwrite=True, create_attributes=attributes ) @@ -105,16 +106,19 @@ def _windows_overwrite_fd(path: Path) -> Iterator[int]: os.close(fd) -def _windows_creation_attributes(parent: Path) -> int: - """Capture CRT-masked permissions using a private, empty creation probe.""" - probe = parent / f".specify-mode-{secrets.token_hex(16)}.tmp" - fd = os.open(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o666) - try: - readonly = not os.fstat(fd).st_mode & stat.S_IWRITE - finally: - try: - os.chmod(probe, 0o600) - finally: - os.close(fd) - os.unlink(probe) +def _windows_creation_attributes() -> int: + """Capture CRT-masked permissions in independent runtime-owned storage.""" + with tempfile.TemporaryDirectory(prefix="specify-mode-") as directory: + parent = Path(directory) + with _windows_handle(parent, directory=True): + probe = parent / f".specify-mode-{secrets.token_hex(16)}.tmp" + fd = os.open(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_BINARY, 0o666) + try: + readonly = not os.fstat(fd).st_mode & stat.S_IWRITE + finally: + try: + os.chmod(probe, 0o600) + finally: + os.close(fd) + os.unlink(probe) return 0x1 if readonly else 0 diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 889f1efd51..f683f1104a 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -5,6 +5,7 @@ import sys import threading from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager from ctypes import wintypes from pathlib import Path from types import SimpleNamespace @@ -14,6 +15,37 @@ from specify_cli import _file_handles +@pytest.fixture +def runtime_probe(monkeypatch): + root = Path("runtime") + events = [] + + @contextmanager + def temporary_directory(*, prefix): + assert prefix == "specify-mode-" + events.append("temporary") + try: + yield str(root) + finally: + events.append("cleanup") + + @contextmanager + def pin(path, *, directory): + assert path == root and directory + events.append("pin") + try: + yield 1 + finally: + events.append("unpin") + + monkeypatch.setattr( + _file_handles, "tempfile", + SimpleNamespace(TemporaryDirectory=temporary_directory), raising=False, + ) + monkeypatch.setattr(_file_handles, "_windows_handle", pin) + return root, events + + @pytest.fixture def kernel(monkeypatch): calls = [] @@ -133,7 +165,10 @@ def run(): @pytest.mark.parametrize("mask", [0, 0o200, 0o400, 0o600]) @pytest.mark.parametrize("body_failure", [False, True]) -def test_windows_creation_probe_uses_crt_mask_without_changing_it(monkeypatch, mask, body_failure): +def test_windows_creation_probe_uses_crt_mask_without_changing_it( + monkeypatch, runtime_probe, mask, body_failure +): + runtime, events = runtime_probe created = [] closed_fds = [] chmods = [] @@ -158,18 +193,19 @@ def inspect(fd): "chmod": lambda path, mode: chmods.append((path, mode)), "unlink": removed.append, })) monkeypatch.setattr(_file_handles.secrets, "token_hex", lambda size: "a" * (size * 2)) - probe = Path("parent") / f".specify-mode-{'a' * 32}.tmp" + probe = runtime / f".specify-mode-{'a' * 32}.tmp" if body_failure: with pytest.raises(OSError, match="query failed"): - _file_handles._windows_creation_attributes(Path("parent")) + _file_handles._windows_creation_attributes() else: - assert _file_handles._windows_creation_attributes(Path("parent")) == ( + assert _file_handles._windows_creation_attributes() == ( 0x1 if mask & 0o200 else 0 ) assert created == [(probe, os.O_WRONLY | os.O_CREAT | os.O_EXCL | 0x8000, 0o666)] assert chmods == [(probe, 0o600)] assert removed == [probe] assert closed_fds == [42] + assert events == ["temporary", "pin", "unpin", "cleanup"] @pytest.mark.parametrize("attributes", [0, 0x1]) @@ -181,10 +217,10 @@ def test_missing_windows_leaf_uses_native_no_follow_creation( state.handles = [wintypes.HANDLE(-1).value, 123] monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) closed_fds = [] - parents = [] + probes = [] - def probe(parent): - parents.append(parent) + def probe(): + probes.append(True) return attributes monkeypatch.setattr(_file_handles, "_windows_creation_attributes", probe) @@ -205,7 +241,7 @@ def write(): write() else: write() - assert parents == [Path("parent")] + assert probes == [True] assert calls[0][4] == 3 assert calls[1][4:6] == (1, 0x02200000 | attributes) assert closed_handles == [] @@ -224,7 +260,7 @@ def open_handle(path, **kwargs): raise error("creation failed") monkeypatch.setattr(_file_handles, "_open_windows_handle", open_handle) - monkeypatch.setattr(_file_handles, "_windows_creation_attributes", lambda parent: 0) + monkeypatch.setattr(_file_handles, "_windows_creation_attributes", lambda: 0) with pytest.raises(error, match="creation failed"): with _file_handles._windows_overwrite_fd(Path("new")): pytest.fail("A failed creation yielded a descriptor") @@ -289,3 +325,42 @@ def overwrite(role): assert mask_calls == [] assert all(not call[5] & 0x1 for call in calls) assert closed == [42, 42] + + +def test_missing_windows_leaf_does_not_require_project_delete_rights( + kernel, runtime_probe, monkeypatch +): + state, calls, closed_handles = kernel + state.handles = [wintypes.HANDLE(-1).value, 123] + monkeypatch.setattr(ctypes, "get_last_error", lambda: 2) + runtime, events = runtime_probe + created = [] + deleted = [] + closed = [] + + def create(path, flags, mode): + created.append(Path(path)) + return 100 + + def unlink(path): + path = Path(path) + if path.parent == Path("project"): + raise PermissionError("Project grants creation but not deletion") + deleted.append(path) + + monkeypatch.setattr(_file_handles, "os", SimpleNamespace(**{ + **vars(os), "O_BINARY": 0x8000, "open": create, + "fstat": lambda fd: SimpleNamespace(st_mode=0o666), + "chmod": lambda path, mode: None, "unlink": unlink, "close": closed.append, + })) + monkeypatch.setitem( + sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=lambda handle, flags: 42) + ) + with _file_handles._windows_overwrite_fd(Path("project/new")) as fd: + assert fd == 42 + assert len(created) == 1 and created[0].parent == runtime + assert deleted == created + assert events == ["temporary", "pin", "unpin", "cleanup"] + assert closed == [100, 42] + assert closed_handles == [] + assert calls[1][4] == 1 diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 0649dc4f68..488d5e6f32 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -1,5 +1,6 @@ """Handle-based non-atomic text overwrite behavior.""" +import csv import os import subprocess import sys @@ -221,6 +222,46 @@ def test_native_windows_overwrite_creation_matches_masked_native_creation(tmp_pa path.chmod(0o600) +@pytest.mark.skipif(os.name != "nt", reason="Native Windows directory ACL semantics required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_overwrite_does_not_require_project_delete_rights( + tmp_path, existing, allow +): + root = tmp_path / "project" + root.mkdir() + leaf = root / "file" + if existing: + leaf.write_text("longer old content") + identity = subprocess.run( + ["whoami", "/user", "/fo", "csv", "/nh"], + capture_output=True, text=True, check=True, + ) + rows = [row for row in csv.reader(identity.stdout.splitlines()) if row] + sid = rows[0][1].strip() + assert sid.startswith("S-") + + def icacls(*args): + result = subprocess.run( + ["icacls", str(root), *args], capture_output=True, text=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + try: + icacls("/deny", f"*{sid}:(OI)(CI)(D,DC)") + native = root / "native" + native.write_text("native") + with pytest.raises(PermissionError): + native.unlink() + FileHelper(root, allow_symlinks=allow).overwrite_text("file", "new") + assert leaf.read_text() == "new" + with pytest.raises(PermissionError): + leaf.unlink() + assert {path.name for path in root.iterdir()} == {"native", "file"} + finally: + icacls("/remove:d", f"*{sid}", "/T", "/C") + + @pytest.mark.parametrize("allow", [False, True]) def test_overwrite_trusted_root_alias_and_contained_link_chains(tmp_path, allow): root = tmp_path / "project" From 580018b969125386090443a2d57600015282b0c4 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:08:10 -0600 Subject: [PATCH 08/13] Isolate overwrite ACL coverage from trusted-root setup Apply create/write-without-delete permissions to the child destination directory, keeping root canonicalization separate from the overwrite permission regression. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper_overwrite.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 488d5e6f32..c4f5d66926 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -229,8 +229,9 @@ def test_native_windows_overwrite_does_not_require_project_delete_rights( tmp_path, existing, allow ): root = tmp_path / "project" - root.mkdir() - leaf = root / "file" + parent = root / "parent" + parent.mkdir(parents=True) + leaf = parent / "file" if existing: leaf.write_text("longer old content") identity = subprocess.run( @@ -243,21 +244,21 @@ def test_native_windows_overwrite_does_not_require_project_delete_rights( def icacls(*args): result = subprocess.run( - ["icacls", str(root), *args], capture_output=True, text=True, check=False, + ["icacls", str(parent), *args], capture_output=True, text=True, check=False, ) assert result.returncode == 0, result.stdout + result.stderr try: icacls("/deny", f"*{sid}:(OI)(CI)(D,DC)") - native = root / "native" + native = parent / "native" native.write_text("native") with pytest.raises(PermissionError): native.unlink() - FileHelper(root, allow_symlinks=allow).overwrite_text("file", "new") + FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new") assert leaf.read_text() == "new" with pytest.raises(PermissionError): leaf.unlink() - assert {path.name for path in root.iterdir()} == {"native", "file"} + assert {path.name for path in parent.iterdir()} == {"native", "file"} finally: icacls("/remove:d", f"*{sid}", "/T", "/C") From d1dbf885f07e06d7dfc0178004078fc7d49b59fd Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:22:10 -0600 Subject: [PATCH 09/13] Use exact delete permissions in the Windows ACL regression Deny the advanced DE and DC rights explicitly and confirm ordinary file reading remains available before exercising overwrite behavior. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper_overwrite.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index c4f5d66926..10e8914647 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -249,9 +249,10 @@ def icacls(*args): assert result.returncode == 0, result.stdout + result.stderr try: - icacls("/deny", f"*{sid}:(OI)(CI)(D,DC)") + icacls("/deny", f"*{sid}:(OI)(CI)(DE,DC)") native = parent / "native" native.write_text("native") + assert native.read_text() == "native" with pytest.raises(PermissionError): native.unlink() FileHelper(root, allow_symlinks=allow).overwrite_text("parent/file", "new") From 1737ae9f280ffdd7c658b04a100f2dfc0be10ee3 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:26:03 -0600 Subject: [PATCH 10/13] Document Windows overwrite directory access requirements State that the canonical root and every resolved parent require directory-list and read-attributes access, including the resulting failure when an ACL allows file writes but denies listing. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index c91c219f6a..cd72104472 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -201,11 +201,14 @@ helpers for independent project/source/managed boundaries. access where supported so unreadable but searchable parents remain usable, and closes the previous directory after opening its child. Descriptor usage stays bounded independently of path depth. It then opens the leaf without - truncation. Windows retains every resolved directory's non-reparse handle, - withholding delete sharing, and opens an existing non-reparse leaf without - truncation. For a missing leaf, an empty, randomly named CRT-created probe - in an independently owned runtime temporary directory captures the masked - creation attributes without changing the process mask. This scratch root is + truncation. Windows pins the canonical root and every resolved parent with + non-reparse handles withholding delete sharing. Each anchored directory must + permit `FILE_LIST_DIRECTORY` and `FILE_READ_ATTRIBUTES` access. An ACL that + permits file writing but denies directory listing can therefore cause an + overwrite to fail before opening the leaf. Existing non-reparse leaves are + opened without truncation. For a missing leaf, an empty, randomly named + CRT-created probe in an independently owned runtime temporary directory + captures the masked creation attributes without changing the process mask. This scratch root is pinned separately, contains no project data, and is removed before native no-follow exclusive creation of the destination. No disposable sibling is created in the project, so destination creation does not require project From 750a995e0ae7c2cc5f2cc9e7269a2708c8f12434 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:02:13 -0600 Subject: [PATCH 11/13] Cover FIFO overwrites without a reader Exercise leaf replacement with a no-reader FIFO in timeout-bounded subprocesses for both link policies. Require the nonblocking ENXIO failure and preserve the original file contents while retaining reader-present file-type coverage. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper_overwrite.py | 47 +++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 10e8914647..aaf35756ab 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -96,6 +96,53 @@ def swap(path, flags, *args, **kwargs): assert (root / "original").read_text() == "original" +@pytest.mark.skipif(os.name == "nt", reason="POSIX FIFO open semantics required") +@pytest.mark.parametrize("allow", [False, True]) +def test_fifo_without_reader_at_leaf_open_does_not_block(tmp_path, allow): + result = subprocess.run( + [ + sys.executable, "-c", + """ +import errno +import os +import stat +import sys +from pathlib import Path +from specify_cli.file_helper import FileHelper + +root = Path(sys.argv[1]) +leaf = root / "file" +leaf.write_text("original") +files = FileHelper(root, allow_symlinks=sys.argv[2] == "True") +original = os.open +swapped = False + +def swap(path, flags, *args, **kwargs): + global swapped + if Path(path).name == "file": + leaf.rename(root / "original") + os.mkfifo(leaf) + swapped = True + return original(path, flags, *args, **kwargs) + +os.open = swap +try: + files.overwrite_text("file", "new") +except OSError as exc: + assert exc.errno == errno.ENXIO, repr(exc) +else: + raise AssertionError("Overwrite accepted a FIFO without a reader") +assert swapped +assert stat.S_ISFIFO(leaf.lstat().st_mode) +assert (root / "original").read_text() == "original" +""", + str(tmp_path), str(allow), + ], + capture_output=True, text=True, timeout=10, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + @pytest.mark.parametrize("allow", [False, True]) @pytest.mark.parametrize("encoding", ["utf-8", "utf-16", "cp1252"]) def test_overwrite_matches_native_text_and_preserves_hardlinks(tmp_path, allow, encoding): From 9b36b0924269156f2732343c0e32b5c75b408ab6 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:35:02 -0600 Subject: [PATCH 12/13] Cover overwrite capability and creation edge cases Exercise missing and zero-valued primitives, regular files introduced before POSIX open, and Windows existing-file probe avoidance. Check explicit failures and preserve inode, hard-link, and permission behavior. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_handles.py | 4 ++ tests/test_file_helper_overwrite.py | 102 +++++++++++++++++++++++++++- 2 files changed, 103 insertions(+), 3 deletions(-) diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 910255bacc..7167a171ee 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -138,6 +138,10 @@ def convert(handle, flags): raise OSError("conversion failed") return 42 + def unexpected_probe(): + raise AssertionError("Existing-file overwrites must not probe creation attributes") + + monkeypatch.setattr(_file_handles, "_windows_creation_attributes", unexpected_probe) monkeypatch.setitem(sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=convert)) monkeypatch.setattr( _file_handles, "os", diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index aaf35756ab..f433914d7f 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -1,6 +1,7 @@ """Handle-based non-atomic text overwrite behavior.""" import csv +import errno import os import subprocess import sys @@ -354,19 +355,114 @@ def test_missing_parent_and_invalid_codec_do_not_create_or_truncate(tmp_path, al @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor capability required") @pytest.mark.parametrize("existing", [False, True]) -def test_unsupported_descriptor_backend_fails_without_path_fallback(tmp_path, monkeypatch, existing): +@pytest.mark.parametrize( + ("capability", "value"), + [ + ("dir_fd", False), + ("O_NOFOLLOW", 0), ("O_NOFOLLOW", None), + ("O_DIRECTORY", 0), ("O_DIRECTORY", None), + ("O_NONBLOCK", 0), ("O_NONBLOCK", None), + ], +) +def test_unsupported_descriptor_backend_fails_without_path_fallback( + tmp_path, monkeypatch, existing, capability, value +): path = tmp_path / "file" if existing: path.write_text("old") - monkeypatch.setattr(file_helper, "_OVERWRITE_DIR_FD_SUPPORTED", False) - with pytest.raises(OSError, match="unsupported"): + + def unexpected_open(*args, **kwargs): + raise AssertionError("An unsupported backend must not open a destination") + + attributes = {**vars(os), "open": unexpected_open} + if capability == "dir_fd": + monkeypatch.setattr(file_helper, "_OVERWRITE_DIR_FD_SUPPORTED", False) + elif value is None: + attributes.pop(capability, None) + else: + attributes[capability] = value + monkeypatch.setattr(file_helper, "os", SimpleNamespace(**attributes)) + with pytest.raises(OSError, match="unsupported") as caught: FileHelper(tmp_path).overwrite_text("file", "new") + assert caught.value.errno == errno.ENOTSUP if existing: assert path.read_text() == "old" else: assert not path.exists() +@pytest.mark.skipif(os.name == "nt", reason="POSIX upsert open semantics required") +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("writable", [False, True]) +def test_regular_file_created_at_leaf_open_retains_native_upsert_behavior( + tmp_path, monkeypatch, allow, writable +): + if not writable and os.geteuid() == 0: + pytest.skip("Root bypasses file write permissions") + leaf = tmp_path / "file" + alias = tmp_path / "hardlink" + original = os.open + created = [] + mode = 0o600 if writable else 0o400 + + def create_before_open(path, flags, *args, **kwargs): + if Path(path).name == "file": + assert not leaf.exists() + assert flags & os.O_CREAT and not flags & os.O_TRUNC + leaf.write_text("created immediately before open") + leaf.chmod(mode) + os.link(leaf, alias) + created.append(leaf.stat().st_ino) + return original(path, flags, *args, **kwargs) + + monkeypatch.setattr( + file_helper, "os", SimpleNamespace(**{**vars(os), "open": create_before_open}) + ) + files = FileHelper(tmp_path, allow_symlinks=allow) + if writable: + files.overwrite_text("file", "new") + else: + with pytest.raises(PermissionError): + files.overwrite_text("file", "new") + assert len(created) == 1 + assert leaf.stat().st_ino == alias.stat().st_ino == created[0] + assert leaf.stat().st_mode & 0o777 == mode + expected = "new" if writable else "created immediately before open" + assert leaf.read_text() == alias.read_text() == expected + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows overwrite backend required") +@pytest.mark.parametrize("existing", [False, True]) +@pytest.mark.parametrize("allow", [False, True]) +def test_native_windows_creation_probe_is_only_required_for_missing_leaf( + tmp_path, monkeypatch, existing, allow +): + leaf = tmp_path / "file" + if existing: + leaf.write_text("longer old content") + before = leaf.stat() + probes = [] + + def unavailable_probe(): + probes.append(True) + raise PermissionError("Runtime permissions probe unavailable") + + monkeypatch.setattr(_file_handles, "_windows_creation_attributes", unavailable_probe) + files = FileHelper(tmp_path, allow_symlinks=allow) + if existing: + files.overwrite_text("file", "new") + assert leaf.read_text() == "new" + assert leaf.stat().st_ino == before.st_ino + assert leaf.stat().st_mode == before.st_mode + assert probes == [] + else: + with pytest.raises(PermissionError, match="Runtime permissions probe unavailable"): + files.overwrite_text("file", "new") + assert not leaf.exists() + assert probes == [True] + assert {path.name for path in tmp_path.iterdir()} == ({"file"} if existing else set()) + + @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor cleanup required") @pytest.mark.parametrize("failure", ["open", "fstat", "ftruncate", "fdopen", "write"]) def test_overwrite_closes_descriptors_on_failure(tmp_path, monkeypatch, failure): From 032dad0da37e67efab9b0c0207fd21dbc90dcf91 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:43:40 -0600 Subject: [PATCH 13/13] Simplify Windows overwrite concurrency coverage Reuse the direct process-mask assertion while retaining concurrent calls and descriptor cleanup checks. Remove simulated mask state, synchronization events, and timed interleaving waits. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_handles.py | 57 ++++++++------------------------------ 1 file changed, 11 insertions(+), 46 deletions(-) diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py index 7167a171ee..e582364cdd 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -3,7 +3,6 @@ import ctypes import os import sys -import threading from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from ctypes import wintypes @@ -276,59 +275,25 @@ def open_handle(path, **kwargs): assert closed_handles == [] -def test_interleaved_windows_overwrites_do_not_change_process_mask(kernel, monkeypatch): - _, calls, _ = kernel - started = threading.Barrier(2) - first_changed = threading.Event() - second_changed = threading.Event() - first_restored = threading.Event() - local = threading.local() - lock = threading.Lock() - current_mask = 0 - mask_calls = [] +def test_concurrent_windows_overwrites_do_not_query_process_mask(kernel, monkeypatch): + _, calls, closed_handles = kernel closed = [] - - def umask(value): - nonlocal current_mask - initial = local.mask_calls == 0 - local.mask_calls += 1 - if initial and local.role == "second": - assert first_changed.wait(5) - with lock: - previous, current_mask = current_mask, value - mask_calls.append((local.role, value)) - if initial and local.role == "first": - first_changed.set() - assert second_changed.wait(5) - elif initial: - second_changed.set() - assert first_restored.wait(5) - elif local.role == "first": - first_restored.set() - return previous - monkeypatch.setitem( sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=lambda handle, flags: 42) ) - monkeypatch.setattr( - _file_handles, "os", - SimpleNamespace(O_WRONLY=os.O_WRONLY, O_BINARY=0x8000, close=closed.append, umask=umask), - ) + monkeypatch.setattr(_file_handles.os, "O_BINARY", 0x8000, raising=False) + monkeypatch.setattr(_file_handles.os, "close", closed.append) - def overwrite(role): - local.role = role - local.mask_calls = 0 - started.wait(5) - with _file_handles._windows_overwrite_fd(Path(role)) as fd: + def overwrite(name): + with _file_handles._windows_overwrite_fd(Path(name)) as fd: assert fd == 42 with ThreadPoolExecutor(max_workers=2) as pool: - futures = [pool.submit(overwrite, role) for role in ("first", "second")] - for future in futures: - future.result(timeout=10) - assert current_mask == 0 - assert mask_calls == [] - assert all(not call[5] & 0x1 for call in calls) + list(pool.map(overwrite, ("first", "second"))) + assert {call[0] for call in calls} == {"first", "second"} + assert len(calls) == 2 + assert all(call[4] == 3 and not call[5] & 0x1 for call in calls) + assert closed_handles == [] assert closed == [42, 42]