From ea2dafd436e1d6c082b3cd32e326883f09b7ae51 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:27:49 -0600 Subject: [PATCH 1/9] fix: preserve FileHelper atomic writes for long names and strict modes Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 7 +- src/specify_cli/file_helper.py | 38 +++++++++-- tests/test_file_helper.py | 118 +++++++++++++++++++++++++++++++++ 3 files changed, 156 insertions(+), 7 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b9fca560b7..b3c79b31cd 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -274,9 +274,12 @@ descriptor-relative or change their documented concurrency limitations. 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 + `encoding="utf-8"`. A short, exclusively created sibling stages the write. + On POSIX, the initial mode is restricted to the requested owner read/write + bits and filtered by the process umask. After writing, the supplied mode is + applied with `chmod` using the platform's supported semantics. Metadata and hard-link identity are not preserved. Atomic means same-directory - `os.replace`, not crash durability. + `os.replace`, not crash durability or protection from concurrent path changes. - `overwrite_text(path, content, encoding="utf-8")` is a **non-atomic** text upsert with existing parents, used for configuration compatibility. It uses the same accessed-path/link/containment checks as other operations, follows diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 9b00895ae0..570fa8d22f 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -3,6 +3,7 @@ import codecs import errno import os +import secrets import stat import sys import tempfile @@ -587,17 +588,44 @@ def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> destination = self._path(path, allow_missing=True) if destination.exists(): self._require_file(destination) - fd, temporary = tempfile.mkstemp(prefix=f".{destination.name}.", dir=destination.parent) - temporary_path = Path(temporary) + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + flags |= getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + # Keep the sibling name short regardless of the destination's length. + for _ in range(10): + name = f".{secrets.token_hex(8)}.tmp" + if name == destination.name.rstrip(" .").casefold(): + continue + temporary_path = destination.with_name(name) + try: + # Retain private staging, intersected with the requested mode. + fd = os.open(temporary_path, flags, mode & 0o600) + except FileExistsError: + continue + break + else: + raise FileExistsError(errno.EEXIST, "Could not allocate a staging file", str(destination)) + published = False try: - with os.fdopen(fd, "wb") as stream: - stream.write(content) + try: + with os.fdopen(fd, "wb", closefd=False) as stream: + stream.write(content) + finally: + os.close(fd) temporary_path.chmod(mode) if self._path(path, allow_missing=True) != destination: raise FileHelperError(f"Destination changed during write: {path}") os.replace(temporary_path, destination) + published = True finally: - temporary_path.unlink(missing_ok=True) + if not published: + try: + temporary_path.unlink(missing_ok=True) + except PermissionError: + if os.name != "nt" or temporary_path.stat().st_mode & stat.S_IWRITE: + raise + # Windows cannot unlink a read-only file without clearing the attribute. + temporary_path.chmod(0o600) + temporary_path.unlink(missing_ok=True) def write_text( self, path: Path | str, content: str, *, encoding: str = "utf-8", mode: int = 0o644 diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 1448be9121..d1422ba79d 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3442,6 +3442,124 @@ def fail(*args): assert list(root.iterdir()) == [root / "file"] +@pytest.mark.skipif(os.name == "nt", reason="Windows path length depends on host configuration") +def test_atomic_write_creates_and_replaces_long_component(root, monkeypatch): + destination = root / ("x" * 252 + ".sh") + try: + destination.touch() + except OSError as exc: + if exc.errno == errno.ENAMETOOLONG: + pytest.skip("Filesystem does not support a 255-byte component") + raise + destination.unlink() + replace = os.replace + old_content = None + + def observe(source, target): + assert source.parent == target.parent == destination.parent + assert source != target == destination + assert (target.read_bytes() if target.exists() else None) == old_content + replace(source, target) + + monkeypatch.setattr(os, "replace", observe) + with FileHelper(root) as files: + for content in (b"first", b"second"): + files.write_bytes(destination, content) + assert destination.read_bytes() == content + assert list(root.iterdir()) == [destination] + old_content = content + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits required") +@pytest.mark.parametrize(("mode", "staging_mode"), [(0o400, 0o400), (0o755, 0o600)]) +def test_atomic_write_staging_mode_and_exact_final_mode(root, monkeypatch, mode, staging_mode): + fdopen = os.fdopen + observed_modes = [] + + def observe(fd, *args, **kwargs): + observed_modes.append(stat.S_IMODE(os.fstat(fd).st_mode)) + return fdopen(fd, *args, **kwargs) + + monkeypatch.setattr(os, "fdopen", observe) + previous = os.umask(0o077) + try: + with FileHelper(root) as files: + files.write_bytes("file", b"new", mode=mode) + finally: + os.umask(previous) + assert observed_modes == [staging_mode] + assert stat.S_IMODE((root / "file").stat().st_mode) == mode + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows read-only semantics required") +def test_atomic_write_windows_readonly_mode_and_cleanup(root, monkeypatch): + fdopen = os.fdopen + replace = os.replace + observed_modes = [] + + def observe(fd, *args, **kwargs): + observed_modes.append(os.fstat(fd).st_mode & stat.S_IWRITE) + return fdopen(fd, *args, **kwargs) + + def fail(source, target): + assert not source.stat().st_mode & stat.S_IWRITE + raise PermissionError("replacement denied") + + monkeypatch.setattr(os, "fdopen", observe) + monkeypatch.setattr(os, "replace", fail) + with FileHelper(root) as files: + with pytest.raises(PermissionError, match="replacement denied"): + files.write_bytes("file", b"new", mode=0o400) + assert not list(root.iterdir()) + monkeypatch.setattr(os, "replace", replace) + files.write_bytes("file", b"new", mode=0o400) + target = root / "file" + try: + assert not target.stat().st_mode & stat.S_IWRITE + assert target.read_bytes() == b"new" + assert observed_modes == [0, 0] + finally: + target.chmod(0o600) + + +def test_atomic_write_retries_staging_collisions_without_touching_entries(root, monkeypatch): + existing = root / ".0000000000000000.tmp" + existing.write_bytes(b"keep") + destination = root / ".1111111111111111.tmp" + tokens = iter(["0" * 16, "1" * 16, "2" * 16]) + replace = os.replace + + def observe(source, target): + assert not target.exists() + replace(source, target) + + monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: next(tokens)) + monkeypatch.setattr(os, "replace", observe) + with FileHelper(root) as files: + files.write_bytes(destination, b"new") + assert existing.read_bytes() == b"keep" + assert destination.read_bytes() == b"new" + assert set(root.iterdir()) == {destination, existing} + + +def test_atomic_write_deny_revalidates_destination_and_cleans_stage(root, link, monkeypatch): + target = root / "target" + target.write_bytes(b"old") + destination = root / "destination" + chmod = Path.chmod + + def insert_link(path, mode, **kwargs): + chmod(path, mode, **kwargs) + link(destination, target) + + monkeypatch.setattr(Path, "chmod", insert_link) + with FileHelper(root) as files, pytest.raises(SymlinkDeniedError): + files.write_bytes(destination, b"new") + assert destination.is_symlink() + assert target.read_bytes() == b"old" + assert set(root.iterdir()) == {destination, target} + + def test_native_permission_failure_is_not_suppressed(root, monkeypatch): files = FileHelper(root) From 336c07d060a8094e6f3fc934717f2583514a0981 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 08:56:57 -0600 Subject: [PATCH 2/9] fix: fit atomic staging names within the available path length Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 2 + src/specify_cli/file_helper.py | 14 +++- tests/test_file_helper.py | 115 +++++++++++++++++++++++++++++++++ 3 files changed, 129 insertions(+), 2 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index b3c79b31cd..7771ce191d 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -275,6 +275,8 @@ descriptor-relative or change their documented concurrency limitations. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. A short, exclusively created sibling stages the write. + If the staging name exceeds a path limit, retry with a name no longer than + the destination's final component. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 570fa8d22f..6f671c71fe 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -590,9 +590,10 @@ def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> self._require_file(destination) flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL flags |= getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) - # Keep the sibling name short regardless of the destination's length. + use_short_name = False for _ in range(10): - name = f".{secrets.token_hex(8)}.tmp" + token = secrets.token_hex(8) + name = token[:len(destination.name)] if use_short_name else f".{token}.tmp" if name == destination.name.rstrip(" .").casefold(): continue temporary_path = destination.with_name(name) @@ -601,6 +602,15 @@ def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> fd = os.open(temporary_path, flags, mode & 0o600) except FileExistsError: continue + except OSError as exc: + # The Windows CRT can report an overlong path as ENOENT. + length_error = exc.errno == errno.ENAMETOOLONG or ( + os.name == "nt" and exc.errno == errno.ENOENT + ) + if use_short_name or len(name) <= len(destination.name) or not length_error: + raise + use_short_name = True + continue break else: raise FileExistsError(errno.EEXIST, "Could not allocate a staging file", str(destination)) diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index d1422ba79d..ae31361e97 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3442,6 +3442,107 @@ def fail(*args): assert list(root.iterdir()) == [root / "file"] +def test_atomic_fdopen_failure_closes_stage_and_preserves_target(root, monkeypatch): + destination = root / "file" + destination.write_bytes(b"old") + stage_fds = [] + + def fail(fd, *args, **kwargs): + os.fstat(fd) + stage_fds.append(fd) + raise OSError("fdopen failed") + + monkeypatch.setattr(os, "fdopen", fail) + with FileHelper(root) as files, pytest.raises(OSError, match="fdopen failed"): + files.write_bytes(destination, b"new") + assert len(stage_fds) == 1 + with pytest.raises(OSError) as exc: + os.fstat(stage_fds[0]) + assert exc.value.errno == errno.EBADF + assert destination.read_bytes() == b"old" + assert list(root.iterdir()) == [destination] + + +def test_atomic_writable_stage_cleanup_propagates_unlink_failure(root, monkeypatch): + destination = root / "file" + destination.write_bytes(b"old") + error = PermissionError(errno.EACCES, "unlink denied") + chmod = Path.chmod + modes = [] + failed_unlinks = [] + + def replace_fails(source, target): + assert source.stat().st_mode & stat.S_IWRITE + raise OSError("replacement failed") + + def unlink_fails(path, *, missing_ok=False): + failed_unlinks.append(path) + raise error + + def observe_chmod(path, mode): + modes.append(mode) + chmod(path, mode) + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "replace": replace_fails})) + model.setattr(Path, "chmod", observe_chmod) + model.setattr(Path, "unlink", unlink_fails) + with pytest.raises(PermissionError) as exc: + files.write_bytes(destination, b"new") + assert exc.value is error + assert modes == [0o644] + assert len(failed_unlinks) == 1 + assert destination.read_bytes() == b"old" + assert set(root.iterdir()) == {destination, failed_unlinks[0]} + failed_unlinks[0].unlink() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +@pytest.mark.parametrize("leaf_budget", [1, 16]) +def test_atomic_write_near_native_path_limit(root, monkeypatch, leaf_budget): + parent = root.resolve() + path_max = os.pathconf(parent, "PC_PATH_MAX") + name_max = os.pathconf(parent, "PC_NAME_MAX") + if path_max < 0 or name_max < 0 or path_max - len(os.fsencode(parent)) < 22: + pytest.skip("No usable native path-length limit") + # Reserve the leaf budget plus the separator and NUL. + while (remaining := path_max - leaf_budget - 2 - len(os.fsencode(parent))) > 0: + component_size = min(name_max, remaining - 1) + if remaining - component_size == 2: + component_size -= 1 + parent /= "x" * component_size + parent.mkdir() + destination = parent / "f" + assert len(os.fsencode(destination)) == path_max - leaf_budget + destination.write_bytes(b"probe") + destination.unlink() + monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: "2" * 16) + with FileHelper(root) as files: + for content in (b"first", b"second"): + files.write_bytes(destination, content) + assert destination.read_bytes() == content + assert list(parent.iterdir()) == [destination] + + +def test_atomic_write_retries_windows_enoent_with_short_name(root, monkeypatch): + destination = root / "file" + attempted = [] + + def open_with_limit(path, flags, mode): + attempted.append(path) + if len(path.name) > len(destination.name): + raise FileNotFoundError(errno.ENOENT, "modeled Windows CRT path limit") + return os.open(path, flags, mode) + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": open_with_limit})) + model.setattr(file_helper.secrets, "token_hex", lambda _: "2" * 16) + files.write_bytes(destination, b"new") + assert len(attempted) == 2 + assert destination.read_bytes() == b"new" + assert list(root.iterdir()) == [destination] + + @pytest.mark.skipif(os.name == "nt", reason="Windows path length depends on host configuration") def test_atomic_write_creates_and_replaces_long_component(root, monkeypatch): destination = root / ("x" * 252 + ".sh") @@ -3542,6 +3643,20 @@ def observe(source, target): assert set(root.iterdir()) == {destination, existing} +def test_atomic_write_collision_exhaustion_preserves_entries(root, monkeypatch): + existing = root / ".0000000000000000.tmp" + existing.write_bytes(b"keep") + destination = root / "file" + destination.write_bytes(b"old") + monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: "0" * 16) + with FileHelper(root) as files, pytest.raises(FileExistsError) as exc: + files.write_bytes(destination, b"new") + assert exc.value.errno == errno.EEXIST + assert existing.read_bytes() == b"keep" + assert destination.read_bytes() == b"old" + assert set(root.iterdir()) == {destination, existing} + + def test_atomic_write_deny_revalidates_destination_and_cleans_stage(root, link, monkeypatch): target = root / "target" target.write_bytes(b"old") From cde149da51b7f08ab78fddac75980c3b2ac7f9c8 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:29:13 -0600 Subject: [PATCH 3/9] fix: isolate near-limit FileHelper staging payloads Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 11 ++- src/specify_cli/file_helper.py | 143 +++++++++++++++++++++++------ tests/test_file_helper.py | 160 ++++++++++++++++++++++++++++++--- 3 files changed, 272 insertions(+), 42 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 7771ce191d..f910ccde60 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -275,13 +275,16 @@ descriptor-relative or change their documented concurrency limitations. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. A short, exclusively created sibling stages the write. - If the staging name exceeds a path limit, retry with a name no longer than - the destination's final component. + If the staging path exceeds a path limit, stage inside a separate temporary + directory under the destination's parent instead of using a short file name + that could also be another write's destination. This uses directory-relative + operations where supported on POSIX and an extended staging path on Windows. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and - hard-link identity are not preserved. Atomic means same-directory - `os.replace`, not crash durability or protection from concurrent path changes. + hard-link identity are not preserved. Atomic means same-filesystem + replacement with `os.replace`, not crash durability or protection from + concurrent path changes. - `overwrite_text(path, content, encoding="utf-8")` is a **non-atomic** text upsert with existing parents, used for configuration compatibility. It uses the same accessed-path/link/containment checks as other operations, follows diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 6f671c71fe..64e80bbd77 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -44,6 +44,15 @@ def _strip_extended_length_prefix(path: _PathType) -> _PathType: return path +def _windows_extended_path(path: _PathType) -> _PathType: + raw = str(path) + if raw.startswith("\\\\?\\"): + return path + if raw.startswith("\\\\"): + return type(path)("\\\\?\\UNC\\" + raw[2:]) + return type(path)("\\\\?\\" + raw) + + class FileHelperError(ValueError): """An operation violates the scoped filesystem contract.""" @@ -590,16 +599,41 @@ def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> self._require_file(destination) flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL flags |= getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) - use_short_name = False + with ExitStack() as staging: + fd, stage, parent_fd = self._open_atomic_stage(destination, flags, mode, staging) + published = False + try: + try: + with os.fdopen(fd, "wb", closefd=False) as stream: + stream.write(content) + if parent_fd is not None: + os.fchmod(fd, mode) + finally: + os.close(fd) + if parent_fd is None: + stage.chmod(mode) + if self._path(path, allow_missing=True) != destination: + raise FileHelperError(f"Destination changed during write: {path}") + if parent_fd is None: + os.replace(stage, destination) + else: + os.replace(stage, destination, src_dir_fd=parent_fd) + published = True + finally: + if not published: + self._unlink_atomic_stage(stage, parent_fd) + + def _open_atomic_stage( + self, destination: Path, flags: int, mode: int, staging: ExitStack, + ) -> tuple[int, Path, int | None]: + mode &= 0o600 for _ in range(10): - token = secrets.token_hex(8) - name = token[:len(destination.name)] if use_short_name else f".{token}.tmp" + name = f".{secrets.token_hex(8)}.tmp" if name == destination.name.rstrip(" .").casefold(): continue - temporary_path = destination.with_name(name) + stage = destination.with_name(name) try: - # Retain private staging, intersected with the requested mode. - fd = os.open(temporary_path, flags, mode & 0o600) + return os.open(stage, flags, mode), stage, None except FileExistsError: continue except OSError as exc: @@ -607,35 +641,88 @@ def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> length_error = exc.errno == errno.ENAMETOOLONG or ( os.name == "nt" and exc.errno == errno.ENOENT ) - if use_short_name or len(name) <= len(destination.name) or not length_error: + if not length_error or len(name) <= len(destination.name): + raise + if os.name == "nt": + if not destination.parent.is_dir(): + raise + directory = Path(tempfile.mkdtemp(dir=_windows_extended_path(destination.parent))) + staging.enter_context(self._remove_atomic_directory(directory)) + stage = directory / "payload" + return os.open(stage, flags, mode), stage, None + if not {os.mkdir, os.chmod, os.rename, os.rmdir, os.unlink} <= os.supports_dir_fd: raise - use_short_name = True - continue break else: raise FileExistsError(errno.EEXIST, "Could not allocate a staging file", str(destination)) - published = False + + # Keep the payload out of the destination's namespace, without + # spending the remaining absolute path budget on the staging name. + parent = staging.enter_context(self._posix_directory( + destination.parent, unsupported_message="Directory-relative staging is unsupported", + )) + for _ in range(10): + name = f".{secrets.token_hex(8)}.tmp" + try: + os.mkdir(name, 0o700, dir_fd=parent) + except FileExistsError: + continue + staging.enter_context(self._remove_atomic_directory(Path(name), parent)) + break + else: + raise FileExistsError(errno.EEXIST, "Could not allocate a staging directory", str(destination)) + # A restrictive umask must not make the private staging directory unusable. + os.chmod(name, 0o700, dir_fd=parent, follow_symlinks=False) + directory_fd = os.open(name, self._directory_flags(), dir_fd=parent) + staging.callback(os.close, directory_fd) + stage = Path("payload") + return os.open(stage, flags, mode, dir_fd=directory_fd), stage, directory_fd + + @staticmethod + @contextmanager + def _remove_atomic_directory(directory: Path, parent: int | None = None) -> Iterator[None]: + def remove() -> None: + if parent is None: + directory.rmdir() + else: + os.rmdir(directory, dir_fd=parent) + try: + yield + except BaseException as exc: try: - with os.fdopen(fd, "wb", closefd=False) as stream: - stream.write(content) - finally: - os.close(fd) - temporary_path.chmod(mode) - if self._path(path, allow_missing=True) != destination: - raise FileHelperError(f"Destination changed during write: {path}") - os.replace(temporary_path, destination) - published = True - finally: - if not published: + remove() + except OSError as cleanup_error: + exc.add_note(f"Could not remove atomic staging directory: {cleanup_error}") + raise + else: + remove() + + @staticmethod + def _unlink_atomic_stage(stage: Path, parent: int | None) -> None: + if parent is not None: + try: + os.unlink(stage, dir_fd=parent) + except FileNotFoundError: + pass + return + try: + stage.unlink(missing_ok=True) + except PermissionError: + if os.name != "nt": + raise + mode = stat.S_IMODE(stage.stat().st_mode) + if mode & stat.S_IWRITE: + raise + stage.chmod(mode | stat.S_IWRITE) + try: + stage.unlink(missing_ok=True) + except OSError as exc: try: - temporary_path.unlink(missing_ok=True) - except PermissionError: - if os.name != "nt" or temporary_path.stat().st_mode & stat.S_IWRITE: - raise - # Windows cannot unlink a read-only file without clearing the attribute. - temporary_path.chmod(0o600) - temporary_path.unlink(missing_ok=True) + stage.chmod(mode) + except OSError as restore_error: + exc.add_note(f"Could not restore atomic stage permissions: {restore_error}") + raise def write_text( self, path: Path | str, content: str, *, encoding: str = "utf-8", mode: int = 0o644 diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index ae31361e97..c613e82697 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3497,9 +3497,7 @@ def observe_chmod(path, mode): failed_unlinks[0].unlink() -@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") -@pytest.mark.parametrize("leaf_budget", [1, 16]) -def test_atomic_write_near_native_path_limit(root, monkeypatch, leaf_budget): +def _near_limit_parent(root, leaf_budget): parent = root.resolve() path_max = os.pathconf(parent, "PC_PATH_MAX") name_max = os.pathconf(parent, "PC_NAME_MAX") @@ -3512,37 +3510,179 @@ def test_atomic_write_near_native_path_limit(root, monkeypatch, leaf_budget): component_size -= 1 parent /= "x" * component_size parent.mkdir() + return parent + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +@pytest.mark.parametrize("leaf_budget", [1, 16]) +def test_atomic_write_near_native_path_limit(root, monkeypatch, leaf_budget): + parent = _near_limit_parent(root, leaf_budget) destination = parent / "f" + path_max = os.pathconf(parent, "PC_PATH_MAX") assert len(os.fsencode(destination)) == path_max - leaf_budget destination.write_bytes(b"probe") destination.unlink() monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: "2" * 16) + previous = os.umask(0o700) + try: + with FileHelper(root) as files: + for content in (b"first", b"second"): + files.write_bytes(destination, content, mode=0o640) + assert destination.read_bytes() == content + assert stat.S_IMODE(destination.stat().st_mode) == 0o640 + assert list(parent.iterdir()) == [destination] + finally: + os.umask(previous) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +def test_atomic_near_limit_writes_do_not_move_each_others_payload(root, monkeypatch): + parent = _near_limit_parent(root, 1) + first, second = parent / "a", parent / "2" + fdopen = os.fdopen + interleaved = False + + def interleave(fd, *args, **kwargs): + nonlocal interleaved + if not interleaved: + interleaved = True + with FileHelper(root) as other: + other.write_bytes(second, b"second") + return fdopen(fd, *args, **kwargs) + + monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: ("3" if interleaved else "2") * 16) + monkeypatch.setattr(os, "fdopen", interleave) with FileHelper(root) as files: - for content in (b"first", b"second"): - files.write_bytes(destination, content) - assert destination.read_bytes() == content - assert list(parent.iterdir()) == [destination] + files.write_bytes(first, b"first") + assert first.read_bytes() == b"first" + assert second.read_bytes() == b"second" + assert set(parent.iterdir()) == {first, second} + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +def test_atomic_near_limit_write_ignores_occupied_short_names(root, monkeypatch): + parent = _near_limit_parent(root, 1) + occupied = {parent / name for name in "0123456789abcdef"} + for path in occupied: + path.write_bytes(b"keep") + target = parent / "x" + monkeypatch.setattr(file_helper.secrets, "token_hex", lambda _: "2" * 16) + with FileHelper(root) as files: + files.write_bytes(target, b"new") + assert all(path.read_bytes() == b"keep" for path in occupied) + assert target.read_bytes() == b"new" + assert set(parent.iterdir()) == occupied | {target} + + +def test_atomic_windows_failed_cleanup_restores_readonly_stage(root, monkeypatch): + destination = root / "file" + error = PermissionError(errno.EACCES, "retry unlink denied") + stages = [] + + def replace_fails(source, target): + raise OSError("replacement failed") + + def unlink_fails(path, *, missing_ok=False): + stages.append(path) + if len(stages) == 1: + assert not path.stat().st_mode & stat.S_IWRITE + raise PermissionError(errno.EACCES, "read-only") + assert path.stat().st_mode & stat.S_IWRITE + raise error + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "replace": replace_fails})) + model.setattr(Path, "unlink", unlink_fails) + with pytest.raises(PermissionError) as exc: + files.write_bytes(destination, b"new", mode=0o400) + assert exc.value is error + assert len(stages) == 2 and stages[0] == stages[1] + try: + assert not stages[0].stat().st_mode & stat.S_IWRITE + assert stages[0].read_bytes() == b"new" + assert not destination.exists() + finally: + stages[0].chmod(0o600) + stages[0].unlink() -def test_atomic_write_retries_windows_enoent_with_short_name(root, monkeypatch): +def test_atomic_write_retries_windows_enoent_in_staging_directory(root, monkeypatch): destination = root / "file" + parent = root.resolve() attempted = [] def open_with_limit(path, flags, mode): attempted.append(path) - if len(path.name) > len(destination.name): + if path.parent == parent: raise FileNotFoundError(errno.ENOENT, "modeled Windows CRT path limit") return os.open(path, flags, mode) with FileHelper(root) as files, monkeypatch.context() as model: model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": open_with_limit})) - model.setattr(file_helper.secrets, "token_hex", lambda _: "2" * 16) + model.setattr(file_helper, "_windows_extended_path", lambda path: path) files.write_bytes(destination, b"new") assert len(attempted) == 2 + assert attempted[1].parent.parent == parent assert destination.read_bytes() == b"new" assert list(root.iterdir()) == [destination] +@pytest.mark.parametrize(("name", "code"), [ + ("file", errno.EACCES), + ("x" * 22, errno.ENAMETOOLONG), + ("missing/file", errno.ENOENT), +]) +def test_atomic_staging_nonretryable_error_is_preserved(root, monkeypatch, name, code): + destination = root / name + error = OSError(code, "staging denied") + attempts = [] + keep = root / "keep" + keep.write_bytes(b"old") + + def reject(path, flags, mode): + attempts.append(path) + raise error + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": reject})) + with pytest.raises(OSError) as exc: + files.write_bytes(destination, b"new") + assert exc.value is error + assert len(attempts) == 1 + assert not destination.exists() + assert list(root.iterdir()) == [keep] + assert keep.read_bytes() == b"old" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +@pytest.mark.parametrize("fail_at", ["open", "replace"]) +def test_atomic_near_limit_staging_failure_cleans_directory(root, monkeypatch, fail_at): + parent = _near_limit_parent(root, 1) + destination = parent / "f" + destination.write_bytes(b"old") + error = OSError(errno.ENAMETOOLONG if fail_at == "open" else errno.EACCES, "staging failed") + + def observe_open(path, flags, *args, **kwargs): + if fail_at == "open" and path == Path("payload"): + raise error + return os.open(path, flags, *args, **kwargs) + + def observe_replace(source, target, *, src_dir_fd): + assert fail_at == "replace" + assert stat.S_ISREG(os.stat(source, dir_fd=src_dir_fd).st_mode) + raise error + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{ + **vars(os), "open": observe_open, "replace": observe_replace, + })) + with pytest.raises(OSError) as exc: + files.write_bytes(destination, b"new") + assert exc.value is error + assert destination.read_bytes() == b"old" + assert list(parent.iterdir()) == [destination] + + @pytest.mark.skipif(os.name == "nt", reason="Windows path length depends on host configuration") def test_atomic_write_creates_and_replaces_long_component(root, monkeypatch): destination = root / ("x" * 252 + ".sh") From 900b6ad90217950722825aae72f66f8cfad61473 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 09:57:02 -0600 Subject: [PATCH 4/9] fix: preserve inherited permissions in atomic staging Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 2 + src/specify_cli/file_helper.py | 42 +++++++--- tests/test_file_helper.py | 140 +++++++++++++++++++++++++++++++++ 3 files changed, 172 insertions(+), 12 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index f910ccde60..3bb2ad0eed 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -279,6 +279,8 @@ descriptor-relative or change their documented concurrency limitations. directory under the destination's parent instead of using a short file name that could also be another write's destination. This uses directory-relative operations where supported on POSIX and an extended staging path on Windows. + The staging directory preserves inherited setgid on POSIX and inherits + the destination parent's access control on Windows. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 64e80bbd77..29d853e3ef 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -646,11 +646,10 @@ def _open_atomic_stage( if os.name == "nt": if not destination.parent.is_dir(): raise - directory = Path(tempfile.mkdtemp(dir=_windows_extended_path(destination.parent))) - staging.enter_context(self._remove_atomic_directory(directory)) - stage = directory / "payload" - return os.open(stage, flags, mode), stage, None - if not {os.mkdir, os.chmod, os.rename, os.rmdir, os.unlink} <= os.supports_dir_fd: + elif not ( + {os.mkdir, os.rename, os.rmdir, os.stat, os.unlink} <= os.supports_dir_fd + and os.stat in os.supports_follow_symlinks + ): raise break else: @@ -658,22 +657,41 @@ def _open_atomic_stage( # Keep the payload out of the destination's namespace, without # spending the remaining absolute path budget on the staging name. - parent = staging.enter_context(self._posix_directory( + parent = None if os.name == "nt" else staging.enter_context(self._posix_directory( destination.parent, unsupported_message="Directory-relative staging is unsupported", )) for _ in range(10): - name = f".{secrets.token_hex(8)}.tmp" + name = f".s{secrets.token_hex(6)}" + if name == destination.name.rstrip(" .").casefold(): + continue + directory = _windows_extended_path(destination.parent) / name if parent is None else Path(name) try: - os.mkdir(name, 0o700, dir_fd=parent) + if parent is None: + # The payload should inherit the destination parent's ACL. + directory.mkdir() + else: + os.mkdir(directory.name, 0o700, dir_fd=parent) except FileExistsError: continue - staging.enter_context(self._remove_atomic_directory(Path(name), parent)) + staging.enter_context(self._remove_atomic_directory(directory, parent)) break else: raise FileExistsError(errno.EEXIST, "Could not allocate a staging directory", str(destination)) - # A restrictive umask must not make the private staging directory unusable. - os.chmod(name, 0o700, dir_fd=parent, follow_symlinks=False) - directory_fd = os.open(name, self._directory_flags(), dir_fd=parent) + if parent is None: + stage = directory / "payload" + return os.open(stage, flags, mode), stage, None + directory_mode = os.stat(name, dir_fd=parent, follow_symlinks=False).st_mode + if not stat.S_ISDIR(directory_mode): + raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), name) + if directory_mode & 0o700 != 0o700: + # Restore owner access masked by umask without clearing inherited setgid. + if os.chmod not in os.supports_dir_fd: + raise OSError(errno.ENOTSUP, "Directory-relative staging chmod is unsupported", name) + try: + os.chmod(name, stat.S_IMODE(directory_mode) | 0o700, dir_fd=parent, follow_symlinks=False) + except (NotImplementedError, ValueError) as exc: + raise OSError(errno.ENOTSUP, "Directory-relative staging chmod is unsupported", name) from exc + directory_fd = os.open(directory, self._directory_flags(), dir_fd=parent) staging.callback(os.close, directory_fd) stage = Path("payload") return os.open(stage, flags, mode, dir_fd=directory_fd), stage, directory_fd diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index c613e82697..c9cc31cb79 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3627,6 +3627,57 @@ def open_with_limit(path, flags, mode): assert list(root.iterdir()) == [destination] +@pytest.mark.parametrize(("source", "expected"), [ + (r"C:\project\dir", r"\\?\C:\project\dir"), + (r"\\server\share\dir", r"\\?\UNC\server\share\dir"), + (r"\\?\C:\project\dir", r"\\?\C:\project\dir"), + (r"\\?\UNC\server\share\dir", r"\\?\UNC\server\share\dir"), +]) +def test_windows_extended_atomic_path(source, expected): + assert str(file_helper._windows_extended_path(PureWindowsPath(source))) == expected + + +@pytest.mark.skipif(os.name != "nt", reason="Native Windows staging and ACLs required") +def test_atomic_windows_extended_staging_inherits_parent_acl(root, monkeypatch): + parent = root.resolve() + destination = parent / "file" + acl = parent.parent / "acl.txt" + run = subprocess.run + run(["icacls", str(parent), "/grant", "*S-1-5-11:(OI)(CI)(RX)"], check=True, capture_output=True) + real_open = os.open + real_replace = os.replace + stages = [] + + def open_stage(path, flags, mode): + if path.parent == parent: + raise FileNotFoundError(errno.ENOENT, "forced CRT length error") + assert str(path).startswith("\\\\?\\") + stages.append(path) + return real_open(path, flags, mode) + + def fail(source, target): + assert source == stages[-1] and target == destination + raise PermissionError(errno.EACCES, "replacement denied") + + with FileHelper(root) as files, monkeypatch.context() as model: + windows_os = SimpleNamespace(**{**vars(os), "open": open_stage}) + model.setattr(file_helper, "os", windows_os) + files.write_bytes(destination, b"first") + assert destination.read_bytes() == b"first" + files.write_bytes(destination, b"second") + assert destination.read_bytes() == b"second" + model.setattr(windows_os, "replace", fail) + with pytest.raises(PermissionError, match="replacement denied"): + files.write_bytes(destination, b"rejected", mode=0o400) + model.setattr(windows_os, "replace", real_replace) + assert len(stages) == 3 + assert list(parent.iterdir()) == [destination] + assert destination.read_bytes() == b"second" + run(["icacls", str(destination), "/save", str(acl)], check=True, capture_output=True) + sddl = acl.read_text(encoding="utf-16-le") + assert ";;;AU)" in sddl or ";;;S-1-5-11)" in sddl + + @pytest.mark.parametrize(("name", "code"), [ ("file", errno.EACCES), ("x" * 22, errno.ENAMETOOLONG), @@ -3654,6 +3705,95 @@ def reject(path, flags, mode): assert keep.read_bytes() == b"old" +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative staging required") +def test_atomic_staging_respects_posix_minimum_name_max(root, monkeypatch): + destination = root / (".s" + "2" * 12) + tokens = iter(["1" * 16, "2" * 12, "3" * 12]) + real_open = os.open + real_mkdir = os.mkdir + + def check(path): + if len(os.fsencode(Path(path).name)) > 14: + raise OSError(errno.ENAMETOOLONG, "modeled NAME_MAX") + + def open_checked(path, flags, *args, **kwargs): + check(path) + return real_open(path, flags, *args, **kwargs) + + def mkdir_checked(path, mode, *, dir_fd): + check(path) + assert path != destination.name + return real_mkdir(path, mode, dir_fd=dir_fd) + + with FileHelper(root) as files, monkeypatch.context() as model: + # FileHelper's resolved root name also has to fit the modeled limit. + model.setattr(file_helper, "os", SimpleNamespace(**{ + **vars(os), "open": open_checked, "mkdir": mkdir_checked, + "supports_dir_fd": os.supports_dir_fd | {mkdir_checked}, + })) + model.setattr(file_helper.secrets, "token_hex", lambda _: next(tokens)) + files.write_bytes(destination, b"new") + assert destination.read_bytes() == b"new" + assert list(root.iterdir()) == [destination] + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative staging required") +@pytest.mark.parametrize(("capability", "code"), [ + ("supports_dir_fd", errno.ENAMETOOLONG), + ("O_NOFOLLOW", errno.ENOTSUP), + ("O_DIRECTORY", errno.ENOTSUP), +]) +def test_atomic_near_limit_missing_capability_preserves_destination(root, monkeypatch, capability, code): + parent = _near_limit_parent(root, 1) + destination = parent / "f" + destination.write_bytes(b"old") + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{ + **vars(os), capability: set() if capability == "supports_dir_fd" else 0, + })) + with pytest.raises(OSError) as exc: + files.write_bytes(destination, b"new") + assert exc.value.errno == code + assert destination.read_bytes() == b"old" + assert list(parent.iterdir()) == [destination] + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX directory modes required") +@pytest.mark.parametrize(("mask", "chmod_supported"), [(0o077, False), (0o700, True), (0o700, False)]) +def test_atomic_near_limit_preserves_inherited_setgid(root, monkeypatch, mask, chmod_supported): + parent = _near_limit_parent(root, 1) + destination = parent / "f" + real_mkdir, real_chmod = os.mkdir, os.chmod + changed = [] + + def mkdir_with_setgid(path, mode, *, dir_fd): + real_mkdir(path, mode, dir_fd=dir_fd) + # Model inheritance on filesystems that do not inherit setgid by default. + real_chmod(path, (mode & ~mask) | stat.S_ISGID, dir_fd=dir_fd) + + def chmod_stage(path, mode, **kwargs): + changed.append(mode) + real_chmod(path, mode, **kwargs) + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{ + **vars(os), "mkdir": mkdir_with_setgid, "chmod": chmod_stage, + "supports_dir_fd": os.supports_dir_fd | {mkdir_with_setgid} | ( + {chmod_stage} if chmod_supported else set() + ), + })) + if mask == 0o700 and not chmod_supported: + with pytest.raises(OSError) as exc: + files.write_bytes(destination, b"new") + assert exc.value.errno == errno.ENOTSUP + assert not list(parent.iterdir()) + else: + files.write_bytes(destination, b"new") + assert destination.read_bytes() == b"new" + assert list(parent.iterdir()) == [destination] + assert changed == ([0o2700] if mask == 0o700 and chmod_supported else []) + + @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") @pytest.mark.parametrize("fail_at", ["open", "replace"]) def test_atomic_near_limit_staging_failure_cleans_directory(root, monkeypatch, fail_at): From 53aa6c1d1974b8661ae51c5b28f06a0699126e11 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:19:22 -0600 Subject: [PATCH 5/9] fix: preserve direct Windows ACL inheritance during atomic staging Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 11 +++--- src/specify_cli/file_helper.py | 35 ++++++++----------- tests/test_file_helper.py | 61 ++++++++++++++++++++++++++++++---- 3 files changed, 72 insertions(+), 35 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 3bb2ad0eed..7924d8f3bd 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -275,12 +275,11 @@ descriptor-relative or change their documented concurrency limitations. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. A short, exclusively created sibling stages the write. - If the staging path exceeds a path limit, stage inside a separate temporary - directory under the destination's parent instead of using a short file name - that could also be another write's destination. This uses directory-relative - operations where supported on POSIX and an extended staging path on Windows. - The staging directory preserves inherited setgid on POSIX and inherits - the destination parent's access control on Windows. + If the staging path exceeds a path limit, POSIX uses directory-relative + operations where supported to stage inside a separate temporary directory + that preserves inherited setgid. Windows retries the same kind of sibling + file with an extended path, retaining direct inheritance of the destination + parent's access control without requiring subdirectory creation rights. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 29d853e3ef..cb013101dd 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -627,11 +627,12 @@ def _open_atomic_stage( self, destination: Path, flags: int, mode: int, staging: ExitStack, ) -> tuple[int, Path, int | None]: mode &= 0o600 + extended_parent = None for _ in range(10): name = f".{secrets.token_hex(8)}.tmp" if name == destination.name.rstrip(" .").casefold(): continue - stage = destination.with_name(name) + stage = (extended_parent or destination.parent) / name try: return os.open(stage, flags, mode), stage, None except FileExistsError: @@ -644,9 +645,12 @@ def _open_atomic_stage( if not length_error or len(name) <= len(destination.name): raise if os.name == "nt": - if not destination.parent.is_dir(): + if extended_parent is not None or not destination.parent.is_dir(): raise - elif not ( + # Keep file-only ACL inheritance and avoid requiring directory creation rights. + extended_parent = _windows_extended_path(destination.parent) + continue + if not ( {os.mkdir, os.rename, os.rmdir, os.stat, os.unlink} <= os.supports_dir_fd and os.stat in os.supports_follow_symlinks ): @@ -657,29 +661,22 @@ def _open_atomic_stage( # Keep the payload out of the destination's namespace, without # spending the remaining absolute path budget on the staging name. - parent = None if os.name == "nt" else staging.enter_context(self._posix_directory( + parent = staging.enter_context(self._posix_directory( destination.parent, unsupported_message="Directory-relative staging is unsupported", )) for _ in range(10): name = f".s{secrets.token_hex(6)}" if name == destination.name.rstrip(" .").casefold(): continue - directory = _windows_extended_path(destination.parent) / name if parent is None else Path(name) + directory = Path(name) try: - if parent is None: - # The payload should inherit the destination parent's ACL. - directory.mkdir() - else: - os.mkdir(directory.name, 0o700, dir_fd=parent) + os.mkdir(directory.name, 0o700, dir_fd=parent) except FileExistsError: continue staging.enter_context(self._remove_atomic_directory(directory, parent)) break else: raise FileExistsError(errno.EEXIST, "Could not allocate a staging directory", str(destination)) - if parent is None: - stage = directory / "payload" - return os.open(stage, flags, mode), stage, None directory_mode = os.stat(name, dir_fd=parent, follow_symlinks=False).st_mode if not stat.S_ISDIR(directory_mode): raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), name) @@ -698,23 +695,17 @@ def _open_atomic_stage( @staticmethod @contextmanager - def _remove_atomic_directory(directory: Path, parent: int | None = None) -> Iterator[None]: - def remove() -> None: - if parent is None: - directory.rmdir() - else: - os.rmdir(directory, dir_fd=parent) - + def _remove_atomic_directory(directory: Path, parent: int) -> Iterator[None]: try: yield except BaseException as exc: try: - remove() + os.rmdir(directory, dir_fd=parent) except OSError as cleanup_error: exc.add_note(f"Could not remove atomic staging directory: {cleanup_error}") raise else: - remove() + os.rmdir(directory, dir_fd=parent) @staticmethod def _unlink_atomic_stage(stage: Path, parent: int | None) -> None: diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index c9cc31cb79..dd5caa6999 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3606,23 +3606,28 @@ def unlink_fails(path, *, missing_ok=False): stages[0].unlink() -def test_atomic_write_retries_windows_enoent_in_staging_directory(root, monkeypatch): +def test_atomic_windows_length_retry_uses_only_file_creation(root, monkeypatch): destination = root / "file" parent = root.resolve() attempted = [] def open_with_limit(path, flags, mode): attempted.append(path) - if path.parent == parent: + if len(attempted) == 1: raise FileNotFoundError(errno.ENOENT, "modeled Windows CRT path limit") + assert path.parent == parent + assert flags & os.O_EXCL return os.open(path, flags, mode) + def deny_mkdir(*args, **kwargs): + raise PermissionError(errno.EACCES, "parent allows only file creation") + with FileHelper(root) as files, monkeypatch.context() as model: model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": open_with_limit})) + model.setattr(Path, "mkdir", deny_mkdir) model.setattr(file_helper, "_windows_extended_path", lambda path: path) files.write_bytes(destination, b"new") assert len(attempted) == 2 - assert attempted[1].parent.parent == parent assert destination.read_bytes() == b"new" assert list(root.iterdir()) == [destination] @@ -3643,15 +3648,23 @@ def test_atomic_windows_extended_staging_inherits_parent_acl(root, monkeypatch): destination = parent / "file" acl = parent.parent / "acl.txt" run = subprocess.run - run(["icacls", str(parent), "/grant", "*S-1-5-11:(OI)(CI)(RX)"], check=True, capture_output=True) + # File-only, non-propagating deny for a principal outside the runner's token. + run(["icacls", str(parent), "/deny", "*S-1-5-32-546:(OI)(IO)(NP)(RD)"], check=True, capture_output=True) + user = run(["whoami"], check=True, capture_output=True, text=True).stdout.strip() + run(["icacls", str(parent), "/deny", f"{user}:(AD)"], check=True, capture_output=True) + with pytest.raises(PermissionError): + (parent / "blocked-directory").mkdir() + probe = parent / "allowed-file" + probe.write_bytes(b"probe") + probe.unlink() real_open = os.open real_replace = os.replace stages = [] def open_stage(path, flags, mode): - if path.parent == parent: + if not str(path).startswith("\\\\?\\"): raise FileNotFoundError(errno.ENOENT, "forced CRT length error") - assert str(path).startswith("\\\\?\\") + assert path.parent == file_helper._windows_extended_path(parent) stages.append(path) return real_open(path, flags, mode) @@ -3675,7 +3688,11 @@ def fail(source, target): assert destination.read_bytes() == b"second" run(["icacls", str(destination), "/save", str(acl)], check=True, capture_output=True) sddl = acl.read_text(encoding="utf-16-le") - assert ";;;AU)" in sddl or ";;;S-1-5-11)" in sddl + aces = (part.split(")", 1)[0] for part in sddl.split("(")[1:]) + assert any( + ace.startswith("D;") and ace.endswith((";;;BG", ";;;S-1-5-32-546")) + for ace in aces + ) @pytest.mark.parametrize(("name", "code"), [ @@ -3699,12 +3716,37 @@ def reject(path, flags, mode): with pytest.raises(OSError) as exc: files.write_bytes(destination, b"new") assert exc.value is error + assert exc.value.errno == code assert len(attempts) == 1 assert not destination.exists() assert list(root.iterdir()) == [keep] assert keep.read_bytes() == b"old" +@pytest.mark.parametrize("code", [errno.ENAMETOOLONG, errno.ENOENT]) +def test_atomic_windows_failed_length_retry_is_preserved(root, monkeypatch, code): + destination = root / "file" + destination.write_bytes(b"old") + initial = OSError(errno.ENAMETOOLONG, "regular path exceeds limit") + error = OSError(code, "extended path still exceeds limit") + attempts = [] + + def reject(path, flags, mode): + attempts.append(path) + raise initial if len(attempts) == 1 else error + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": reject})) + model.setattr(file_helper, "_windows_extended_path", lambda path: path) + with pytest.raises(OSError) as exc: + files.write_bytes(destination, b"new") + assert exc.value is error + assert exc.value.errno == code + assert len(attempts) == 2 + assert destination.read_bytes() == b"old" + assert list(root.iterdir()) == [destination] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative staging required") def test_atomic_staging_respects_posix_minimum_name_max(root, monkeypatch): destination = root / (".s" + "2" * 12) @@ -3801,8 +3843,11 @@ def test_atomic_near_limit_staging_failure_cleans_directory(root, monkeypatch, f destination = parent / "f" destination.write_bytes(b"old") error = OSError(errno.ENAMETOOLONG if fail_at == "open" else errno.EACCES, "staging failed") + stage_attempts = [] def observe_open(path, flags, *args, **kwargs): + if flags & os.O_CREAT: + stage_attempts.append(path) if fail_at == "open" and path == Path("payload"): raise error return os.open(path, flags, *args, **kwargs) @@ -3819,6 +3864,8 @@ def observe_replace(source, target, *, src_dir_fd): with pytest.raises(OSError) as exc: files.write_bytes(destination, b"new") assert exc.value is error + assert exc.value.errno == error.errno + assert len(stage_attempts) == 2 and stage_attempts[-1] == Path("payload") assert destination.read_bytes() == b"old" assert list(parent.iterdir()) == [destination] From ece88e862519222ade1ab1bcc27bbaa2c601e432 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:41:28 -0600 Subject: [PATCH 6/9] fix: preserve direct POSIX inheritance during atomic staging Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 9 ++-- src/specify_cli/file_helper.py | 49 +++---------------- tests/test_file_helper.py | 88 +++++++++++++++++----------------- 3 files changed, 55 insertions(+), 91 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index 7924d8f3bd..f0461c7cc3 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -275,11 +275,10 @@ descriptor-relative or change their documented concurrency limitations. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. A short, exclusively created sibling stages the write. - If the staging path exceeds a path limit, POSIX uses directory-relative - operations where supported to stage inside a separate temporary directory - that preserves inherited setgid. Windows retries the same kind of sibling - file with an extended path, retaining direct inheritance of the destination - parent's access control without requiring subdirectory creation rights. + If the staging path exceeds a path limit, POSIX retries with a random sibling + opened relative to the parent directory where supported. Windows retries + with an extended path. Both keep the stage directly in the destination + directory for normal inheritance and do not require subdirectory creation. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index cb013101dd..9d5d05bf19 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -650,62 +650,27 @@ def _open_atomic_stage( # Keep file-only ACL inheritance and avoid requiring directory creation rights. extended_parent = _windows_extended_path(destination.parent) continue - if not ( - {os.mkdir, os.rename, os.rmdir, os.stat, os.unlink} <= os.supports_dir_fd - and os.stat in os.supports_follow_symlinks - ): + if not {os.rename, os.unlink} <= os.supports_dir_fd: raise break else: raise FileExistsError(errno.EEXIST, "Could not allocate a staging file", str(destination)) - # Keep the payload out of the destination's namespace, without - # spending the remaining absolute path budget on the staging name. + # A parent-relative sibling keeps direct inheritance and avoids the + # absolute path limit without shrinking the name to the leaf budget. parent = staging.enter_context(self._posix_directory( destination.parent, unsupported_message="Directory-relative staging is unsupported", )) for _ in range(10): - name = f".s{secrets.token_hex(6)}" + name = "." + secrets.token_hex(7)[:13] # POSIX minimum NAME_MAX is 14. if name == destination.name.rstrip(" .").casefold(): continue - directory = Path(name) + stage = Path(name) try: - os.mkdir(directory.name, 0o700, dir_fd=parent) + return os.open(stage, flags, mode, dir_fd=parent), stage, parent except FileExistsError: continue - staging.enter_context(self._remove_atomic_directory(directory, parent)) - break - else: - raise FileExistsError(errno.EEXIST, "Could not allocate a staging directory", str(destination)) - directory_mode = os.stat(name, dir_fd=parent, follow_symlinks=False).st_mode - if not stat.S_ISDIR(directory_mode): - raise NotADirectoryError(errno.ENOTDIR, os.strerror(errno.ENOTDIR), name) - if directory_mode & 0o700 != 0o700: - # Restore owner access masked by umask without clearing inherited setgid. - if os.chmod not in os.supports_dir_fd: - raise OSError(errno.ENOTSUP, "Directory-relative staging chmod is unsupported", name) - try: - os.chmod(name, stat.S_IMODE(directory_mode) | 0o700, dir_fd=parent, follow_symlinks=False) - except (NotImplementedError, ValueError) as exc: - raise OSError(errno.ENOTSUP, "Directory-relative staging chmod is unsupported", name) from exc - directory_fd = os.open(directory, self._directory_flags(), dir_fd=parent) - staging.callback(os.close, directory_fd) - stage = Path("payload") - return os.open(stage, flags, mode, dir_fd=directory_fd), stage, directory_fd - - @staticmethod - @contextmanager - def _remove_atomic_directory(directory: Path, parent: int) -> Iterator[None]: - try: - yield - except BaseException as exc: - try: - os.rmdir(directory, dir_fd=parent) - except OSError as cleanup_error: - exc.add_note(f"Could not remove atomic staging directory: {cleanup_error}") - raise - else: - os.rmdir(directory, dir_fd=parent) + raise FileExistsError(errno.EEXIST, "Could not allocate a staging file", str(destination)) @staticmethod def _unlink_atomic_stage(stage: Path, parent: int | None) -> None: diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index dd5caa6999..9b1469b343 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3749,10 +3749,9 @@ def reject(path, flags, mode): @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative staging required") def test_atomic_staging_respects_posix_minimum_name_max(root, monkeypatch): - destination = root / (".s" + "2" * 12) - tokens = iter(["1" * 16, "2" * 12, "3" * 12]) + destination = root / ("." + "2" * 13) + tokens = iter(["1" * 16, "2" * 16, "3" * 16]) real_open = os.open - real_mkdir = os.mkdir def check(path): if len(os.fsencode(Path(path).name)) > 14: @@ -3760,18 +3759,20 @@ def check(path): def open_checked(path, flags, *args, **kwargs): check(path) + if flags & os.O_CREAT and kwargs.get("dir_fd") is not None: + assert os.path.samestat(os.fstat(kwargs["dir_fd"]), root.stat()) + assert Path(path).name != destination.name + assert flags & os.O_EXCL return real_open(path, flags, *args, **kwargs) - def mkdir_checked(path, mode, *, dir_fd): - check(path) - assert path != destination.name - return real_mkdir(path, mode, dir_fd=dir_fd) + def forbid_mkdir(*args, **kwargs): + raise PermissionError(errno.EACCES, "parent allows only file creation") with FileHelper(root) as files, monkeypatch.context() as model: # FileHelper's resolved root name also has to fit the modeled limit. model.setattr(file_helper, "os", SimpleNamespace(**{ - **vars(os), "open": open_checked, "mkdir": mkdir_checked, - "supports_dir_fd": os.supports_dir_fd | {mkdir_checked}, + **vars(os), "open": open_checked, "mkdir": forbid_mkdir, + "supports_dir_fd": os.supports_dir_fd | {forbid_mkdir}, })) model.setattr(file_helper.secrets, "token_hex", lambda _: next(tokens)) files.write_bytes(destination, b"new") @@ -3779,6 +3780,22 @@ def mkdir_checked(path, mode, *, dir_fd): assert list(root.iterdir()) == [destination] +@pytest.mark.skipif(sys.platform != "darwin", reason="Native macOS ACL inheritance required") +def test_atomic_near_limit_inherits_file_only_parent_acl(root): + parent = _near_limit_parent(root, 1) + destination = parent / "f" + marker = "group:everyone deny writeextattr,file_inherit,limit_inherit,only_inherit" + subprocess.run(["/bin/chmod", "+a", marker, str(parent)], check=True, capture_output=True) + with FileHelper(root) as files: + files.write_bytes(destination, b"new") + acl = subprocess.run( + ["/bin/ls", "-led", str(destination)], check=True, capture_output=True, text=True, + ).stdout + assert "group:everyone inherited deny writeextattr" in acl + assert destination.read_bytes() == b"new" + assert list(parent.iterdir()) == [destination] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX descriptor-relative staging required") @pytest.mark.parametrize(("capability", "code"), [ ("supports_dir_fd", errno.ENAMETOOLONG), @@ -3801,44 +3818,26 @@ def test_atomic_near_limit_missing_capability_preserves_destination(root, monkey @pytest.mark.skipif(os.name == "nt", reason="POSIX directory modes required") -@pytest.mark.parametrize(("mask", "chmod_supported"), [(0o077, False), (0o700, True), (0o700, False)]) -def test_atomic_near_limit_preserves_inherited_setgid(root, monkeypatch, mask, chmod_supported): +@pytest.mark.parametrize("mask", [0o077, 0o700, 0o777]) +def test_atomic_near_limit_inherits_parent_group_and_applies_mode(root, mask): parent = _near_limit_parent(root, 1) destination = parent / "f" - real_mkdir, real_chmod = os.mkdir, os.chmod - changed = [] - - def mkdir_with_setgid(path, mode, *, dir_fd): - real_mkdir(path, mode, dir_fd=dir_fd) - # Model inheritance on filesystems that do not inherit setgid by default. - real_chmod(path, (mode & ~mask) | stat.S_ISGID, dir_fd=dir_fd) - - def chmod_stage(path, mode, **kwargs): - changed.append(mode) - real_chmod(path, mode, **kwargs) - - with FileHelper(root) as files, monkeypatch.context() as model: - model.setattr(file_helper, "os", SimpleNamespace(**{ - **vars(os), "mkdir": mkdir_with_setgid, "chmod": chmod_stage, - "supports_dir_fd": os.supports_dir_fd | {mkdir_with_setgid} | ( - {chmod_stage} if chmod_supported else set() - ), - })) - if mask == 0o700 and not chmod_supported: - with pytest.raises(OSError) as exc: - files.write_bytes(destination, b"new") - assert exc.value.errno == errno.ENOTSUP - assert not list(parent.iterdir()) - else: - files.write_bytes(destination, b"new") - assert destination.read_bytes() == b"new" - assert list(parent.iterdir()) == [destination] - assert changed == ([0o2700] if mask == 0o700 and chmod_supported else []) + parent.chmod(0o2700) + previous = os.umask(mask) + try: + with FileHelper(root) as files: + files.write_bytes(destination, b"new", mode=0o640) + finally: + os.umask(previous) + assert destination.stat().st_gid == parent.stat().st_gid + assert stat.S_IMODE(destination.stat().st_mode) == 0o640 + assert destination.read_bytes() == b"new" + assert list(parent.iterdir()) == [destination] @pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") @pytest.mark.parametrize("fail_at", ["open", "replace"]) -def test_atomic_near_limit_staging_failure_cleans_directory(root, monkeypatch, fail_at): +def test_atomic_near_limit_staging_failure_cleans_sibling(root, monkeypatch, fail_at): parent = _near_limit_parent(root, 1) destination = parent / "f" destination.write_bytes(b"old") @@ -3848,8 +3847,8 @@ def test_atomic_near_limit_staging_failure_cleans_directory(root, monkeypatch, f def observe_open(path, flags, *args, **kwargs): if flags & os.O_CREAT: stage_attempts.append(path) - if fail_at == "open" and path == Path("payload"): - raise error + if fail_at == "open" and kwargs.get("dir_fd") is not None: + raise error return os.open(path, flags, *args, **kwargs) def observe_replace(source, target, *, src_dir_fd): @@ -3865,7 +3864,8 @@ def observe_replace(source, target, *, src_dir_fd): files.write_bytes(destination, b"new") assert exc.value is error assert exc.value.errno == error.errno - assert len(stage_attempts) == 2 and stage_attempts[-1] == Path("payload") + assert len(stage_attempts) == 2 + assert not stage_attempts[-1].is_absolute() assert destination.read_bytes() == b"old" assert list(parent.iterdir()) == [destination] From 5ea8e409138064a3dd8f2101bde4306f0ef465a3 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:12:23 -0600 Subject: [PATCH 7/9] test: cover POSIX atomic stage collision retries Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 9b1469b343..2a8dc00338 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3574,6 +3574,37 @@ def test_atomic_near_limit_write_ignores_occupied_short_names(root, monkeypatch) assert set(parent.iterdir()) == occupied | {target} +@pytest.mark.skipif(os.name == "nt", reason="POSIX PATH_MAX required") +@pytest.mark.parametrize("exhausted", [False, True]) +def test_atomic_near_limit_stage_collisions_preserve_existing_files(root, monkeypatch, exhausted): + parent = _near_limit_parent(root, 14) + occupied = parent / ("." + "a" * 13) + occupied.write_bytes(b"keep") + destination = parent / "f" + destination.write_bytes(b"old") + attempts = [] + + def token_hex(size): + attempts.append(size) + digit = "a" if exhausted or len(attempts) <= 2 else "b" + return digit * (size * 2) + + monkeypatch.setattr(file_helper.secrets, "token_hex", token_hex) + with FileHelper(root) as files: + if exhausted: + with pytest.raises(FileExistsError) as exc: + files.write_bytes(destination, b"new") + assert exc.value.errno == errno.EEXIST + assert destination.read_bytes() == b"old" + assert attempts == [8] + [7] * 10 + else: + files.write_bytes(destination, b"new") + assert destination.read_bytes() == b"new" + assert attempts == [8, 7, 7] + assert occupied.read_bytes() == b"keep" + assert set(parent.iterdir()) == {destination, occupied} + + def test_atomic_windows_failed_cleanup_restores_readonly_stage(root, monkeypatch): destination = root / "file" error = PermissionError(errno.EACCES, "retry unlink denied") From 1792bad9768e10002663dc712f2df09af15a131e Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 11:42:59 -0600 Subject: [PATCH 8/9] fix: verify the Windows atomic staging parent before retry Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/file-helper.md | 5 +-- src/specify_cli/file_helper.py | 6 ++++ tests/test_file_helper.py | 59 +++++++++++++++++++++++++++++++++- 3 files changed, 67 insertions(+), 3 deletions(-) diff --git a/design/file-helper.md b/design/file-helper.md index f0461c7cc3..58047983f7 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -277,8 +277,9 @@ descriptor-relative or change their documented concurrency limitations. `encoding="utf-8"`. A short, exclusively created sibling stages the write. If the staging path exceeds a path limit, POSIX retries with a random sibling opened relative to the parent directory where supported. Windows retries - with an extended path. Both keep the stage directly in the destination - directory for normal inheritance and do not require subdirectory creation. + with an extended path only if it identifies the validated parent. Both keep + the stage directly in the destination directory for normal inheritance and + do not require subdirectory creation. On POSIX, the initial mode is restricted to the requested owner read/write bits and filtered by the process umask. After writing, the supplied mode is applied with `chmod` using the platform's supported semantics. Metadata and diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 9d5d05bf19..d83c55d86d 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -647,8 +647,14 @@ def _open_atomic_stage( if os.name == "nt": if extended_parent is not None or not destination.parent.is_dir(): raise + parent_info = destination.parent.stat() # Keep file-only ACL inheritance and avoid requiring directory creation rights. extended_parent = _windows_extended_path(destination.parent) + # The extended spelling bypasses Win32 name normalization. + if not os.path.samestat(parent_info, extended_parent.stat()): + raise FileHelperError( + f"Extended staging path does not match destination parent: {destination.parent}" + ) continue if not {os.rename, os.unlink} <= os.supports_dir_fd: raise diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 2a8dc00338..ad9f937b7e 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3663,6 +3663,59 @@ def deny_mkdir(*args, **kwargs): assert list(root.iterdir()) == [destination] +def test_atomic_windows_length_retry_rejects_different_parent(root, monkeypatch): + destination = root / "file" + destination.write_bytes(b"old") + other_parent = root / "other" + other_parent.mkdir() + attempts = [] + + def open_stage(path, flags, mode): + attempts.append(path) + if len(attempts) == 1: + raise OSError(errno.ENAMETOOLONG, "modeled path limit") + return os.open(path, flags, mode) + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": open_stage})) + model.setattr(file_helper, "_windows_extended_path", lambda _: other_parent) + with pytest.raises(FileHelperError, match="does not match destination parent"): + files.write_bytes(destination, b"new") + assert len(attempts) == 1 + assert destination.read_bytes() == b"old" + assert set(root.iterdir()) == {destination, other_parent} + assert not list(other_parent.iterdir()) + + +def test_atomic_windows_length_retry_rechecks_destination_before_replace(root, link, monkeypatch): + destination = root / "file" + target = root / "target" + target.write_bytes(b"keep") + attempts = [] + chmod = Path.chmod + + def open_stage(path, flags, mode): + attempts.append(path) + if len(attempts) == 1: + raise OSError(errno.ENAMETOOLONG, "modeled path limit") + return os.open(path, flags, mode) + + def change_destination(path, mode): + chmod(path, mode) + link(destination, target) + + with FileHelper(root) as files, monkeypatch.context() as model: + model.setattr(file_helper, "os", SimpleNamespace(**{**vars(os), "name": "nt", "open": open_stage})) + model.setattr(file_helper, "_windows_extended_path", lambda path: path) + model.setattr(Path, "chmod", change_destination) + with pytest.raises(SymlinkDeniedError): + files.write_bytes(destination, b"new") + assert len(attempts) == 2 + assert destination.is_symlink() + assert target.read_bytes() == b"keep" + assert set(root.iterdir()) == {destination, target} + + @pytest.mark.parametrize(("source", "expected"), [ (r"C:\project\dir", r"\\?\C:\project\dir"), (r"\\server\share\dir", r"\\?\UNC\server\share\dir"), @@ -3703,8 +3756,12 @@ def fail(source, target): assert source == stages[-1] and target == destination raise PermissionError(errno.EACCES, "replacement denied") + def replace(source, target): + assert source == stages[-1] and str(target) == str(destination) + real_replace(source, target) + with FileHelper(root) as files, monkeypatch.context() as model: - windows_os = SimpleNamespace(**{**vars(os), "open": open_stage}) + windows_os = SimpleNamespace(**{**vars(os), "open": open_stage, "replace": replace}) model.setattr(file_helper, "os", windows_os) files.write_bytes(destination, b"first") assert destination.read_bytes() == b"first" From 4651758b5830b12457100281cc24d7b4386c297c Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:36:34 -0600 Subject: [PATCH 9/9] test: cover native Windows atomic writes at path limits Assisted-by: GitHub Copilot (model: GPT-6.2 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- tests/test_file_helper.py | 41 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index ad9f937b7e..06ade38b61 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -3986,6 +3986,47 @@ def observe(source, target): old_content = content +@pytest.mark.skipif(os.name != "nt", reason="Native Windows path handling required") +@pytest.mark.parametrize("case", ["long-component", "near-limit-parent"]) +def test_atomic_windows_create_and_replace_at_path_limits(root, case): + parent = root.resolve() + if case == "long-component": + name = "x" * 252 + ".sh" + else: + # Leave room to create the directory under legacy MAX_PATH, but not + # for the 21-character staging leaf (without long-path support). + units = len(str(parent).encode("utf-16-le")) // 2 + while units < 245: + size = min(64, 246 - units) + parent /= "d" * size + units += size + 1 + name = "f" + destination = parent / name + try: + parent.mkdir(parents=True, exist_ok=True) + # Native rename to the long path is part of the capability probe. + destination.touch() + probe = parent / "p" + probe.write_bytes(b"replacement probe") + os.replace(probe, destination) + except OSError as exc: + # The CRT may map a too-long path to ENOENT even with an existing parent. + crt_limit = ( + exc.errno == errno.ENOENT and exc.filename == str(destination) + and len(str(destination).encode("utf-16-le")) // 2 >= 260 and parent.is_dir() + ) + if crt_limit or exc.errno == errno.ENAMETOOLONG or getattr(exc, "winerror", None) == 206: + pytest.skip(f"Direct create/replace probe hit the host path limit: {exc}") + raise + destination.unlink() + + with FileHelper(root) as files: + for content in (b"first", b"second"): + files.write_bytes(destination, content) + assert destination.read_bytes() == content + assert list(parent.iterdir()) == [destination] + + @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits required") @pytest.mark.parametrize(("mode", "staging_mode"), [(0o400, 0o400), (0o755, 0o600)]) def test_atomic_write_staging_mode_and_exact_final_mode(root, monkeypatch, mode, staging_mode):