diff --git a/design/file-helper.md b/design/file-helper.md index 186e563439..cd72104472 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 | @@ -195,6 +196,32 @@ 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, using search/path-only + 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 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 + 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 + 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. @@ -225,12 +252,11 @@ 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. For all operations that still use -validated paths (reads, directory creation, atomic writes, non-atomic -overwrites, symlink creation, and deletion), portable path checks are **not** -a race-free sandbox: another process can exchange parents or entries between -checks and syscalls, and an I/O failure during mutation can leave partial -results. Protect against concurrent untrusted mutation separately. +deletion rechecks each accessed entry. No operation is a general race-free +sandbox. For operations that still use validated paths, another process can +exchange parents or entries between checks and syscalls. An I/O failure during +any mutation can leave partial results. Protect against concurrent untrusted +mutation separately. Exclusive file creation anchors its resolved parent hierarchy as described above. On POSIX, renaming an opened directory does not redirect creation to its replacement: creation stays with the opened directory, even if it is @@ -244,9 +270,14 @@ 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 index 460e25525c..74531851ce 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -1,23 +1,21 @@ """Private platform handles for confined filesystem operations.""" import errno +import os +import secrets +import stat +import tempfile from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path -@contextmanager -def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: - """Pin a non-reparse path by withholding Windows delete sharing.""" +def _windows_api(): 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 = [ + kernel.CreateFileW.argtypes = [ wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, @@ -26,38 +24,101 @@ class AttributeTagInfo(ctypes.Structure): 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( + 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, create_attributes: int | None = None +) -> 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), - (0x80 | 0x1) if directory else 0x80000000, + (0x40000000 | 0x80) if overwrite else ((0x80 | 0x1) if directory else 0x80000000), 0x3, None, - 3, - 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: raise ctypes.WinError(ctypes.get_last_error()) try: attributes = AttributeTagInfo() - if not info(handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes)): + 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 filesystem path", str(path)) if bool(attributes.attributes & 0x10) != directory: raise OSError(errno.EINVAL, "Unexpected filesystem object 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: - close(handle) + _windows_api().CloseHandle(handle) + + +@contextmanager +def _windows_overwrite_fd(path: Path) -> Iterator[int]: + """Open/create without following a new leaf or changing the CRT mask.""" + try: + handle = _open_windows_handle(path, directory=False, overwrite=True) + except FileNotFoundError: + attributes = _windows_creation_attributes() + 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 + try: + yield fd + finally: + os.close(fd) + + +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/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index e1c4a0cf2d..f820668181 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -1,21 +1,21 @@ """Scoped filesystem operations; see design/file-helper.md for the contract.""" -from dataclasses import dataclass, field -from collections.abc import Iterator -from contextlib import ExitStack, contextmanager import codecs import errno import os -from pathlib import Path, PurePath, PureWindowsPath import stat import sys import tempfile +from 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 - +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: @@ -266,11 +266,58 @@ 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_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 = ( + directory_access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + ) + parent = os.open(self._canonical_root, directory_flags) + 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 75fae0ead2..e582364cdd 100644 --- a/tests/test_file_handles.py +++ b/tests/test_file_handles.py @@ -1,14 +1,341 @@ -"""Portable contract checks for the private Windows handle primitive.""" +"""Portable checks of Windows handle flags, validation, and ownership.""" import ctypes +import os +import sys +from concurrent.futures import ThreadPoolExecutor +from contextlib import contextmanager from ctypes import wintypes +from pathlib import Path from types import SimpleNamespace import pytest +from specify_cli import _file_handles from specify_cli._file_handles import _windows_handle +@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 = [] + closed = [] + 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.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 + 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(_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 + + +@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("mask", [0, 0o200, 0o400, 0o600]) +@pytest.mark.parametrize("query_ok", [False, True]) +def test_existing_windows_overwrite_does_not_query_creation_mask(kernel, monkeypatch, mask, query_ok): + state, calls, closed = kernel + state.query_ok = query_ok + def umask(value): + 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: + 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 calls == [("path", 0x40000080, 0x3, None, 3, 0x02200000, None)] + 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 + 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, 3, 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 + + 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", + 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] == 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_windows_creation_probe_uses_crt_mask_without_changing_it( + monkeypatch, runtime_probe, mask, body_failure +): + runtime, events = runtime_probe + created = [] + closed_fds = [] + chmods = [] + removed = [] + + def create(path, flags, mode): + 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, "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 = runtime / f".specify-mode-{'a' * 32}.tmp" + if body_failure: + with pytest.raises(OSError, match="query failed"): + _file_handles._windows_creation_attributes() + else: + 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]) +@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 = [] + probes = [] + + def probe(): + probes.append(True) + 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("parent/new")) as fd: + assert fd == 42 + if body_failure: + raise OSError("write failed") + + if body_failure: + with pytest.raises(OSError, match="write failed"): + write() + else: + write() + assert probes == [True] + 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_native_creation_errors_propagate_without_retry(kernel, monkeypatch, error): + _, _, closed_handles = kernel + attempted = [] + + def open_handle(path, **kwargs): + attempted.append(kwargs) + if len(attempted) == 1: + raise FileNotFoundError("missing") + raise error("creation failed") + + monkeypatch.setattr(_file_handles, "_open_windows_handle", open_handle) + 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") + assert attempted == [ + {"directory": False, "overwrite": True}, + {"directory": False, "overwrite": True, "create_attributes": 0}, + ] + assert closed_handles == [] + + +def test_concurrent_windows_overwrites_do_not_query_process_mask(kernel, monkeypatch): + _, calls, closed_handles = kernel + closed = [] + monkeypatch.setitem( + sys.modules, "msvcrt", SimpleNamespace(open_osfhandle=lambda handle, flags: 42) + ) + monkeypatch.setattr(_file_handles.os, "O_BINARY", 0x8000, raising=False) + monkeypatch.setattr(_file_handles.os, "close", closed.append) + + def overwrite(name): + with _file_handles._windows_overwrite_fd(Path(name)) as fd: + assert fd == 42 + + with ThreadPoolExecutor(max_workers=2) as pool: + 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] + + +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 + + @pytest.mark.parametrize("directory", [False, True]) def test_windows_handle_declares_complete_createfile_prototype(tmp_path, monkeypatch, directory): closed = [] diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 40ecd09efa..8bf31e9ba8 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -152,7 +152,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 new file mode 100644 index 0000000000..f433914d7f --- /dev/null +++ b/tests/test_file_helper_overwrite.py @@ -0,0 +1,784 @@ +"""Handle-based non-atomic text overwrite behavior.""" + +import csv +import errno +import os +import subprocess +import sys +from contextlib import contextmanager +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from specify_cli import _file_handles, 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.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): + 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.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"]) +@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, 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) + 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", encoding="utf-8") + 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") + assert {path.name for path in tmp_path.iterdir()} == {"native", "file", "existing"} + finally: + os.umask(previous_mask) + for path in (native, leaf): + if path.exists(): + 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" + parent = root / "parent" + parent.mkdir(parents=True) + leaf = parent / "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(parent), *args], capture_output=True, text=True, check=False, + ) + assert result.returncode == 0, result.stdout + result.stderr + + try: + 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") + assert leaf.read_text() == "new" + with pytest.raises(PermissionError): + leaf.unlink() + assert {path.name for path in parent.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" + 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]) +@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") + + 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): + 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="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_during_mode_probe_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 flags & os.O_EXCL and not flags & os.O_TRUNC + fd = original(path, flags, mode) + attempted.append(leaf) + if kind == "file": + leaf.write_text("introduced") + else: + leaf.symlink_to(outside) + return fd + + 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]) +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 + + +@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