From b8d9228a74bd5578a298a3bbed95f0190eb893f4 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:24:31 -0600 Subject: [PATCH 1/4] Use handle-based exclusive creation in FileHelper Anchor byte and text creation to policy-resolved parent directories while preserving contained links, root aliases, modes, and encoding. Reuse the Windows handle primitive and cover creation behavior with focused tests. 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 | 30 +- src/specify_cli/_file_handles.py | 62 ++++ src/specify_cli/file_helper.py | 47 ++- src/specify_cli/workflows/_catalog_cache.py | 59 +--- tests/test_file_helper.py | 312 ++++++++++++++++++++ 5 files changed, 441 insertions(+), 69 deletions(-) create mode 100644 src/specify_cli/_file_handles.py diff --git a/design/file-helper.md b/design/file-helper.md index b9dbcddd2f..976a8574e5 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -164,7 +164,14 @@ helpers for independent project/source/managed boundaries. existing leaves, including dangling links, before opening the destination. This avoids target creation on backends that follow dangling links despite exclusive-open flags. `O_EXCL` and `O_NOFOLLOW` (where available) remain in use; - the static preflight does not eliminate concurrent path-change races. + the policy-resolved parent hierarchy is anchored through creation. POSIX + opens each resolved directory without following links and creates the leaf + relative to the final directory descriptor. Windows pins the canonical root + and every resolved parent with non-reparse handles withholding delete sharing. + Allowed contained parent links and trusted root aliases are resolved before + anchoring; they are not banned. Parents must already exist, and the supplied + mode remains filtered by the process umask. Unsupported anchoring primitives + fail explicitly rather than falling back to unanchored creation. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. Replacement files use the supplied mode; metadata and @@ -209,13 +216,17 @@ entries, not reject a whole project for excluded/unrelated links. Preflight detects static policy failures before recursive deletion or parent creation. Atomic writes recheck the original path before replacement, and -deletion rechecks each accessed entry. Portable path checks are **not** a -race-free sandbox: another process can exchange parents or entries between +deletion rechecks each accessed entry. Those path-based operations are **not** +a race-free sandbox: another process can exchange parents or entries between checks and syscalls, and an I/O failure during mutation can leave partial -results. Protect against concurrent untrusted mutation separately; descriptor- -relative traversal or platform-specific mechanisms are future work, not a -claim of this API. The helper does not constrain subprocesses or third-party -code. Exclusive creation uses `O_EXCL` and `O_NOFOLLOW` where available. +results. Protect against concurrent untrusted mutation separately. +Exclusive file creation anchors its resolved parent hierarchy as described +above. On POSIX, renaming an opened directory does not redirect creation to +its replacement: creation stays with the opened directory, even if it is +renamed out of the root. This is not a guarantee of stable namespace membership +under concurrent renames, nor does parent anchoring make every leaf preflight +atomic with the subsequent open. The helper does not constrain subprocesses +or third-party code. Existing safe-write mechanisms informed this helper, but existing shared infrastructure warning/skip behavior and development-mode link creation are @@ -229,4 +240,7 @@ path replacement. Windows path classification and directory-mode reparse rejection have portable regression tests. Native Windows path and junction tests also exist and are skipped on other hosts; running the portable cases on macOS does not validate -Windows filesystem syscalls or junction behavior. +Windows filesystem syscalls or junction behavior. Exclusive-creation tests +cover parent replacement before anchoring and at the final open, along with +native Windows parent-handle pinning and portable handle-lifetime checks; +portable checks do not substitute for native Windows execution. diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py new file mode 100644 index 0000000000..dcc6626d4a --- /dev/null +++ b/src/specify_cli/_file_handles.py @@ -0,0 +1,62 @@ +"""Private platform handles for confined filesystem operations.""" + +import errno +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + + +@contextmanager +def _windows_handle(path: Path, *, directory: bool) -> Iterator[int]: + """Pin a non-reparse path by withholding Windows delete sharing.""" + import ctypes + from ctypes import wintypes + + class AttributeTagInfo(ctypes.Structure): + _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)] + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + create = kernel.CreateFileW + create.argtypes = [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.HANDLE, + ] + create.restype = wintypes.HANDLE + info = kernel.GetFileInformationByHandleEx + info.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD] + info.restype = wintypes.BOOL + close = kernel.CloseHandle + close.argtypes = [wintypes.HANDLE] + close.restype = wintypes.BOOL + + # OPEN_REPARSE_POINT inspects the link itself; BACKUP_SEMANTICS permits + # directory handles. Holding every ancestor without FILE_SHARE_DELETE + # prevents a junction/symlink swap during path-based create/replace. + # Attribute-only handles bypass share checking: include FILE_LIST_DIRECTORY + # with FILE_READ_ATTRIBUTES so even an empty directory cannot be renamed. + handle = create( + str(path), + (0x80 | 0x1) if directory else 0x80000000, + 0x3, + None, + 3, + 0x00200000 | 0x02000000, + None, + ) + if handle == wintypes.HANDLE(-1).value: + raise ctypes.WinError(ctypes.get_last_error()) + try: + attributes = AttributeTagInfo() + if not info(handle, 9, ctypes.byref(attributes), ctypes.sizeof(attributes)): + raise ctypes.WinError(ctypes.get_last_error()) + if attributes.attributes & 0x400: + raise OSError(errno.ELOOP, "Refusing a reparse-point filesystem path", str(path)) + if bool(attributes.attributes & 0x10) != directory: + raise OSError(errno.EINVAL, "Unexpected filesystem object type", str(path)) + yield handle + finally: + close(handle) diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 49441ce494..c9c1034f9e 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -1,6 +1,8 @@ """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 @@ -9,6 +11,8 @@ import tempfile from typing import TypeVar +from specify_cli._file_handles import _windows_handle + _PathType = TypeVar("_PathType", bound=PurePath) @@ -167,6 +171,34 @@ def read_bytes(self, path: Path | str) -> bytes: def read_text(self, path: Path | str, *, encoding: str = "utf-8") -> str: return self.read_bytes(path).decode(encoding) + @contextmanager + def _creation_directory(self, directory: Path) -> Iterator[int | Path]: + """Anchor an already policy-resolved parent without following new links.""" + parts = directory.relative_to(self._canonical_root).parts + with ExitStack() as stack: + if os.name == "nt": + current = self._canonical_root + stack.enter_context(_windows_handle(current, directory=True)) + for part in parts: + current = current / part + stack.enter_context(_windows_handle(current, directory=True)) + yield current + return + + if not ( + getattr(os, "O_NOFOLLOW", 0) + and getattr(os, "O_DIRECTORY", 0) + and os.open in os.supports_dir_fd + ): + raise OSError(errno.ENOTSUP, "Anchored file creation is unsupported on this platform") + flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + parent = os.open(self._canonical_root, flags) + stack.callback(os.close, parent) + for part in parts: + parent = os.open(part, flags, dir_fd=parent) + stack.callback(os.close, parent) + yield parent + def create_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Exclusively create a file; never overwrite an existing entry.""" destination = self._path(path, allow_missing=True, follow_leaf=False) @@ -178,9 +210,18 @@ def create_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) - raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(destination)) flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL flags |= getattr(os, "O_NOFOLLOW", 0) - fd = os.open(destination, flags, mode) - with os.fdopen(fd, "wb") as stream: - stream.write(content) + with self._creation_directory(destination.parent) as directory: + if isinstance(directory, Path): + fd = os.open(directory / destination.name, flags, mode) + else: + fd = os.open(destination.name, flags, mode, dir_fd=directory) + try: + stream = os.fdopen(fd, "wb") + except BaseException: + os.close(fd) + raise + with stream: + stream.write(content) def create_text( self, path: Path | str, content: str, *, encoding: str = "utf-8", mode: int = 0o644 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_helper.py b/tests/test_file_helper.py index a04b9e0a34..47a7607988 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -1,6 +1,7 @@ """Operation-level evidence for the scoped FileHelper foundation.""" from dataclasses import FrozenInstanceError +from contextlib import contextmanager import errno import os from pathlib import Path, PureWindowsPath @@ -9,6 +10,7 @@ import pytest +from specify_cli import file_helper from specify_cli.file_helper import ( FileHelper, FileHelperError, @@ -596,6 +598,315 @@ def windows_open(path, flags, mode): assert not os.path.lexists(target) +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("ancestor", ["parent", "parent/nested"]) +def test_exclusive_create_rejects_parent_exchange_after_validation( + root, link, monkeypatch, operation, allow, ancestor +): + destination = root / "parent/nested/new" + destination.parent.mkdir(parents=True) + parent = root / ancestor + retained = parent.with_name("retained") + outside = root.parent / "outside" + outside.mkdir() + redirected = outside / destination.relative_to(parent) + redirected.parent.mkdir(parents=True, exist_ok=True) + files = FileHelper(root, allow_symlinks=allow) + original_path = FileHelper._path + + def exchange_after_validation(self, path, **kwargs): + destination = original_path(self, path, **kwargs) + parent.rename(retained) + link(parent, outside) + return destination + + monkeypatch.setattr(FileHelper, "_path", exchange_after_validation) + content = b"new" if operation == "create_bytes" else "new" + with pytest.raises(OSError): + getattr(files, operation)(destination, content) + assert not redirected.exists() + assert not (retained / destination.relative_to(parent)).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative creation") +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("ancestor", ["parent", "parent/nested"]) +def test_exclusive_create_uses_open_parent_after_exchange( + root, link, monkeypatch, operation, allow, ancestor +): + destination = root / "parent/nested/new" + destination.parent.mkdir(parents=True) + parent = root / ancestor + retained = parent.with_name("retained") + outside = root.parent / "outside" + outside.mkdir() + redirected = outside / destination.relative_to(parent) + redirected.parent.mkdir(parents=True, exist_ok=True) + original_open = os.open + exchanged = False + + def exchange_before_create(path, flags, *args, **kwargs): + nonlocal exchanged + if flags & os.O_CREAT: + parent.rename(retained) + link(parent, outside) + exchanged = True + return original_open(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", exchange_before_create) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {exchange_before_create}) + content = b"new" if operation == "create_bytes" else "new" + getattr(FileHelper(root, allow_symlinks=allow), operation)(destination, content) + assert exchanged + assert not redirected.exists() + assert (retained / destination.relative_to(parent)).read_bytes() == b"new" + + +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("absolute", [False, True]) +def test_exclusive_create_preserves_contained_parent_chain( + root, link, operation, allow, absolute +): + target = root / "target/nested" + target.mkdir(parents=True) + first = link(root / "first", root / "target" if absolute else "target") + second = link(root / "second", first if absolute else "first") + path = second / "nested/new" + files = FileHelper(root, allow_symlinks=allow) + content = b"\x00\xff" if operation == "create_bytes" else "caf\u00e9\n" + if allow: + kwargs = {"encoding": "utf-16"} if operation == "create_text" else {} + getattr(files, operation)(path, content, **kwargs) + expected = content if isinstance(content, bytes) else content.encode("utf-16") + assert (target / "new").read_bytes() == expected + else: + with pytest.raises(SymlinkDeniedError): + getattr(files, operation)(path, content) + assert not (target / "new").exists() + assert first.is_symlink() and second.is_symlink() + + +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +def test_exclusive_create_accepts_trusted_root_alias(root, link, operation, allow): + alias = link(root.parent / "root-alias", root) + ancestor = link(root.parent / "ancestor-alias", root.parent) + content = b"new" if operation == "create_bytes" else "new" + for index, supplied in enumerate((alias, ancestor / root.name)): + files = FileHelper(supplied, allow_symlinks=allow) + getattr(files, operation)(supplied / f"new-{index}", content) + assert (root / f"new-{index}").read_bytes() == b"new" + assert alias.is_symlink() and ancestor.is_symlink() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX exclusive no-follow leaf open") +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("kind", ["file", "directory", "symlink", "dangling"]) +def test_exclusive_create_rejects_leaf_inserted_at_open( + root, link, monkeypatch, operation, allow, kind +): + (root / "parent").mkdir() + outside = root.parent / "outside" + if kind != "dangling": + outside.write_bytes(b"keep") + destination = root / "parent/new" + real_open = os.open + attempted = False + + def insert_leaf(path, flags, *args, **kwargs): + nonlocal attempted + if flags & os.O_CREAT: + attempted = True + if kind == "file": + destination.write_bytes(b"keep") + elif kind == "directory": + destination.mkdir() + else: + link(destination, outside) + return real_open(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", insert_leaf) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {insert_leaf}) + content = b"new" if operation == "create_bytes" else "new" + with pytest.raises(FileExistsError): + getattr(FileHelper(root, allow_symlinks=allow), operation)(destination, content) + assert attempted + if kind == "file": + assert destination.read_bytes() == b"keep" + elif kind == "directory": + assert list(destination.iterdir()) == [] + else: + assert destination.is_symlink() + if kind == "dangling": + assert not outside.exists() + else: + assert outside.read_bytes() == b"keep" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode and umask semantics") +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +def test_exclusive_create_preserves_mode_and_umask(root, operation, allow): + previous = os.umask(0o027) + try: + content = b"new" if operation == "create_bytes" else "new" + getattr(FileHelper(root, allow_symlinks=allow), operation)("new", content, mode=0o666) + finally: + os.umask(previous) + assert (root / "new").stat().st_mode & 0o777 == 0o640 + + +@pytest.mark.parametrize("encoding", ["ascii", "unknown-encoding"]) +def test_exclusive_create_text_encoding_failure_precedes_creation(root, encoding): + with pytest.raises((UnicodeEncodeError, LookupError)): + FileHelper(root).create_text("new", "caf\u00e9", encoding=encoding) + assert not (root / "new").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX capability checks") +@pytest.mark.parametrize("capability", ["O_NOFOLLOW", "O_DIRECTORY", "supports_dir_fd"]) +def test_exclusive_create_requires_anchored_io(root, monkeypatch, capability): + monkeypatch.setattr(os, capability, set() if capability == "supports_dir_fd" else 0) + with pytest.raises(OSError) as error: + FileHelper(root).create_bytes("new", b"new") + assert error.value.errno == errno.ENOTSUP + assert not (root / "new").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory descriptor lifetimes") +@pytest.mark.parametrize("failure", ["parent", "open", "fdopen", "write", None]) +def test_exclusive_create_releases_directory_handles(root, monkeypatch, failure): + (root / "parent/nested").mkdir(parents=True) + real_open = os.open + real_fdopen = os.fdopen + opened = [] + + def observe_open(path, flags, *args, **kwargs): + if failure == "parent" and path == "nested": + raise PermissionError("parent denied") + if failure == "open" and flags & os.O_CREAT: + raise PermissionError("open denied") + fd = real_open(path, flags, *args, **kwargs) + opened.append(fd) + return fd + + class FailedWriter: + def __init__(self, fd): + self.stream = real_fdopen(fd, "wb") + + def __enter__(self): + return self + + def write(self, content): + raise OSError("write failed") + + def __exit__(self, *args): + self.stream.close() + + def observe_fdopen(fd, *args): + if failure == "fdopen": + raise OSError("fdopen failed") + if failure == "write": + return FailedWriter(fd) + return real_fdopen(fd, *args) + + monkeypatch.setattr(os, "open", observe_open) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {observe_open}) + monkeypatch.setattr(os, "fdopen", observe_fdopen) + if failure: + with pytest.raises(OSError, match=failure): + FileHelper(root).create_bytes("parent/nested/new", b"new") + else: + FileHelper(root).create_bytes("parent/nested/new", b"new") + assert (root / "parent/nested/new").read_bytes() == b"new" + assert opened + for fd in opened: + with pytest.raises(OSError) as error: + os.fstat(fd) + assert error.value.errno == errno.EBADF + + +@pytest.mark.parametrize("failure", ["parent", "open", None]) +def test_exclusive_create_windows_pins_resolved_hierarchy_portably( + root, link, monkeypatch, failure +): + (root / "parent/nested").mkdir(parents=True) + alias = link(root / "alias", root / "parent") + files = FileHelper(root, allow_symlinks=True) + pinned = [] + acquired = [] + real_open = os.open + expected = [root, root / "parent", root / "parent/nested"] + + @contextmanager + def pin(path, *, directory): + assert directory + if failure == "parent" and path == expected[-1]: + raise PermissionError("parent denied") + pinned.append(path) + acquired.append(path) + try: + yield 1 + finally: + assert pinned.pop() == path + + def open_pinned(path, flags, mode): + assert pinned == expected + assert path == root / "parent/nested/new" + assert flags & os.O_CREAT and flags & os.O_EXCL + if failure == "open": + raise PermissionError("open denied") + return real_open(path, flags, mode) + + windows_os = SimpleNamespace(**{**vars(os), "name": "nt", "open": open_pinned}) + monkeypatch.setattr(file_helper, "os", windows_os) + monkeypatch.setattr(file_helper, "_windows_handle", pin) + if failure: + with pytest.raises(PermissionError, match=failure): + files.create_bytes(alias / "nested/new", b"new") + assert not (root / "parent/nested/new").exists() + else: + files.create_bytes(alias / "nested/new", b"new") + assert (root / "parent/nested/new").read_bytes() == b"new" + assert acquired == (expected[:-1] if failure == "parent" else expected) + assert pinned == [] + assert alias.is_symlink() + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows directory handle semantics") +@pytest.mark.parametrize("ancestor", [".", "parent", "parent/nested"]) +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +def test_exclusive_create_windows_blocks_parent_exchange( + root, monkeypatch, ancestor, operation, allow +): + (root / "parent/nested").mkdir(parents=True) + parent = root / ancestor + retained = parent.with_name(parent.name + "-retained") + real_open = os.open + attempted = False + + def try_exchange(path, flags, *args, **kwargs): + nonlocal attempted + if flags & os.O_CREAT: + attempted = True + with pytest.raises(OSError): + parent.rename(retained) + return real_open(path, flags, *args, **kwargs) + + monkeypatch.setattr(os, "open", try_exchange) + content = b"new" if operation == "create_bytes" else "new" + getattr(FileHelper(root, allow_symlinks=allow), operation)("parent/nested/new", content) + assert attempted + assert (root / "parent/nested/new").read_bytes() == b"new" + parent.rename(retained) + assert retained.is_dir() + + def test_symlink_creation_requires_permission_and_contained_target(root, link): (root / "file").write_text("ok") with pytest.raises(SymlinkDeniedError): @@ -680,6 +991,7 @@ def fail(*args, **kwargs): raise PermissionError("creation denied") monkeypatch.setattr("specify_cli.file_helper.os.open", fail) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {fail}) with pytest.raises(PermissionError, match="creation denied"): files.create_bytes("file", b"bad") assert list(root.iterdir()) == [] From e506d29eb599f339481df1f9e6e96a311a90e5f7 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:52:44 -0600 Subject: [PATCH 2/4] Fix FileHelper creation handle compatibility Restore the complete CreateFileW prototype, use search-only POSIX directory handles where available, and close previous parent descriptors during traversal. Add regression coverage for the Windows prototype, directory permissions, and bounded descriptor use. 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 | 1 + src/specify_cli/file_helper.py | 34 +++++++++-------- tests/test_file_handles.py | 59 +++++++++++++++++++++++++++++ tests/test_file_helper.py | 64 ++++++++++++++++++++++++++++++++ 5 files changed, 149 insertions(+), 17 deletions(-) create mode 100644 tests/test_file_handles.py diff --git a/design/file-helper.md b/design/file-helper.md index 976a8574e5..b5e30586ee 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -166,8 +166,12 @@ helpers for independent project/source/managed boundaries. exclusive-open flags. `O_EXCL` and `O_NOFOLLOW` (where available) remain in use; the policy-resolved parent hierarchy is anchored through creation. POSIX opens each resolved directory without following links and creates the leaf - relative to the final directory descriptor. Windows pins the canonical root - and every resolved parent with non-reparse handles withholding delete sharing. + relative to the final directory descriptor. Search-only handles (`O_PATH` + or `O_SEARCH`, where available) avoid adding a directory-read permission + requirement. Traversal closes each previous parent after opening its child, + keeping the number of live directory descriptors independent of path depth. + Windows pins the canonical root and every resolved parent with non-reparse + handles withholding delete sharing. Allowed contained parent links and trusted root aliases are resolved before anchoring; they are not banned. Parents must already exist, and the supplied mode remains filtered by the process umask. Unsupported anchoring primitives diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index dcc6626d4a..460e25525c 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -23,6 +23,7 @@ class AttributeTagInfo(ctypes.Structure): wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD, + wintypes.DWORD, wintypes.HANDLE, ] create.restype = wintypes.HANDLE diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index c9c1034f9e..c5fafed2ab 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -175,29 +175,33 @@ def read_text(self, path: Path | str, *, encoding: str = "utf-8") -> str: def _creation_directory(self, directory: Path) -> Iterator[int | Path]: """Anchor an already policy-resolved parent without following new links.""" parts = directory.relative_to(self._canonical_root).parts - with ExitStack() as stack: - if os.name == "nt": + if os.name == "nt": + with ExitStack() as stack: current = self._canonical_root stack.enter_context(_windows_handle(current, directory=True)) for part in parts: current = current / part stack.enter_context(_windows_handle(current, directory=True)) yield current - return - - if not ( - getattr(os, "O_NOFOLLOW", 0) - and getattr(os, "O_DIRECTORY", 0) - and os.open in os.supports_dir_fd - ): - raise OSError(errno.ENOTSUP, "Anchored file creation is unsupported on this platform") - flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) - parent = os.open(self._canonical_root, flags) - stack.callback(os.close, parent) + return + + if not ( + getattr(os, "O_NOFOLLOW", 0) + and getattr(os, "O_DIRECTORY", 0) + and os.open in os.supports_dir_fd + ): + raise OSError(errno.ENOTSUP, "Anchored file creation is unsupported on this platform") + access = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY + flags = access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) + parent = os.open(self._canonical_root, flags) + try: for part in parts: - parent = os.open(part, flags, dir_fd=parent) - stack.callback(os.close, parent) + child = os.open(part, flags, dir_fd=parent) + os.close(parent) + parent = child yield parent + finally: + os.close(parent) def create_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Exclusively create a file; never overwrite an existing entry.""" diff --git a/tests/test_file_handles.py b/tests/test_file_handles.py new file mode 100644 index 0000000000..75fae0ead2 --- /dev/null +++ b/tests/test_file_handles.py @@ -0,0 +1,59 @@ +"""Portable contract checks for the private Windows handle primitive.""" + +import ctypes +from ctypes import wintypes +from types import SimpleNamespace + +import pytest + +from specify_cli._file_handles import _windows_handle + + +@pytest.mark.parametrize("directory", [False, True]) +def test_windows_handle_declares_complete_createfile_prototype(tmp_path, monkeypatch, directory): + closed = [] + + def create(*args): + assert create.argtypes == [ + wintypes.LPCWSTR, + wintypes.DWORD, + wintypes.DWORD, + wintypes.LPVOID, + wintypes.DWORD, + wintypes.DWORD, + wintypes.HANDLE, + ] + assert create.restype is wintypes.HANDLE + assert args == ( + str(tmp_path), + (0x80 | 0x1) if directory else 0x80000000, + 0x3, + None, + 3, + 0x00200000 | 0x02000000, + None, + ) + return 123 + + def info(handle, info_class, buffer, size): + assert handle == 123 and info_class == 9 + assert size == 2 * ctypes.sizeof(wintypes.DWORD) + attributes = ctypes.cast(buffer, ctypes.POINTER(wintypes.DWORD)) + attributes[0] = 0x10 if directory else 0 + return True + + def close(handle): + closed.append(handle) + return True + + def load_kernel(name, *, use_last_error): + assert name == "kernel32" and use_last_error + return SimpleNamespace( + CreateFileW=create, GetFileInformationByHandleEx=info, CloseHandle=close + ) + + monkeypatch.setattr(ctypes, "WinDLL", load_kernel, raising=False) + with _windows_handle(tmp_path, directory=directory) as handle: + assert handle == 123 + assert closed == [] + assert closed == [123] diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 47a7607988..c2f658485f 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -760,6 +760,70 @@ def test_exclusive_create_preserves_mode_and_umask(root, operation, allow): assert (root / "new").stat().st_mode & 0o777 == 0o640 +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory permissions") +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +@pytest.mark.parametrize("ancestor", [".", "parent", "parent/nested"]) +@pytest.mark.parametrize("permissions", [0o300, 0o200]) +def test_exclusive_create_respects_write_and_search_permissions( + root, operation, allow, ancestor, permissions +): + if os.geteuid() == 0: + pytest.skip("Root bypasses directory permission checks") + (root / "parent/nested").mkdir(parents=True) + files = FileHelper(root, allow_symlinks=allow) + restricted = root / ancestor + content = b"new" if operation == "create_bytes" else "new" + restricted.chmod(permissions) + try: + if permissions == 0o300: + getattr(files, operation)("parent/nested/new", content) + assert (root / "parent/nested/new").read_bytes() == b"new" + else: + with pytest.raises(PermissionError): + getattr(files, operation)("parent/nested/new", content) + finally: + restricted.chmod(0o700) + if permissions == 0o200: + assert not (root / "parent/nested/new").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory descriptor traversal") +@pytest.mark.parametrize("operation", ["create_bytes", "create_text"]) +@pytest.mark.parametrize("allow", [False, True]) +def test_exclusive_create_bounds_live_parent_descriptors(root, monkeypatch, operation, allow): + destination = root.joinpath(*("nested" for _ in range(32)), "new") + destination.parent.mkdir(parents=True) + files = FileHelper(root, allow_symlinks=allow) + real_open = os.open + real_close = os.close + live = set() + maximum = 0 + + def limited_open(path, flags, *args, **kwargs): + nonlocal maximum + if len(live) >= 2: + raise OSError(errno.EMFILE, "parent descriptor budget exhausted") + fd = real_open(path, flags, *args, **kwargs) + if flags & os.O_DIRECTORY: + live.add(fd) + maximum = max(maximum, len(live)) + return fd + + def observe_close(fd): + real_close(fd) + live.remove(fd) + + monkeypatch.setattr(os, "open", limited_open) + monkeypatch.setattr(os, "close", observe_close) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {limited_open}) + content = b"new" if operation == "create_bytes" else "new" + getattr(files, operation)(destination, content) + assert destination.read_bytes() == b"new" + assert maximum == 2 + assert live == set() + + @pytest.mark.parametrize("encoding", ["ascii", "unknown-encoding"]) def test_exclusive_create_text_encoding_failure_precedes_creation(root, encoding): with pytest.raises((UnicodeEncodeError, LookupError)): From 60831807f80d4837685c180f394e8533970fef2b Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:05:36 -0600 Subject: [PATCH 3/4] Support directory search handles on older macOS Python builds Use Darwin's native O_SEARCH value when Python does not expose the flag. Cover write/search-only parents with missing exported search flags and preserve no-follow directory traversal. 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 | 6 ++++-- src/specify_cli/file_helper.py | 6 +++++- tests/test_file_helper.py | 18 +++++++++++++++++- 3 files changed, 26 insertions(+), 4 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b5e30586ee..941210739e 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -168,8 +168,10 @@ helpers for independent project/source/managed boundaries. opens each resolved directory without following links and creates the leaf relative to the final directory descriptor. Search-only handles (`O_PATH` or `O_SEARCH`, where available) avoid adding a directory-read permission - requirement. Traversal closes each previous parent after opening its child, - keeping the number of live directory descriptors independent of path depth. + requirement; macOS uses the native `O_SEARCH` value when an older Python + build does not expose it. Traversal closes each previous parent after opening + its child, keeping the number of live directory descriptors independent of + path depth. Windows pins the canonical root and every resolved parent with non-reparse handles withholding delete sharing. Allowed contained parent links and trusted root aliases are resolved before diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index c5fafed2ab..e1c4a0cf2d 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -8,6 +8,7 @@ import os from pathlib import Path, PurePath, PureWindowsPath import stat +import sys import tempfile from typing import TypeVar @@ -191,7 +192,10 @@ def _creation_directory(self, directory: Path) -> Iterator[int | Path]: and os.open in os.supports_dir_fd ): raise OSError(errno.ENOTSUP, "Anchored file creation is unsupported on this platform") - access = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) or os.O_RDONLY + access = getattr(os, "O_PATH", 0) or getattr(os, "O_SEARCH", 0) + if not access: + # Darwin's O_SEARCH ABI is missing from some older Python builds. + access = (0x40000000 | os.O_DIRECTORY) if sys.platform == "darwin" else os.O_RDONLY flags = access | os.O_DIRECTORY | os.O_NOFOLLOW | getattr(os, "O_CLOEXEC", 0) parent = os.open(self._canonical_root, flags) try: diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index c2f658485f..40ecd09efa 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -6,6 +6,7 @@ import os from pathlib import Path, PureWindowsPath import subprocess +import sys from types import SimpleNamespace import pytest @@ -765,11 +766,26 @@ def test_exclusive_create_preserves_mode_and_umask(root, operation, allow): @pytest.mark.parametrize("allow", [False, True]) @pytest.mark.parametrize("ancestor", [".", "parent", "parent/nested"]) @pytest.mark.parametrize("permissions", [0o300, 0o200]) +@pytest.mark.parametrize( + "search_api", + [ + "default", + pytest.param( + "legacy-macos", + marks=pytest.mark.skipif( + sys.platform != "darwin", reason="macOS search-only directory handles" + ), + ), + ], +) def test_exclusive_create_respects_write_and_search_permissions( - root, operation, allow, ancestor, permissions + root, monkeypatch, operation, allow, ancestor, permissions, search_api ): if os.geteuid() == 0: pytest.skip("Root bypasses directory permission checks") + if search_api == "legacy-macos": + monkeypatch.delattr(os, "O_PATH", raising=False) + monkeypatch.delattr(os, "O_SEARCH", raising=False) (root / "parent/nested").mkdir(parents=True) files = FileHelper(root, allow_symlinks=allow) restricted = root / ancestor From 95e7a692f3efae4427b8085b98d5804e91e31f63 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:13:51 -0600 Subject: [PATCH 4/4] Clarify FileHelper creation access requirements and operation limits Document Windows directory-listing and attribute access for pinned parents, and keep the path-based-operation disclaimer explicit for reads, directory creation, writes, overwrites, symlink creation, and deletion. 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 | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 941210739e..186e563439 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -173,7 +173,10 @@ helpers for independent project/source/managed boundaries. its child, keeping the number of live directory descriptors independent of path depth. Windows pins the canonical root and every resolved parent with non-reparse - handles withholding delete sharing. + handles withholding delete sharing. Each anchored directory must permit + `FILE_LIST_DIRECTORY` and `FILE_READ_ATTRIBUTES` access. An ACL that permits + creating files but denies directory listing can therefore cause creation to + fail before opening the leaf. Allowed contained parent links and trusted root aliases are resolved before anchoring; they are not banned. Parents must already exist, and the supplied mode remains filtered by the process umask. Unsupported anchoring primitives @@ -222,7 +225,9 @@ 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. Those path-based operations are **not** +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.