diff --git a/design/file-helper.md b/design/file-helper.md index b9fca560b7..de56c3342d 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -250,6 +250,25 @@ descriptor-relative or change their documented concurrency limitations. with cleanup details attached as a note. The yielded path uses the same spelling rule as `iterdir`; cleanup uses the resolved staging location. - `read_bytes(path)` / `read_text(path, encoding="utf-8")` read regular files. +- `stat(path)` returns the metadata of an existing entry after the normal policy + walk: allowed contained links, including a leaf link, are resolved, and the + resolved entry itself is not followed. The entry is queried relative to the + anchored parent hierarchy, so a parent swapped after resolution cannot + redirect it. The root itself is queried without following a link, so a root + replaced by a link after construction is not followed. Missing entries raise + `FileNotFoundError`. It is a + point-in-time query, not an anchor: callers that act on the result must + re-check identity on the descriptor they act through. +- `access(path, mode)` answers `os.access` for an existing entry found and + anchored as `stat` finds it; the policy walk refuses or resolves a leaf link. + POSIX checks relative to the anchored parent descriptor with a plain + `faccessat` (no `AT_SYMLINK_NOFOLLOW`, which libc emulates from mode bits + where `faccessat2` is missing); Windows pins the parent hierarchy first. It + uses the real user and group ids, so it also reports a read-only filesystem + or a file owned by someone else, which mode bits miss. It is advisory, like + `stat`. +- `canonical_root` is the root with OS and link aliases resolved, fixed on + construction; it is the base that resolved operation paths share. - `create_bytes(path, content, mode=0o644)` / `create_text(...)` exclusively create files with existing parents. A no-follow `lstat` preflight rejects existing leaves, including dangling links, before opening the destination. @@ -272,6 +291,44 @@ descriptor-relative or change their documented concurrency limitations. anchoring; they are not banned. Parents must already exist, and the supplied mode remains filtered by the process umask. Unsupported anchoring primitives fail explicitly rather than falling back to unanchored creation. +- `create_private_bytes(path, content)` exclusively creates a file only the + current user can open, with existing parents, and flushes it before + returning. It shares `create_bytes`'s policy walk, no-follow `lstat` + preflight and anchored parent hierarchy. POSIX creates the leaf with `0o600` + relative to the anchored parent. Before any content is written, it refuses + (removing the still-empty file, with `PermissionError`) when the file came + out with group or other mode bits, which means the filesystem ignored the + mode; when it is owned by a uid other than the caller's effective uid, which + means the filesystem mapped ownership (some network and container mounts); + or, on macOS, with inherited ACL allow entries, which a directory-relative + create cannot withhold (inherited deny entries are accepted). Linux default ACLs are + bounded by the mask the mode sets. NFSv4-style inherited ACLs on other + systems are not inspected. It writes and `fsync`s through that one + descriptor, adding `F_FULLFSYNC` on macOS where the filesystem supports it, + then flushes the parent best effort through a readable descriptor opened + from the anchor (search-only and `O_PATH` anchors reject `fsync`); a + parent that cannot be flushed does not fail the call. Windows creates the leaf + with `CREATE_NEW`, no sharing, `FILE_FLAG_OPEN_REPARSE_POINT`, and a security + descriptor naming the current user as owner with a protected DACL granting + only that user full access, so the content is never readable under an + inherited ACL. It refuses a stream-qualified leaf (`file:stream`), since a + named NTFS stream shares its base file's security descriptor, and, before any + content is written, a volume without `FILE_PERSISTENT_ACLS` (FAT, exFAT), + which would drop the descriptor. A failure after creation removes only the + file this call created: POSIX unlinks the name only while it still has the + created file's identity, checked immediately before the unlink rather than + atomically with it (an identity never read leaves the name in place), with + the created inode held open until the check is done so its number cannot be + reused by a replacement. A name that already holds another file is left, and + the note names it; a name found empty gets a note that the partial file may + have been moved rather than a removal failure. A failed close of that held + descriptor after a complete write raises, leaving the file and saying so in a + note. A replacement swapped in between the check and the unlink + is an accepted residual race, since POSIX has no unlink-if-identity primitive. + Windows marks the open handle for deletion. If that + removal or the close fails, the original exception is kept and carries a note + naming the file. A Windows close failure after a complete write leaves the + file and says so in the note. - `write_bytes(path, content, mode=0o644)` / `write_text(...)` atomically create or update files with existing parents. Text variants also accept `encoding="utf-8"`. Replacement files use the supplied mode; metadata and @@ -312,6 +369,53 @@ descriptor-relative or change their documented concurrency limitations. Windows creation also honors the CRT process mask: masking the owner-write bit creates a read-only file, matching native text creation, without changing the attributes of an existing file. +- `open_rewrite(path)` is a context manager yielding a blocking, binary, + writable descriptor on an existing regular file at offset 0, for in-place byte + rewrites that must keep the file's identity, owner, mode, ACL and hard links. + It uses `overwrite_text`'s anchored, non-truncating open, but never creates: + POSIX omits `O_CREAT` and Windows does not fall back to creation, so a leaf + removed after resolution raises `FileNotFoundError`. The opened file type is + checked with `fstat` before the descriptor is yielded. The helper closes the + descriptor on exit, so callers must not close it; wrap it with + `closefd=False`. Writing, truncating, flushing and any rollback belong to the + caller; nothing is written or truncated by the helper. There is no newline + translation on either platform. +- `open_read(path)` is a context manager yielding a blocking, binary, read-only + descriptor on an existing regular file, opened as `read_bytes` opens it + (which now reads through it): POSIX opens the leaf no-follow and non-blocking + relative to the anchored parent, and Windows reads through a duplicate of the + validated leaf handle. The helper closes the descriptor on exit; a caller + that keeps the file open longer (to pin its inode, say) `os.dup`s it. +- `utime(path, *, ns)` sets an existing entry's access and modification times, + found by the normal policy walk. POSIX uses `utimensat` relative to the + anchored parent without following the leaf, so a leaf swapped for a link + after the walk sets the link's own times, not its target's. Windows pins the + parent hierarchy and sets the times by path, without following a leaf + reparse point where Python supports that. A regular file renamed over the + leaf after the walk still gets the times, so a caller that holds a verified + descriptor uses the module-level `futime(fd, ns=...)` instead, which sets + them through the descriptor (POSIX only; it raises `ENOTSUP` on Windows). +- `chmod(path, mode)` sets an existing entry's permission bits the same way. + Where no no-follow `fchmodat` exists (Linux), the leaf is checked with a + no-follow stat relative to the anchored parent and a link is refused; a link + swapped in between that check and the change is followed. Windows sets the + read-only attribute by path after pinning the parent hierarchy, without + following a leaf reparse point on Python 3.13 and later. Both methods also + accept the root itself; outside Windows, `chmod` changes the root through the + search-only (or `O_PATH`) descriptor pinned at construction, so like native + `chmod` it needs no read or search access to the root. It acts only while the + root's path still names that directory, so a root renamed and replaced since + construction is refused. + Callers that hold a descriptor should prefer `os.fchmod`. +- `rewrite_descriptor(fd, content)` (static) replaces the whole content of a + descriptor returned by `open_rewrite`: it seeks to offset 0, writes every + byte (retrying short writes), truncates to the new length after writing, then + `fsync`s, adding `F_FULLFSYNC` on macOS where the filesystem supports it. An + append-mode descriptor is refused (`EINVAL`) before anything is written, + since its writes ignore the seek and the truncate would cut them off. It + shares that write loop and flush policy with `create_private_bytes`, so a + caller's in-place rewrite and its private backup have the same durability. + A failure can leave partial content; restoring it is the caller's job. - `delete(path, recursive=False)` unlinks files/links or removes directories. Nonrecursive directory deletion requires an empty directory. The established root cannot be deleted. Recursive enumeration and each removal use anchored @@ -447,8 +551,9 @@ its replacement: creation stays with the opened directory, even if it is renamed out of the root. This is not a guarantee of stable namespace membership under concurrent renames, nor does parent anchoring make every leaf preflight atomic with the subsequent open. -On Windows, exclusive creation and text overwrite still open their leaf by -pathname after pinning the parent hierarchy. Attribute-only reparse updates +On Windows, exclusive creation (including `create_private_bytes`), text +overwrite and `open_rewrite` still open their leaf by pathname after pinning the +parent hierarchy, and `stat`, `utime` and `chmod` reach their leaf the same way. Attribute-only reparse updates can redirect those opens; they do not have the read path's parent-relative handle protection. The helper does not constrain subprocesses or third-party code. diff --git a/design/integration.md b/design/integration.md index bee007d1c5..5443d9c9d0 100644 --- a/design/integration.md +++ b/design/integration.md @@ -338,7 +338,24 @@ generated artifacts. Initial inventories retain only names and filesystem metadata; they do not copy agent trees, user data, or the installed package store. Content snapshots are created lazily before the first observed mutation, with an aggregate limit of 128 MiB of file content and 4,096 entries per -transaction. Exceeding either limit fails before the affected write or removal. +transaction. Captured extended-attribute bytes count toward the same budget. +Exceeding either limit fails before the affected write or removal. +A regular file the operation rewrites in place is restored in place: rollback +writes the snapshot's bytes back through the same file, so it keeps its owner, +hard links and Windows ACL, and sets back its mode, times, user extended +attributes and POSIX access ACL. Outside Windows each such file is pinned by a +read-only descriptor, up to a quarter of the open-file limit (at most 1,024), +so its inode cannot be reused by a replacement; a file without a pin, one the +operation replaced or removed, and a directory are recreated from their +snapshots instead. A file edited in place while it is snapshotted fails the +write. Rollback keeps as a conflict a file whose contents, mode, mtime, +attributes or BSD file flags differ from what the operation left (a repeated +notification with no write in between does not move that baseline), or that +is replaced or edited while rollback works on it. A recreated file gets its +captured attributes back. A file whose bytes come back without all of its +metadata is reported as incomplete. Either way the snapshots are retained, with captured +attributes beside each snapshot as `.xattrs.json`, and the warning +names the snapshot of each affected path. Preset and extension package installation/replacement, configuration rescue directories, and project extension configuration participate in the journal. Package replacements keep one bounded directory snapshot rather than duplicate diff --git a/docs/integrations/api.md b/docs/integrations/api.md index 13795ea708..fd0ffe069a 100644 --- a/docs/integrations/api.md +++ b/docs/integrations/api.md @@ -347,7 +347,13 @@ code. Failed lifecycle operations restore their own tracked changes while preserving unrelated files, workflow progress, and conflicting external edits. Recovery -failures report retained snapshots for manual recovery. Upgrade and uninstall +failures report retained snapshots for manual recovery. Individual files the +operation rewrote in place are restored in place; replaced or removed files, +and directories, are recreated from their snapshots. A file whose bytes are +restored without all of its metadata (mode, times, extended attributes, or BSD +file flags) is reported with its snapshots retained, and captured extended +attributes are kept beside each snapshot as `.xattrs.json`; see the +[shared CLI reference](cli.md#upgrade-an-integration). Upgrade and uninstall preserve modified generated files unless forced; forced recovery still needs local ownership proof to delete old files and does not bypass catalog policy or replacement-package trust. diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index c8bdf3f843..008b8af706 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -295,7 +295,18 @@ Recovery does not bypass catalog policy or replacement-package trust. Failed operations roll back their own changes, not unrelated user files or workflow progress. Conflicting concurrent edits are reported with recovery -snapshots retained. Adapter authors should follow the +snapshots retained, including a file replaced while rollback restores it and a +mode, time or attribute changed after the operation wrote the file. A file +edited in place while the operation snapshots it stops the operation before +it writes. A file the operation rewrote in place gets its original +bytes back in that same file, so it keeps its owner, hard links and Windows +access-control list, and its mode, times, user extended attributes and POSIX +access ACL are set back where the platform allows it safely. If some of that +metadata does not come back, or the file is replaced while its bytes are being +restored, the file is reported as not fully restored, with recovery snapshots +retained. A file the operation replaced or removed, one rollback +cannot safely identify as the original, and a directory are recreated from +their snapshots instead. Adapter authors should follow the [setup and file ownership contract](api.md#setup-and-file-ownership) and [lifecycle guarantees](api.md#external-adapter-lifecycle-guarantees) for safe writes and recovery. diff --git a/src/specify_cli/_file_handles.py b/src/specify_cli/_file_handles.py index 9dceb5a80e..5641f0ceca 100644 --- a/src/specify_cli/_file_handles.py +++ b/src/specify_cli/_file_handles.py @@ -3,6 +3,7 @@ from collections.abc import Iterator from contextlib import contextmanager import errno +import functools import os import secrets import stat @@ -440,6 +441,39 @@ def _windows_stat(handle: int) -> os.stat_result: os.close(fd) +def _has_inherited_allow_entry(fd: int) -> bool: + """Whether a macOS file's ACL has an allow entry; deny entries grant nothing.""" + import ctypes + + libc = ctypes.CDLL(None, use_errno=True) + libc.acl_get_fd_np.restype = ctypes.c_void_p + libc.acl_get_fd_np.argtypes = [ctypes.c_int, ctypes.c_int] + libc.acl_get_entry.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.POINTER(ctypes.c_void_p)] + libc.acl_get_tag_type.argtypes = [ctypes.c_void_p, ctypes.POINTER(ctypes.c_int)] + libc.acl_free.argtypes = [ctypes.c_void_p] + acl = libc.acl_get_fd_np(fd, 0x00000100) # ACL_TYPE_EXTENDED + if not acl: + code = ctypes.get_errno() + # No ACL, or a filesystem that cannot hold one. + if code in (errno.ENOENT, errno.ENOTSUP, errno.EOPNOTSUPP): + return False + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") + try: + entry = ctypes.c_void_p() + tag = ctypes.c_int() + which = 0 # ACL_FIRST_ENTRY, then ACL_NEXT_ENTRY + while libc.acl_get_entry(acl, which, ctypes.byref(entry)) == 0: + which = -1 + if libc.acl_get_tag_type(entry, ctypes.byref(tag)) != 0: + code = ctypes.get_errno() + raise OSError(code, f"Could not read ACL entries: {os.strerror(code)}") + if tag.value == 1: # ACL_EXTENDED_ALLOW + return True + return False + finally: + libc.acl_free(acl) + + @contextmanager def windows_read_fd(handle: int) -> Iterator[int]: """Read the validated object through an independently owned duplicate.""" @@ -462,11 +496,13 @@ def windows_read_fd(handle: int) -> Iterator[int]: @contextmanager -def _windows_overwrite_fd(path: Path) -> Iterator[int]: +def _windows_overwrite_fd(path: Path, *, create: bool = True) -> Iterator[int]: """Open/create without following a new leaf or changing the CRT mask.""" try: handle = _open_windows_handle(path, directory=False, overwrite=True) except FileNotFoundError: + if not create: + raise attributes = _windows_creation_attributes() handle = _open_windows_handle( path, directory=False, overwrite=True, create_attributes=attributes @@ -500,3 +536,184 @@ def _windows_creation_attributes() -> int: os.close(fd) os.unlink(probe) return 0x1 if readonly else 0 + + +_GENERIC_WRITE = 0x40000000 +_DELETE = 0x00010000 +_CREATE_NEW = 1 +_FILE_ATTRIBUTE_NORMAL = 0x80 +_FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000 +_FILE_DISPOSITION_INFO = 4 +_TOKEN_QUERY = 0x8 +_TOKEN_USER = 1 +_ERROR_INSUFFICIENT_BUFFER = 122 +_SDDL_REVISION_1 = 1 +_FILE_PERSISTENT_ACLS = 0x8 + + +def _windows_create_private_fd(path: Path) -> int: + """Create ``path`` owned by, and only accessible to, the current user. + + The owner and protected access-control list are set by the call that + creates the file, and nothing is shared until it closes, so the content is + never readable under an inherited list. A volume that does not persist + access-control lists would drop that list, so the empty file is removed and + the call refused. Returns a binary CRT descriptor. + """ + import ctypes + import msvcrt + from ctypes import wintypes + + kernel, advapi, attributes_type = _windows_security_api() + descriptor = ctypes.c_void_p() + if not advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW( + _windows_owner_only_sddl(), _SDDL_REVISION_1, ctypes.byref(descriptor), None, + ): + raise ctypes.WinError(ctypes.get_last_error()) + try: + attributes = attributes_type(ctypes.sizeof(attributes_type), descriptor, False) + # DELETE lets a later failure remove the file through its own handle. + handle = kernel.CreateFileW( + str(path), _GENERIC_WRITE | _DELETE, 0, ctypes.byref(attributes), _CREATE_NEW, + _FILE_ATTRIBUTE_NORMAL | _FILE_FLAG_OPEN_REPARSE_POINT, None, + ) + if handle is None or handle == wintypes.HANDLE(-1).value: + raise ctypes.WinError(ctypes.get_last_error()) + finally: + kernel.LocalFree(descriptor) + try: + _require_persistent_acls(kernel, handle, path) + return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY) + except BaseException as error: + # No descriptor reaches the caller, so remove the empty file here. With + # no sharing, nothing else could have opened, renamed or replaced it. + class FileDispositionInfo(ctypes.Structure): + _fields_ = [("DeleteFile", wintypes.BOOLEAN)] + + try: + disposition = FileDispositionInfo(True) + if not kernel.SetFileInformationByHandle( + handle, _FILE_DISPOSITION_INFO, ctypes.byref(disposition), + ctypes.sizeof(disposition), + ): + raise ctypes.WinError(ctypes.get_last_error()) + except Exception as cleanup_error: + error.add_note(f"Could not remove empty file {path}: {cleanup_error}") + finally: + kernel.CloseHandle(handle) + raise + + +def _require_persistent_acls(kernel, handle: int, path: Path) -> None: + """Refuse a volume that drops security descriptors, such as FAT or exFAT.""" + import ctypes + from ctypes import wintypes + + flags = wintypes.DWORD() + if not kernel.GetVolumeInformationByHandleW( + handle, None, 0, None, None, ctypes.byref(flags), None, 0, + ): + error = ctypes.WinError(ctypes.get_last_error()) + error.add_note(f"Could not check that the volume holding {path} keeps access-control lists") + raise error + if not flags.value & _FILE_PERSISTENT_ACLS: + raise PermissionError( + errno.EACCES, + f"Refusing to write {path}: its volume does not keep access-control lists", + ) + + +def _windows_owner_only_sddl() -> str: + """The security descriptor, as SDDL, private files are created with.""" + sid = _windows_current_user_sid() + return f"O:{sid}D:P(A;;FA;;;{sid})" + + +@functools.lru_cache(maxsize=1) +def _windows_current_user_sid() -> str: + import ctypes + from ctypes import wintypes + + kernel, advapi, _ = _windows_security_api() + token = wintypes.HANDLE() + if not advapi.OpenProcessToken(kernel.GetCurrentProcess(), _TOKEN_QUERY, ctypes.byref(token)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + size = wintypes.DWORD() + if not advapi.GetTokenInformation(token, _TOKEN_USER, None, 0, ctypes.byref(size)): + code = ctypes.get_last_error() + if code != _ERROR_INSUFFICIENT_BUFFER: + raise ctypes.WinError(code) + buffer = ctypes.create_string_buffer(size.value) + if not advapi.GetTokenInformation( + token, _TOKEN_USER, buffer, size, ctypes.byref(size), + ): + raise ctypes.WinError(ctypes.get_last_error()) + # TOKEN_USER starts with SID_AND_ATTRIBUTES, whose first field is the SID. + sid = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p))[0] + text = wintypes.LPWSTR() + if not advapi.ConvertSidToStringSidW(sid, ctypes.byref(text)): + raise ctypes.WinError(ctypes.get_last_error()) + try: + value = text.value + finally: + kernel.LocalFree(ctypes.cast(text, ctypes.c_void_p)) + finally: + kernel.CloseHandle(token) + if not value or not value.startswith("S-"): + raise OSError(errno.EINVAL, "Could not read the current user's security identifier") + return value + + +@functools.lru_cache(maxsize=1) +def _windows_security_api(): + """kernel32 and advapi32 with private prototypes, and SECURITY_ATTRIBUTES.""" + import ctypes + from ctypes import wintypes + + class SecurityAttributes(ctypes.Structure): + _fields_ = [ + ("nLength", wintypes.DWORD), + ("lpSecurityDescriptor", ctypes.c_void_p), + ("bInheritHandle", wintypes.BOOL), + ] + + kernel = ctypes.WinDLL("kernel32", use_last_error=True) + advapi = ctypes.WinDLL("advapi32", use_last_error=True) + kernel.LocalFree.argtypes = [ctypes.c_void_p] + kernel.LocalFree.restype = ctypes.c_void_p + kernel.CloseHandle.argtypes = [wintypes.HANDLE] + kernel.CloseHandle.restype = wintypes.BOOL + kernel.GetCurrentProcess.argtypes = [] + kernel.GetCurrentProcess.restype = wintypes.HANDLE + kernel.CreateFileW.argtypes = [ + wintypes.LPCWSTR, wintypes.DWORD, wintypes.DWORD, + ctypes.POINTER(SecurityAttributes), wintypes.DWORD, wintypes.DWORD, wintypes.HANDLE, + ] + kernel.CreateFileW.restype = wintypes.HANDLE + kernel.SetFileInformationByHandle.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, + ] + kernel.SetFileInformationByHandle.restype = wintypes.BOOL + kernel.GetVolumeInformationByHandleW.argtypes = [ + wintypes.HANDLE, wintypes.LPWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD), + ctypes.POINTER(wintypes.DWORD), ctypes.POINTER(wintypes.DWORD), wintypes.LPWSTR, + wintypes.DWORD, + ] + kernel.GetVolumeInformationByHandleW.restype = wintypes.BOOL + advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [ + wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), wintypes.LPVOID, + ] + advapi.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL + advapi.OpenProcessToken.argtypes = [ + wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE), + ] + advapi.OpenProcessToken.restype = wintypes.BOOL + advapi.GetTokenInformation.argtypes = [ + wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, + ctypes.POINTER(wintypes.DWORD), + ] + advapi.GetTokenInformation.restype = wintypes.BOOL + advapi.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)] + advapi.ConvertSidToStringSidW.restype = wintypes.BOOL + return kernel, advapi, SecurityAttributes diff --git a/src/specify_cli/file_helper.py b/src/specify_cli/file_helper.py index 9b00895ae0..1cacc37ab1 100644 --- a/src/specify_cli/file_helper.py +++ b/src/specify_cli/file_helper.py @@ -16,9 +16,10 @@ from weakref import finalize from specify_cli._file_handles import ( - _WindowsFileIdentity, _windows_delete, _windows_directory_names, _windows_entry, - _windows_file_id, _windows_handle, _windows_mode, _windows_overwrite_fd, - _windows_readlink, _windows_stat, rename_noreplace, windows_read_fd, + _WindowsFileIdentity, _has_inherited_allow_entry, _windows_create_private_fd, + _windows_delete, _windows_directory_names, _windows_entry, _windows_file_id, + _windows_handle, _windows_mode, _windows_overwrite_fd, _windows_readlink, + _windows_stat, rename_noreplace, windows_read_fd, ) @@ -31,6 +32,112 @@ _DELETE_DIRECTORY_CACHE_SIZE = 8 # Wrapping os.open must not change the underlying platform capability. _POSIX_OPEN = os.open +_NO_FOLLOW_UTIME = {"follow_symlinks": False} if os.utime in os.supports_follow_symlinks else {} +_NO_FOLLOW_CHMOD = {"follow_symlinks": False} if os.chmod in os.supports_follow_symlinks else {} + + +def futime(fd: int, *, ns: tuple[int, int]) -> None: + """Set an open file's access and modification times through its descriptor. + + Raises ``OSError(ENOTSUP)`` where ``os.utime`` takes no descriptor + (Windows); use ``FileHelper.utime`` there. + """ + if os.utime not in os.supports_fd: + raise OSError(errno.ENOTSUP, "Setting times through a descriptor is unsupported on this platform") + os.utime(fd, ns=ns) + + +def _remove_created( + directory: int, name: str, created: os.stat_result | None, error: BaseException +) -> None: + """Unlink ``name`` if it still has the created file's identity (best effort). + + A name that now holds a different file is left in place and named in a note + on ``error``, so the caller learns that cleanup did not happen. + """ + if created is None: + error.add_note(f"Left {name}, which may be empty; delete it before retrying") + return + try: + current = os.stat(name, dir_fd=directory, follow_symlinks=False) + except FileNotFoundError: + error.add_note( + f"Found nothing at {name} to remove: the partial file was moved or deleted " + "by another process and may still exist elsewhere" + ) + return + except OSError as cleanup_error: + error.add_note(f"Could not remove partial file {name}: {cleanup_error}") + return + if (current.st_dev, current.st_ino) != (created.st_dev, created.st_ino): + error.add_note( + f"Left {name}: another writer replaced the partial file, so it was not removed; " + "the partial file may still exist under another name" + ) + return + try: + # Accepted residual race: POSIX has no unlink-if-inode, so a writer that + # swaps the leaf between this stat and the unlink loses its file. Both + # calls go through the same directory descriptor with nothing between + # them, and the caller pins the created inode so its number cannot be + # reused by a replacement that would then pass the check above. + os.unlink(name, dir_fd=directory) + except OSError as cleanup_error: + error.add_note(f"Could not remove partial file {name}: {cleanup_error}") + + +def _require_owner_only(fd: int, info: os.stat_result, name: str) -> None: + """Refuse a new, still-empty file that someone other than its owner can open. + + Group or other mode bits mean the filesystem ignored the creation mode, and a + different owner means it mapped ownership. On + macOS, a parent's inheritable ACEs are added to a new file whatever its mode, + and they cannot be withheld from a directory-relative create, so such a file + is refused before any content reaches it. NFSv4-style inherited ACLs on other + systems are not inspected. + """ + if stat.S_IMODE(info.st_mode) & 0o077: + raise PermissionError( + errno.EACCES, + f"Filesystem did not create {name} owner-only " + f"(mode {stat.S_IMODE(info.st_mode):o})", + ) + # A mapped or fixed-ownership filesystem can give the file to another user, + # who could then read the private content however tight its mode is. + if hasattr(os, "geteuid") and info.st_uid != os.geteuid(): + raise PermissionError( + errno.EACCES, + f"Filesystem created {name} owned by uid {info.st_uid}, not the caller", + ) + if sys.platform == "darwin" and _has_inherited_allow_entry(fd): + raise PermissionError( + errno.EACCES, + f"Refusing to write {name}: its directory's inheritable ACL entries allow " + "others access", + ) + + +def _full_fsync(fd: int) -> None: + """Flush to stable storage; macOS ``fsync`` alone leaves data in the drive cache.""" + os.fsync(fd) + if sys.platform == "darwin": + import fcntl + + try: + fcntl.fcntl(fd, fcntl.F_FULLFSYNC) + except OSError as error: + # Not every filesystem supports it, and fsync has already run. + if error.errno not in (errno.ENOTSUP, errno.EOPNOTSUPP, errno.EINVAL, errno.ENOTTY): + raise + + +def _write_all(fd: int, content: bytes) -> None: + view = memoryview(content) + while view: + count = os.write(fd, view) + if count == 0: + raise OSError(errno.EIO, "Write made no progress") + view = view[count:] def _strip_extended_length_prefix(path: _PathType) -> _PathType: @@ -381,6 +488,66 @@ def _require_directory(path: Path) -> None: if not stat.S_ISDIR(path.stat().st_mode): raise NotADirectoryError(path) + @property + def canonical_root(self) -> Path: + """``root`` with OS and link aliases resolved, as fixed on construction.""" + return self._canonical_root + + def access(self, path: Path | str, mode: int) -> bool: + """Return whether ``os.access`` grants ``mode`` on an existing entry. + + The entry is found and anchored as ``stat`` finds it, so a leaf link is + refused or resolved by the normal policy walk; a leaf swapped for a link + after that walk is followed. Like ``os.access``, the answer uses the + real user and group ids and is advisory: act through a descriptor and + handle its errors. + """ + destination = self._path(path) + if destination == self._canonical_root: + return os.access(destination, mode) + if os.name == "nt": + # Pin the hierarchy as ``stat`` does; Windows ``os.access`` has no ``dir_fd``. + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + return os.access(destination, mode) + unsupported = "Anchored access check is unsupported on this platform" + if os.access not in os.supports_dir_fd: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + # No ``follow_symlinks=False``: the walk already handled a leaf link, + # and without ``faccessat2`` libc emulates that flag from mode bits. + return os.access(destination.name, mode, dir_fd=directory) + + def stat(self, path: Path | str) -> os.stat_result: + """Return the metadata of an existing entry, resolving only allowed links.""" + destination = self._path(path) + if destination == self._canonical_root: + return os.stat(destination, follow_symlinks=False) + # Stat through the anchored parent so a swapped ancestor cannot redirect it. + if os.name == "nt": + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + return os.stat(destination, follow_symlinks=False) + unsupported = "Anchored stat is unsupported on this platform" + if os.stat not in os.supports_dir_fd or os.stat not in os.supports_follow_symlinks: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + return os.stat(destination.name, dir_fd=directory, follow_symlinks=False) + def directory_exists(self, path: Path | str) -> bool: """Return False for absence only; reject wrong types and forbidden paths.""" try: @@ -478,6 +645,16 @@ def cleanup() -> None: cleanup() def read_bytes(self, path: Path | str) -> bytes: + with self.open_read(path) as fd, os.fdopen(fd, "rb", closefd=False) as stream: + return stream.read() + + @contextmanager + def open_read(self, path: Path | str) -> Iterator[int]: + """Yield a blocking binary read descriptor on an existing regular file. + + The helper closes the descriptor on exit, so the caller must not close it; + ``os.dup`` it to keep the file open longer. + """ destination = self._path(path) self._require_file(destination) with ExitStack() as stack: @@ -507,8 +684,10 @@ def read_bytes(self, path: Path | str) -> bytes: stack.callback(os.close, fd) if not stat.S_ISREG(os.fstat(fd).st_mode): raise UnsupportedPathError(f"Expected a regular file: {destination}") - with os.fdopen(fd, "rb", closefd=False) as stream: - return stream.read() + if os.name != "nt": + # Opened non-blocking only so a FIFO swapped in cannot hang the open. + os.set_blocking(fd, True) + yield fd def read_text(self, path: Path | str, *, encoding: str = "utf-8") -> str: return self.read_bytes(path).decode(encoding) @@ -582,6 +761,111 @@ def create_text( ) -> None: self.create_bytes(path, content.encode(encoding), mode=mode) + def create_private_bytes(self, path: Path | str, content: bytes) -> None: + """Exclusively create a file only the current user can open, flushed to disk. + + A failure after creation removes only the file this call created. + """ + if os.name == "nt" and ":" in Path(path).name: + # A named NTFS stream shares its base file's security descriptor, so + # the owner-only descriptor would not apply to it. + raise UnsupportedPathError(f"Refusing to create a named stream: {path}") + destination = self._path(path, allow_missing=True, follow_leaf=False) + try: + self._entry_mode(destination) + except FileNotFoundError: + pass + else: + raise FileExistsError(errno.EEXIST, os.strerror(errno.EEXIST), str(destination)) + with self._creation_directory(destination.parent) as directory: + if isinstance(directory, Path): + self._windows_create_private(directory / destination.name, content) + else: + self._posix_create_private(directory, destination.name, content) + + @staticmethod + def _posix_create_private(directory: int, name: str, content: bytes) -> None: + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + flags |= getattr(os, "O_CLOEXEC", 0) + fd = os.open(name, flags, 0o600, dir_fd=directory) + created: os.stat_result | None = None + pin: int | None = None + try: + created = os.fstat(fd) + # Holds the created inode until any cleanup is done, even if the final + # close releases ``fd``, so a replacement cannot reuse its number and + # pass the identity check. + pin = os.dup(fd) + _require_owner_only(fd, created, name) + _write_all(fd, content) + _full_fsync(fd) + closing, fd = fd, -1 + os.close(closing) + except BaseException as error: + try: + _remove_created(directory, name, created, error) + finally: + for descriptor in (fd, -1 if pin is None else pin): + if descriptor >= 0: + try: + os.close(descriptor) + except OSError as close_error: + error.add_note(f"Could not close {name}: {close_error}") + raise + # The duplicate is now the file's last descriptor, so its close is the + # one that reports a deferred write error (NFS, for example). + try: + os.close(pin) + except OSError as close_error: + close_error.add_note( + f"Wrote and flushed {name}, but closing it failed; check its content " + "before relying on it" + ) + raise + # Best effort: the anchor may be O_PATH or search-only, which fsync rejects. + try: + parent = os.open( + ".", os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_CLOEXEC", 0), + dir_fd=directory, + ) + except OSError: + return + try: + _full_fsync(parent) + except OSError: + pass + finally: + try: + os.close(parent) + except OSError: + pass + + @staticmethod + def _windows_create_private(path: Path, content: bytes) -> None: + fd = _windows_create_private_fd(path) + try: + _write_all(fd, content) + _full_fsync(fd) + except BaseException as error: + import msvcrt + + # The handle shares nothing, so it can only name the created file. + try: + _windows_delete(msvcrt.get_osfhandle(fd)) + except Exception as cleanup_error: + error.add_note(f"Could not remove partial file {path}: {cleanup_error}") + try: + os.close(fd) + except OSError as close_error: + error.add_note(f"Could not close {path}: {close_error}") + raise + try: + os.close(fd) + except OSError as error: + # The handle is gone, so it can no longer remove the file. + error.add_note(f"{path} was written and flushed but may need deleting before a retry") + raise + def write_bytes(self, path: Path | str, content: bytes, *, mode: int = 0o644) -> None: """Atomically create/replace a file, preserving any allowed leaf link.""" destination = self._path(path, allow_missing=True) @@ -620,7 +904,49 @@ def overwrite_text( stream.write(content) @contextmanager - def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: + def open_rewrite(self, path: Path | str) -> Iterator[int]: + """Yield a blocking binary write descriptor on an existing regular file, untruncated. + + The descriptor starts at offset 0 and the helper closes it on exit, so the + caller must not close it (wrap it with ``os.fdopen(fd, "wb", closefd=False)``). + The caller owns writing, truncating and flushing; owner, mode and links are + unchanged. + """ + destination = self._path(path) + self._require_file(destination) + with self._overwrite_descriptor(destination, create=False) as fd: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise UnsupportedPathError(f"Expected a regular file: {destination}") + if os.name != "nt": + # Opened non-blocking only so a FIFO swapped in cannot hang the open. + os.set_blocking(fd, True) + yield fd + + @staticmethod + def rewrite_descriptor(fd: int, content: bytes) -> None: + """Replace everything in the open file ``fd`` with ``content``, flushed to disk. + + Only for a descriptor from ``open_rewrite``. It writes from offset 0 + whatever the current offset, truncates after writing (so the old bytes' + space is reused rather than freed first), then ``fsync``s, adding + ``F_FULLFSYNC`` on macOS where the filesystem supports it: the same + write and flush that ``create_private_bytes`` uses. An append-mode + descriptor is refused before anything is written, since its writes + ignore the seek and the truncate would then cut them off. A failure can + leave partial content; restoring it is the caller's job. + """ + if os.name != "nt": + import fcntl + + if fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_APPEND: + raise OSError(errno.EINVAL, "Refusing to rewrite through an append-mode descriptor") + os.lseek(fd, 0, os.SEEK_SET) + _write_all(fd, content) + os.ftruncate(fd, len(content)) + _full_fsync(fd) + + @contextmanager + def _overwrite_descriptor(self, destination: Path, *, create: bool = True) -> Iterator[int]: """Anchor the resolved hierarchy before opening a non-truncating leaf.""" with ExitStack() as stack: if os.name == "nt": @@ -630,7 +956,7 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: for part in parts[:-1]: current = current / part stack.enter_context(_windows_handle(current, directory=True)) - yield stack.enter_context(_windows_overwrite_fd(destination)) + yield stack.enter_context(_windows_overwrite_fd(destination, create=create)) return unsupported = "Scoped text overwrite is unsupported on this platform" @@ -638,8 +964,8 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: raise OSError(errno.ENOTSUP, unsupported) with self._posix_directory(destination.parent, unsupported_message=unsupported) as parent: flags = ( - os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK - | getattr(os, "O_CLOEXEC", 0) + os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK | getattr(os, "O_CLOEXEC", 0) + | (os.O_CREAT if create else 0) ) fd = os.open(destination.name, flags, 0o666, dir_fd=parent) try: @@ -647,6 +973,107 @@ def _overwrite_descriptor(self, destination: Path) -> Iterator[int]: finally: os.close(fd) + def utime(self, path: Path | str, *, ns: tuple[int, int]) -> None: + """Set an existing entry's access and modification times, in nanoseconds. + + The entry is found as ``stat`` finds it and set without following a leaf + link swapped in after that walk (POSIX ``utimensat`` relative to the + anchored parent). Windows pins the parent hierarchy and sets the times by + path, without following a leaf reparse point where Python supports that. + A regular file renamed over the leaf after the walk still gets the times; + callers holding a verified descriptor should use ``futime``. + """ + destination = self._path(path) + if destination == self._canonical_root: + os.utime(destination, ns=ns, **_NO_FOLLOW_UTIME) + return + if os.name == "nt": + with self._windows_parents(destination): + os.utime(destination, ns=ns, **_NO_FOLLOW_UTIME) + return + unsupported = "Anchored utime is unsupported on this platform" + if os.utime not in os.supports_dir_fd or os.utime not in os.supports_follow_symlinks: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + os.utime(destination.name, ns=ns, dir_fd=directory, follow_symlinks=False) + + def chmod(self, path: Path | str, mode: int) -> None: + """Set an existing entry's permission bits, without following a leaf link. + + Where the platform has no no-follow ``fchmodat`` (Linux), the leaf is + checked with a no-follow stat relative to the anchored parent first and a + link is refused; a link swapped in between that check and the change is + followed. The root itself is changed through the descriptor pinned at + construction, without read access, and only while its path still names + the root the helper was built on. Windows pins the + parent hierarchy and sets the mode by path, + which only toggles the read-only attribute, without following a leaf + reparse point where Python supports that (3.13 and later). Prefer + ``os.fchmod`` on an open descriptor where it exists. + """ + destination = self._path(path) + if destination == self._canonical_root: + if os.name == "nt": + os.chmod(destination, mode, **_NO_FOLLOW_CHMOD) + return + self._chmod_root(mode) + return + if os.name == "nt": + with self._windows_parents(destination): + os.chmod(destination, mode, **_NO_FOLLOW_CHMOD) + return + unsupported = "Anchored chmod is unsupported on this platform" + if os.chmod not in os.supports_dir_fd: + raise OSError(errno.ENOTSUP, unsupported) + with self._posix_directory(destination.parent, unsupported_message=unsupported) as directory: + if os.chmod in os.supports_follow_symlinks: + os.chmod(destination.name, mode, dir_fd=directory, follow_symlinks=False) + return + if stat.S_ISLNK(os.stat(destination.name, dir_fd=directory, follow_symlinks=False).st_mode): + raise SymlinkDeniedError(f"Refusing to change the mode of a link: {destination}") + os.chmod(destination.name, mode, dir_fd=directory) + + def _chmod_root(self, mode: int) -> None: + """Change the established root's mode without needing to read it. + + A root renamed and replaced by a link or another directory since the + helper was built is refused, never changed. The change goes through the + root descriptor pinned at construction (search-only or ``O_PATH``), so + like native ``chmod`` it needs no read or search access to the root. + """ + self._require_open() + if not os.path.samestat(self._root_stat, os.lstat(self._canonical_root)): + raise FileHelperError(f"Established root changed: {self.root}") + with ExitStack() as resources: + descriptor = self._root_anchor + if not isinstance(descriptor, int): + descriptor = os.open(self._canonical_root, self._directory_flags()) + resources.callback(os.close, descriptor) + if not os.path.samestat(self._root_stat, os.fstat(descriptor)): + raise FileHelperError(f"Established root changed: {self.root}") + try: + os.fchmod(descriptor, mode) + except OSError as exc: + # Linux refuses fchmod on an O_PATH descriptor; its /proc entry + # names the same directory, as glibc's own fchmodat fallback uses. + if exc.errno != errno.EBADF or not sys.platform.startswith("linux"): + raise + os.chmod(f"/proc/self/fd/{descriptor}", mode) + + @contextmanager + def _windows_parents(self, destination: Path) -> Iterator[None]: + """Pin the Windows directory handles from the root to ``destination``'s parent.""" + parts = destination.relative_to(self._canonical_root).parts + with ExitStack() as stack: + parent = stack.enter_context(_windows_handle( + self._canonical_root, directory=True, traverse=True, + )) + for part in parts[:-1]: + parent = stack.enter_context(_windows_handle( + Path(part), directory=True, parent=parent, traverse=True, + )) + yield + def symlink(self, target: Path | str, path: Path | str) -> None: """Create a link to an existing contained regular file or directory. diff --git a/src/specify_cli/integrations/_lifecycle.py b/src/specify_cli/integrations/_lifecycle.py index af61010c42..6524b38bf6 100644 --- a/src/specify_cli/integrations/_lifecycle.py +++ b/src/specify_cli/integrations/_lifecycle.py @@ -2,16 +2,20 @@ from __future__ import annotations +import base64 import errno import hashlib import inspect +import json import os import shutil import stat +import sys import tempfile from contextlib import ExitStack, contextmanager from contextvars import ContextVar -from functools import wraps +from collections.abc import Callable +from functools import partial, wraps from pathlib import Path from typing import Any @@ -19,6 +23,7 @@ from rich.markup import escape from .._console import console +from ..file_helper import FileHelper, FileHelperError, futime from ..integration_state import ( default_integration_key, installed_integration_keys, @@ -35,6 +40,68 @@ ) _MAX_BACKUP_BYTES = 128 * 1024 * 1024 _MAX_BACKUP_ENTRIES = 4096 +_HAS_XATTRS = all(hasattr(os, name) for name in ("listxattr", "getxattr", "setxattr", "removexattr")) +_XATTRS_UNSUPPORTED = {errno.ENOTSUP, getattr(errno, "EOPNOTSUPP", errno.ENOTSUP)} +# The Linux POSIX access ACL, which the file's owner may set like a user +# attribute and ``shutil.copy2()`` copies with the others. +_ACCESS_ACL = "system.posix_acl_access" +# Most read-only descriptors held on snapshotted files so rollback can trust +# their identity; ``_pin_limit()`` lowers it to a quarter of the open-file limit. +_MAX_PINNED_FILES = 1024 +# Flags the filesystem itself changes when a file's bytes are rewritten: +# UF_COMPRESSED on macOS, and the UF_ARCHIVE bit FreeBSD and DragonFly set +# on a write (ZFS, msdosfs). +if sys.platform == "darwin": + _UNCOMPARED_FLAGS = getattr(stat, "UF_COMPRESSED", 0x20) +elif sys.platform.startswith(("freebsd", "dragonfly")): + _UNCOMPARED_FLAGS = 0x800 +else: + _UNCOMPARED_FLAGS = 0 + + +def _restorable_xattrs(target: Path | int, journal: Any = None) -> dict[str, bytes]: + """Read the extended attributes of a path or descriptor that rollback restores. + + These are the ``user.*`` attributes and the POSIX access ACL, all of which + the file's owner may set. The kernel and security modules manage the + others (``security.*``, the rest of ``system.*``), which a file write can + change and an unprivileged rollback cannot set back. An attribute removed + between listing and reading it is skipped. ``journal``, when given, is + charged for the bytes kept. + """ + follow = {} if isinstance(target, int) else {"follow_symlinks": False} + attributes = {} + for name in os.listxattr(target, **follow): + if not name.startswith("user.") and name != _ACCESS_ACL: + continue + try: + value = os.getxattr(target, name, **follow) + except OSError as exc: + if exc.errno != errno.ENODATA: + raise + continue + if journal is not None: + # Charged as each value is read, so the budget stops collection + # before the rest are held in memory. + size = len(name) + len(value) + if size > _MAX_BACKUP_BYTES - journal.backup_bytes: + raise installer.IntegrationInstallError("Integration rollback snapshot budget exceeded (bytes)") + journal.backup_bytes += size + attributes[name] = value + return attributes + + +def _pin_limit() -> int: + """How many snapshotted files a transaction may pin, leaving most descriptors free.""" + try: + import resource + + soft, _ = resource.getrlimit(resource.RLIMIT_NOFILE) + if soft == resource.RLIM_INFINITY: + return _MAX_PINNED_FILES + except (ImportError, OSError, ValueError): + soft = 256 + return max(0, min(_MAX_PINNED_FILES, soft // 4)) def lifecycle_owns_rollback() -> bool: @@ -84,6 +151,14 @@ def _entry_state(path: Path) -> tuple[int, ...]: entry.st_mtime_ns, entry.st_ctime_ns, ) +def _stat_state(entry: os.stat_result) -> tuple[int, ...]: + """The fields ``_entry_state`` compares, from a stat result already taken.""" + return ( + entry.st_mode, entry.st_dev, entry.st_ino, entry.st_size, + entry.st_mtime_ns, entry.st_ctime_ns, + ) + + def _matches_directory_before_write(current: Any, expected: Any, parents: tuple[str, ...]) -> bool: """Allow only new empty directories on the destination's parent chain.""" if current == expected: @@ -144,6 +219,37 @@ def __init__( self.backup_entries = 0 self.directory_states: dict[Path, bool] = {} self.created_directories: list[tuple[Path, tuple[int, int]]] = [] + # The (st_dev, st_ino) of each snapshotted regular file, so rollback + # can tell the same file, rewritten in place, from a replacement. + self.snapshotted_files: dict[Path, tuple[int, int]] = {} + # Outside Windows, a read-only descriptor on each such file, held + # until the transaction ends so its inode cannot be freed and reused + # by a replacement. Windows gets none: an open file there cannot be + # replaced or removed, which would fail the operation itself, so it + # keeps the device and file-ID check alone. + self.pinned_files: dict[Path, int] = {} + self.pin_limit = 0 if os.name == "nt" else _pin_limit() + # The (st_dev, st_ino) of files that could not be pinned (past + # ``pin_limit``). Rollback recreates them, and reports one that still + # has that identity, as it was probably rewritten in place. + self.unverified_files: dict[Path, tuple[int, int]] = {} + # Each such file's restorable extended attributes, read when it was + # snapshotted; None when they could not be read or the os module has + # no extended-attribute API (CPython has one on Linux only). A + # non-empty set is also written beside the snapshot + # (``_persist_xattrs``), so a retained snapshot keeps it. + self.snapshotted_xattrs: dict[Path, dict[str, bytes] | None] = {} + # Each such file's BSD file flags (macOS and the BSDs), or None. + self.snapshotted_flags: dict[Path, int | None] = {} + # Files whose bytes rollback restored without all of their metadata. + self.incomplete_restores: list[Path] = [] + # Attributes a pinned snapshot captured, charged to the budget, for + # ``observe`` to keep rather than read (and charge) a second time. + self.pinned_xattrs: dict[Path, dict[str, bytes] | None] = {} + # The mode, mtime and restorable extended attributes (None when not + # read) each regular file had after the operation last wrote it, so + # rollback can tell a later metadata-only edit from the operation's. + self.written_metadata: dict[Path, tuple[int, int, dict[str, bytes] | None]] = {} for path in paths: self._remember_parents(path) @@ -163,6 +269,12 @@ def _remember_parents(self, path: Path) -> None: self.directory_states[parent] = parent.is_dir() def _snapshot(self, source: Path, destination: Path) -> None: + """Copy ``source`` to ``destination``; a pinned regular file's first snapshot is read through its pin. + + A file already journalled has been snapshotted, and the operation may + have replaced it since, so a later snapshot of a directory holding it + reads it from its path: its pin may hold an inode no longer there. + """ self.backup_entries += 1 if self.backup_entries > _MAX_BACKUP_ENTRIES: raise installer.IntegrationInstallError("Integration rollback snapshot budget exceeded (entries)") @@ -174,6 +286,8 @@ def _snapshot(self, source: Path, destination: Path) -> None: for child in source.iterdir(): self._snapshot(child, destination / child.name) shutil.copystat(source, destination, follow_symlinks=False) + elif stat.S_ISREG(mode) and source in self.pinned_files and source not in self.changes: + self.pinned_xattrs[source] = self._snapshot_pinned(self.pinned_files[source], destination) elif stat.S_ISREG(mode): if source.stat().st_size > _MAX_BACKUP_BYTES - self.backup_bytes: raise installer.IntegrationInstallError("Integration rollback snapshot budget exceeded (bytes)") @@ -187,6 +301,213 @@ def _snapshot(self, source: Path, destination: Path) -> None: else: raise installer.IntegrationInstallError(f"Unsupported integration output: {source}") + def _snapshot_with_headroom(self, path: Path, saved: Path) -> None: + """Snapshot ``path``, giving up its pin if the copy runs out of descriptors. + + Pins count against the open-file limit, so a process already near it + can find no slot left for the copy. Then this pin is released, no more + are taken, and the copy is retried from the path; the file falls back + to being recreated on rollback, like any file without a pin. + """ + entries, used = self.backup_entries, self.backup_bytes + try: + self._snapshot(path, saved) + except OSError as exc: + if exc.errno not in (errno.EMFILE, errno.ENFILE) or path not in self.pinned_files: + raise + self._unpin(path) + self.pinned_xattrs.pop(path, None) + self.pin_limit = len(self.pinned_files) + self.backup_entries, self.backup_bytes = entries, used + with FileHelper(saved.parent) as files: + try: + files.delete(saved.name) + except FileNotFoundError: + pass + self._snapshot(path, saved) + + def _snapshot_pinned(self, pinned: int, destination: Path) -> dict[str, bytes] | None: + """Copy a pinned file to ``destination`` through its pin, as ``shutil.copy2`` would. + + Bytes stream through ``os.pread``, which leaves the pin's own offset + alone. Restorable extended attributes, times, mode and BSD flags follow, + each set as best effort where the temporary filesystem refuses it, + like ``shutil.copystat``. The attributes are read once, charged to the + snapshot budget as they are read, and returned as the file's capture + (None if they cannot be read). + """ + original = os.fstat(pinned) + if original.st_size > _MAX_BACKUP_BYTES - self.backup_bytes: + raise installer.IntegrationInstallError("Integration rollback snapshot budget exceeded (bytes)") + with FileHelper(destination.parent) as files: + files.create_bytes(destination.name, b"") + with files.open_rewrite(destination.name) as outgoing: + offset = 0 + while content := os.pread(pinned, min(65536, _MAX_BACKUP_BYTES - self.backup_bytes + 1), offset): + self.backup_bytes += len(content) + if self.backup_bytes > _MAX_BACKUP_BYTES: + raise installer.IntegrationInstallError("Integration rollback snapshot budget exceeded (bytes)") + _write_descriptor(outgoing, content) + offset += len(content) + attributes = self._read_xattrs(pinned) + if attributes: + _copy_xattrs(attributes, outgoing) + futime(outgoing, ns=(original.st_atime_ns, original.st_mtime_ns)) + os.fchmod(outgoing, stat.S_IMODE(original.st_mode)) + flags = getattr(original, "st_flags", 0) + if flags and hasattr(os, "chflags"): + try: + os.chflags(destination, flags, follow_symlinks=False) + except OSError as exc: + if exc.errno not in _XATTRS_UNSUPPORTED: + raise + return attributes + + @staticmethod + def _persist_xattrs(path: Path, saved: Path, attributes: dict[str, bytes] | None) -> None: + """Write ``path``'s captured attributes beside its snapshot, as ``.xattrs.json``. + + The snapshot copy keeps them only where the temporary filesystem has + user attributes, so a retained snapshot would otherwise lose them when + the process exits. A sidecar that cannot be written raises, before the + operation writes the file. + """ + if not attributes: + return + record = { + "path": str(path), + "attributes": {name: base64.b64encode(value).decode("ascii") for name, value in attributes.items()}, + } + with FileHelper(saved.parent) as files: + files.create_private_bytes( + f"{saved.name}.xattrs.json", json.dumps(record, indent=2, sort_keys=True).encode("utf-8"), + ) + + def _remember_original(self, path: Path, entry: os.stat_result, attributes: dict[str, bytes] | None) -> None: + """Record what rollback needs to restore ``path`` in place later.""" + # Kept for every file, pinned or not: a file rollback recreates gets + # them back from here when the snapshot's filesystem dropped them. + self.snapshotted_xattrs[path] = attributes + if os.name != "nt" and path not in self.pinned_files: + self.unverified_files[path] = (entry.st_dev, entry.st_ino) + return + self.snapshotted_files[path] = (entry.st_dev, entry.st_ino) + self.snapshotted_xattrs[path] = attributes + self.snapshotted_flags[path] = getattr(entry, "st_flags", None) + + def _pin(self, path: Path, entry: os.stat_result) -> bool: + """Hold a read-only descriptor on ``path`` if it is still ``entry``. + + Taken before the file is snapshotted, so the inode is held from then + on and a replacement cannot be mistaken for the original. + """ + if len(self.pinned_files) >= self.pin_limit: + return False + try: + with FileHelper(path.parent) as files, files.open_read(path.name) as opened: + descriptor = os.dup(opened) + except (OSError, FileHelperError): + return False + try: + same = os.path.samestat(entry, os.fstat(descriptor)) + except OSError: + same = False + if not same: + os.close(descriptor) + return False + self.pinned_files[path] = descriptor + return True + + def _unpin(self, path: Path) -> None: + descriptor = self.pinned_files.pop(path, None) + if descriptor is not None: + try: + os.close(descriptor) + except OSError: + pass + + def is_original(self, path: Path, current: os.stat_result) -> bool: + """Whether ``current``, found at ``path``, is the snapshotted file itself. + + Same device and inode and, outside Windows, a pin that still has a + name: while pinned the inode cannot be reused, and a pinned inode + unlinked everywhere is not the file now at ``path``. + """ + identity = self.snapshotted_files.get(path) + if not stat.S_ISREG(current.st_mode) or (current.st_dev, current.st_ino) != identity: + return False + if os.name == "nt": + return True + descriptor = self.pinned_files.get(path) + return descriptor is not None and os.fstat(descriptor).st_nlink > 0 + + def release(self) -> None: + """Close the descriptors pinning snapshotted files.""" + descriptors = list(self.pinned_files.values()) + self.pinned_files.clear() + for descriptor in descriptors: + try: + os.close(descriptor) + except OSError: + pass + + def _read_xattrs(self, path: Path | int) -> dict[str, bytes] | None: + """Read a file's restorable extended attributes, or None if they cannot be read. + + Kept in memory rather than relying on the copy ``shutil.copystat()`` + puts on the snapshot, which it silently skips where the temporary + filesystem has no user attributes. + """ + if not _HAS_XATTRS: + return None + try: + return _restorable_xattrs(path, self) + except OSError as exc: + if exc.errno in _XATTRS_UNSUPPORTED: + return {} + return None + + def _remember_written(self, path: Path) -> None: + """Record the metadata the operation left on ``path``, if it is a regular file.""" + self.written_metadata.pop(path, None) + state = _current_state(path) + if state is None or not stat.S_ISREG(state[0]): + return + attributes = None + if _HAS_XATTRS: + try: + attributes = _restorable_xattrs(path) + except OSError: + pass + try: + flags = _entry_flags(path) + except (OSError, FileHelperError): + flags = None + self.written_metadata[path] = (state[0], state[4], attributes, flags) + + def metadata_changed(self, path: Path, state: tuple[int, ...] | None) -> bool: + """Whether ``path``, found as ``state``, has a mode, mtime, attribute or file flag the operation did not leave.""" + written = self.written_metadata.get(path) + if written is None or state is None or not stat.S_ISREG(state[0]): + return False + if (state[0], state[4]) != written[:2]: + return True + if written[3] is not None: + try: + flags = _entry_flags(path) + except (OSError, FileHelperError): + return True + if flags is None: + return True + if (flags ^ written[3]) & ~_UNCOMPARED_FLAGS: + return True + if written[2] is None: + return False + try: + return _restorable_xattrs(path) != written[2] + except OSError: + return True + def directory_created(self, path: Path) -> None: entry = path.lstat() self.created_directories.append((Path(os.path.abspath(path)), (entry.st_dev, entry.st_ino))) @@ -237,7 +558,37 @@ def observe(self, path: Path, before: bool, removal: bool = False) -> None: if path.exists() or path.is_symlink(): saved = self.backup / "writes" / str(len(self.changes)) saved.parent.mkdir(parents=True, exist_ok=True) - self._snapshot(path, saved) + entry = path.lstat() + # A file the operation is removing is recreated, never + # restored in place, so it is not pinned either. + restorable = stat.S_ISREG(entry.st_mode) and not removal + if restorable and os.name != "nt": + self._pin(path, entry) + try: + self._snapshot_with_headroom(path, saved) + if stat.S_ISREG(entry.st_mode): + if not restorable: + attributes = None + elif path in self.pinned_xattrs: + attributes = self.pinned_xattrs.pop(path) + else: + attributes = self._read_xattrs(path) + after = _entry_state(path) + if after[1:3] != (entry.st_dev, entry.st_ino): + self._unpin(path) + elif after != _stat_state(entry): + # Same file, but its size or times moved while it + # was copied: the snapshot may hold mixed bytes. + raise installer.IntegrationInstallError( + f"Integration output changed during the operation; refusing to overwrite {path}" + ) + elif restorable: + self._persist_xattrs(path, saved, attributes) + self._remember_original(path, entry, attributes) + except BaseException: + self._unpin(path) + self.pinned_xattrs.pop(path, None) + raise else: if not any(path == scope or scope in path.parents for scope in self.paths): raise installer.IntegrationInstallError( @@ -257,6 +608,12 @@ def observe(self, path: Path, before: bool, removal: bool = False) -> None: if not before: saved, _ = self.changes[path] self.changes[path] = (saved, _file_identity(path)) + # A repeated after-notification with no write since (as + # ``record_existing`` sends after ``write_file_and_record``) keeps + # the metadata the write left, so a mode changed in between is + # still someone else's edit. + if path in self.pending or path not in self.written_metadata: + self._remember_written(path) self.pending.discard(path) else: self.pending.add(path) @@ -274,11 +631,272 @@ def _prune_new_parents(root: Path, journal: _FileJournal, path: Path) -> None: parent = parent.parent +def _restore_file_in_place( + path: Path, saved: Path, is_original: Callable[[os.stat_result], bool] | None, + attributes: dict[str, bytes] | None, file_flags: int | None = None, + checked: tuple[int, ...] | None = None, +) -> str: + """Write a snapshot back into the file it was taken from. + + Unlinking and recreating the file would give it the restoring user as + owner and the directory's default permissions (on Windows, its inherited + access-control list), so a file the operation rewrote in place gets its + bytes, extended attributes, times and mode back through the same file. + + ``is_original`` tells whether a stat result is the snapshotted file; + None means the file cannot be restored in place. Returns + ``"untouched"``, having changed nothing, when ``path`` is no longer that + regular file (removed, or replaced by another file, a symlink + or a directory) or cannot be opened for writing; the caller then + recreates it. Returns ``"incomplete"`` when the bytes were restored but + some metadata could not be, safely or at all (another user's file, say), + and ``"restored"`` otherwise. ``checked`` is the ``_entry_state`` the + caller's content check saw; when given, a path that no longer holds that + entry, before or after the open, returns ``"modified"`` with nothing + written, so the caller keeps it as a conflict rather than recreating over + it. ``file_flags`` are the file's BSD flags when + snapshotted; Python has no descriptor form of ``chflags()``, so changed + flags are reported, not set back. A failed byte write raises. + """ + if is_original is None: + return "untouched" + try: + files = FileHelper(path.parent) + except (OSError, FileHelperError): + return "untouched" + with files: + try: + entry = files.stat(path.name) + except (OSError, FileHelperError): + return "untouched" + if checked is not None and _stat_state(entry) != checked: + return "modified" + if not is_original(entry): + return "untouched" + with ExitStack() as stack: + # Opened without truncating: nothing is written until the opened + # file is known to be the snapshotted one. + try: + descriptor = stack.enter_context(files.open_rewrite(path.name)) + except (OSError, FileHelperError): + return "untouched" + opened = os.fstat(descriptor) + # The whole entry, not just its identity: an in-place edit between + # the stat above and this open keeps the inode. Compared through a + # second path stat of the opened file, since a handle's stat is not + # a path stat on every platform: on Windows ``fstat`` reports the + # metadata-change time as ``st_ctime`` and a path stat the creation + # time. + if checked is not None: + try: + again = files.stat(path.name) + except (OSError, FileHelperError): + return "modified" + if not os.path.samestat(again, opened) or _stat_state(again) != checked: + return "modified" + if not is_original(opened): + return "untouched" + # Open the snapshot before truncating: one this process cannot read + # (a group-readable source another user owns, say) must raise with + # the live file, and every hard link to it, still intact. + with FileHelper(saved.parent) as backup, backup.open_read(saved.name) as incoming: + # Before reading the snapshot, which can move its access time. + original = os.fstat(incoming) + os.ftruncate(descriptor, 0) + _copy_descriptor(incoming, descriptor) + complete = _restore_metadata(descriptor, files, path.name, original, attributes) + if file_flags is not None: + current = getattr(os.fstat(descriptor), "st_flags", file_flags) + if (current ^ file_flags) & ~_UNCOMPARED_FLAGS: + complete = False + # Only now that the write handle is closed: on Windows closing it can + # move the last-write time again, after any time set while it was open. + # The check after setting the times also catches a path unlinked or + # replaced during the copy, which no longer names the restored file; + # whatever is there is left alone and reported. + if not _restore_times(files, path.name, opened, original): + complete = False + return "restored" if complete else "incomplete" + + +def _restore_times(files: FileHelper, name: str, restored: os.stat_result, original: os.stat_result) -> bool: + """Set the snapshot's times on the closed, restored file, then confirm they held. + + A fresh descriptor confirms ``name`` still names the restored file, and + the times are set through it, so a file renamed over the path meanwhile + is not touched. Windows has no descriptor form of ``os.utime``, so there + they go through ``files`` by path, while that descriptor keeps the file + from being renamed or replaced. + """ + times = (original.st_atime_ns, original.st_mtime_ns) + try: + with ExitStack() as stack: + try: + descriptor = stack.enter_context(files.open_read(name)) + except PermissionError: + # A write-only original: the restore itself opened it for writing. + descriptor = stack.enter_context(files.open_rewrite(name)) + current = os.fstat(descriptor) + if not os.path.samestat(current, restored): + return False + if (current.st_atime_ns, current.st_mtime_ns) != times: + if os.name == "nt": + files.utime(name, ns=times) + else: + futime(descriptor, ns=times) + final = files.stat(name) + except (OSError, FileHelperError): + return False + return os.path.samestat(final, restored) and final.st_mtime_ns == original.st_mtime_ns + + +def _copy_descriptor(source: int, destination: int) -> None: + """Copy the rest of ``source`` to ``destination`` through their descriptors.""" + while content := os.read(source, 65536): + _write_descriptor(destination, content) + + +def _write_descriptor(destination: int, content: bytes) -> None: + view = memoryview(content) + while view: + view = view[os.write(destination, view):] + + +def _copy_xattrs(attributes: dict[str, bytes], destination: int) -> None: + """Set captured attributes on a snapshot descriptor, skipping what it refuses. + + The refusals ``shutil.copystat`` ignores are ignored here too; the + captured values are kept in memory and in the sidecar regardless. + """ + ignored = _XATTRS_UNSUPPORTED | {errno.EPERM, errno.ENODATA, errno.EINVAL} + # The access ACL last: it sets the mode bits, and a read-only one would + # refuse the user attributes still to come. + for name, value in sorted(attributes.items(), key=lambda item: item[0] == _ACCESS_ACL): + try: + os.setxattr(destination, name, value) + except OSError as exc: + if exc.errno not in ignored: + raise + + +def _restore_metadata( + descriptor: int, files: FileHelper, name: str, original: os.stat_result, + attributes: dict[str, bytes] | None, +) -> bool: + """Restore a snapshot's extended attributes and mode onto the open, verified file. + + Extended attributes and, where ``os.fchmod`` exists, the mode go through + ``descriptor``. Elsewhere the mode is set through ``files`` relative to + the file's anchored parent without following a leaf link, so a path + swapped for a symlink since the open cannot redirect it; on Windows a + file Python opens cannot be renamed, replaced or deleted until it is + closed, so ``name`` still names the verified file while ``descriptor`` + is open. Times are set after the descriptor closes (``_restore_times``). + Values that already match are not set again, so a file the restoring + user may write but not otherwise modify is only refused what it actually + needs. + """ + complete = True + if _HAS_XATTRS: + # Before the mode: a read-only mode refuses user attributes, and an + # access ACL sets the group mode bits. + if attributes is None: + complete = False + else: + complete = _restore_xattrs(descriptor, attributes) + current = os.fstat(descriptor) + mode = stat.S_IMODE(original.st_mode) + if stat.S_IMODE(current.st_mode) != mode: + try: + if hasattr(os, "fchmod"): + os.fchmod(descriptor, mode) + else: + files.chmod(name, mode) + except (OSError, FileHelperError): + complete = False + return complete + + +def _restore_xattrs(descriptor: int, attributes: dict[str, bytes]) -> bool: + """Set a file's restorable attributes back, each one independently.""" + try: + live = _restorable_xattrs(descriptor) + except OSError as exc: + return exc.errno in _XATTRS_UNSUPPORTED and not attributes + complete = True + changes = [(name, None) for name in live.keys() - attributes.keys()] + changes += [(name, value) for name, value in attributes.items() if live.get(name) != value] + # The access ACL last: it sets the mode bits, and a read-only one would + # refuse the user attributes still to come. + changes.sort(key=lambda change: change[0] == _ACCESS_ACL) + for name, value in changes: + try: + if value is None: + os.removexattr(descriptor, name) + else: + os.setxattr(descriptor, name, value) + except OSError: + complete = False + return complete + + +def _recreated_xattrs_restored(path: Path, attributes: dict[str, bytes]) -> bool: + """Set captured attributes on a file just recreated from its snapshot. + + ``copy2`` copies only what the snapshot holds, and the snapshot's + filesystem may have dropped them; the captured ones are the record. + """ + try: + with FileHelper(path.parent) as files, files.open_read(path.name) as descriptor: + return _restore_xattrs(descriptor, attributes) + except (OSError, FileHelperError): + return False + + +def _entry_flags(path: Path) -> int | None: + """The BSD file flags of ``path`` itself, or None where the platform has none.""" + with FileHelper(path.parent) as files: + return getattr(files.stat(path.name), "st_flags", None) + + +def _current_state(path: Path) -> tuple[int, ...] | None: + """``_entry_state`` of ``path``, or None when nothing is there.""" + try: + return _entry_state(path) + except FileNotFoundError: + return None + + +def _still_has_identity(path: Path, identity: tuple[int, int] | None) -> bool: + if identity is None: + return False + try: + return _entry_state(path)[1:3] == identity + except OSError: + return False + + +def _snapshot_index(journal: _FileJournal, paths: list[Path]) -> str: + """Name the ``writes/`` snapshot of each of ``paths`` that has one.""" + named = [ + f"{journal.changes[path][0].relative_to(journal.backup).as_posix()} is {path}" + for path in paths if path in journal.changes and journal.changes[path][0] is not None + ] + return f" ({'; '.join(named)})" if named else "" + + def _restore_snapshots(root: Path, journal: _FileJournal) -> list[Path]: conflicts = [] for path, (saved, written_identity) in reversed(tuple(journal.changes.items())): journal.safe_path(path) + # The entry the content check below sees. Everything rollback does to + # the path afterwards first confirms it still holds this entry, so a + # replacement or edit made meanwhile is kept as a conflict. + checked = _current_state(path) current_identity = _file_identity(path) + if _current_state(path) != checked: + conflicts.append(path) + continue if path in journal.pending or any(path in pending.parents for pending in journal.pending): original_identity = _file_identity(saved) if saved is not None else None if saved is None and path not in journal.pending and current_identity == written_identity: @@ -297,6 +915,36 @@ def _restore_snapshots(root: Path, journal: _FileJournal) -> list[Path]: if path not in journal.pending and current_identity != written_identity: conflicts.append(path) continue + if path not in journal.pending and journal.metadata_changed(path, checked): + # Same bytes, but a mode, time or attribute changed after the + # operation's write: someone else's edit, so keep it. + conflicts.append(path) + continue + if saved is not None: + is_original = partial(journal.is_original, path) if path in journal.snapshotted_files else None + restored = _restore_file_in_place( + path, saved, is_original, journal.snapshotted_xattrs.get(path), + journal.snapshotted_flags.get(path), checked, + ) + if restored == "modified": + conflicts.append(path) + continue + if ( + restored == "incomplete" + or _still_has_identity(path, journal.unverified_files.get(path)) + or (restored == "untouched" and _still_has_identity(path, journal.snapshotted_files.get(path))) + ): + # A file still at its old inode that is not restored in place + # (unverified, or refusing to be opened for writing) was + # probably rewritten in place; recreating it below loses its + # owner, links and any metadata its snapshot could not hold. + journal.incomplete_restores.append(path) + if restored != "untouched": + continue + if _current_state(path) != checked: + # Replaced or edited since the content check: never delete it. + conflicts.append(path) + continue if path.is_dir() and not path.is_symlink(): shutil.rmtree(path) elif path.exists() or path.is_symlink(): @@ -309,6 +957,15 @@ def _restore_snapshots(root: Path, journal: _FileJournal) -> list[Path]: shutil.copytree(saved, path, symlinks=True) else: shutil.copy2(saved, path) + attributes = journal.snapshotted_xattrs.get(path) + # An empty set is restored too: it removes attributes the + # recreated file inherited, such as a default ACL's access ACL. + if ( + attributes is not None and not _recreated_xattrs_restored(path, attributes) + and path not in journal.incomplete_restores + ): + # The sidecar is then the only copy, so it is retained. + journal.incomplete_restores.append(path) else: _prune_new_parents(root, journal, path) _prune_new_directories(journal) @@ -438,12 +1095,21 @@ def _journalled( """Restore every observed write if the body raises. Sets ``outcome["retained"]`` when recovery snapshots are kept because - restoring them found conflicts or failed. ``initial`` is the census of - ``paths``, taken here when not given. + restoring them found conflicts, restored a file's contents without all of + its metadata (mode, times, extended attributes or BSD flags), or failed. + A conflict is a path whose contents, or mode, mtime or extended + attributes, differ from what the body left, or that is replaced while + rollback works on it; it is left as found. Captured extended attributes + are kept beside their snapshot as ``.xattrs.json``. + A file the body rewrote in place is restored in place; a file it replaced + or removed, one rollback cannot safely identify, and a directory are + recreated from their snapshots. ``initial`` is the census of ``paths``, + taken here when not given. """ if initial is None: initial = _initial_entries(paths) backup = Path(tempfile.mkdtemp(prefix="speckit-integration-rollback-")) + journal = None try: journal = _FileJournal(root, paths, backup, initial, tuple(home_scopes)) token = file_change_observer.set(journal.observe) @@ -460,13 +1126,23 @@ def _journalled( directory_creation_observer.reset(directory_token) directory_token = None conflicts = _restore_snapshots(root, journal) - outcome["retained"] = bool(conflicts) + incomplete = journal.incomplete_restores + outcome["retained"] = bool(conflicts or incomplete) if conflicts: console.print( "[yellow]Warning:[/yellow] Preserved concurrent edits or incomplete writes to " f"{escape(str(conflicts))}. Recovery snapshots retained at {escape(str(backup))}" + f"{escape(_snapshot_index(journal, conflicts))}" + ) + if incomplete: + console.print( + "[yellow]Warning:[/yellow] Could not fully restore " + f"{escape(str(incomplete))}: their contents, ownership, links, permissions, " + "timestamps, extended attributes or file flags may differ from the originals. " + f"Recovery snapshots retained at {escape(str(backup))}" + f"{escape(_snapshot_index(journal, incomplete))}" ) - except (OSError, installer.IntegrationInstallError) as restore_error: + except (OSError, FileHelperError, installer.IntegrationInstallError) as restore_error: outcome["retained"] = True if isinstance(operation_error, typer.Exit) and operation_error.__context__ is not None: # A command that reports its own failure exits; name the cause. @@ -483,6 +1159,8 @@ def _journalled( if directory_token is not None: directory_creation_observer.reset(directory_token) finally: + if journal is not None: + journal.release() if not outcome["retained"]: # Snapshots keep their source's modes, so make a read-only one # writable; a removal failure must not fail a committed operation. diff --git a/tests/specify_cli/integrations/test_command_upgrade.py b/tests/specify_cli/integrations/test_command_upgrade.py index 8ba95e6ba7..8d51b9dec7 100644 --- a/tests/specify_cli/integrations/test_command_upgrade.py +++ b/tests/specify_cli/integrations/test_command_upgrade.py @@ -2036,6 +2036,46 @@ def save(self, *args, **kwargs): assert _tree(project) == before +def test_builtin_upgrade_rollback_restores_a_rewritten_file_in_place(tmp_path, monkeypatch): + """Rollback writes the original bytes back into a file the upgrade rewrote. + + Recreating the file instead would give it the restoring user as owner and + the directory's default permissions, which on Windows replaces its + access-control list. A hard link to the original file sees the restored + bytes only if rollback wrote through that same file. + """ + project = _init_project(tmp_path, "claude") + skill = project / ".claude" / "skills" / "speckit-plan" / "SKILL.md" + skill.write_text("# user customization\n", encoding="utf-8") + if os.name != "nt": + skill.chmod(0o600) + mode = skill.stat().st_mode + witness = tmp_path / "witness" + os.link(skill, witness) + from specify_cli.integrations.claude import ClaudeIntegration + + real_setup = ClaudeIntegration.setup + written = [] + + def setup(self, *args, **kwargs): + real_setup(self, *args, **kwargs) + written.append(witness.read_text(encoding="utf-8")) + raise OSError("disk full") + + monkeypatch.setattr(ClaudeIntegration, "setup", setup) + + result = _run_in_project(project, ["integration", "upgrade", "claude", "--force"]) + + assert result.exit_code != 0 + assert "disk full" in result.output + # The upgrade rewrote the file through the same inode before failing. + assert written and written[0] != "# user customization\n" + assert skill.read_text(encoding="utf-8") == "# user customization\n" + assert os.path.samefile(skill, witness) + assert witness.read_text(encoding="utf-8") == "# user customization\n" + assert skill.stat().st_mode == mode + + def test_builtin_upgrade_journal_needs_no_trust_store_or_other_manifests(tmp_path, monkeypatch): """The journal adds no precondition a built-in upgrade did not already have.""" from specify_cli.integrations import installer diff --git a/tests/specify_cli/integrations/test_lifecycle.py b/tests/specify_cli/integrations/test_lifecycle.py index 87bdeb1e9c..d4d538ae2d 100644 --- a/tests/specify_cli/integrations/test_lifecycle.py +++ b/tests/specify_cli/integrations/test_lifecycle.py @@ -5,6 +5,7 @@ import json # noqa: F401 import os # noqa: F401 import shutil # noqa: F401 +import stat from pathlib import Path # noqa: F401 import pytest # noqa: F401 @@ -229,3 +230,1542 @@ def test_builtin_journal_removes_a_new_directory_whose_pending_write_never_lande raise OSError("disk full") assert sorted(path.name for path in project.iterdir()) == ["README.md"] + + +def test_builtin_journal_recreates_a_file_the_operation_replaced(tmp_path): + """A file swapped for a new one is restored as a file, never written through the new one.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import after_file_change, before_file_change + + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + witness = tmp_path / "witness" + os.link(target, witness) + replacement = tmp_path / "replacement" + replacement.write_text("generated\n", encoding="utf-8") + other = tmp_path / "other-link" + os.link(replacement, other) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + before_file_change(target) + os.replace(replacement, target) + after_file_change(target) + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "original\n" + assert not os.path.samefile(target, other) + assert other.read_text(encoding="utf-8") == "generated\n" + assert witness.read_text(encoding="utf-8") == "original\n" + + +def test_builtin_journal_recreates_and_reports_a_file_it_cannot_open_in_place(tmp_path, monkeypatch, capsys): + """A file rollback cannot open for writing is recreated from its snapshot, reported, and its snapshot kept.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + from specify_cli.file_helper import FileHelper + + real_open_rewrite = FileHelper.open_rewrite + + def refuse_target(self, path): + # Patched here, not at os.open: Windows opens through CreateFileW. + if Path(self.root) / path == target: + raise PermissionError("read-only") + return real_open_rewrite(self, path) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(target, "generated\n") + monkeypatch.setattr(FileHelper, "open_rewrite", refuse_target) + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "original\n" + assert _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +def test_builtin_journal_leaves_a_file_intact_when_its_snapshot_cannot_be_read(tmp_path, monkeypatch): + """An unreadable snapshot must not empty the live file or its hard links.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + link = tmp_path / "link" + os.link(target, link) + from specify_cli.file_helper import FileHelper + + real_open_read = FileHelper.open_read + + def refuse_snapshot(self, path): + if any(parent in backups for parent in (Path(self.root), *Path(self.root).parents)): + raise PermissionError("unreadable snapshot") + return real_open_read(self, path) + + with pytest.raises(Exception, match="rollback failed"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(target, "generated\n") + monkeypatch.setattr(FileHelper, "open_read", refuse_snapshot) + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "generated\n" + assert link.read_text(encoding="utf-8") == "generated\n" + for backup in backups: + shutil.rmtree(backup) + + +_INCOMPLETE_WARNING = "timestamps, extended attributes or file flags" + + +def _record_rollback_backups(monkeypatch): + from specify_cli.integrations import _lifecycle + + original_mkdtemp = _lifecycle.tempfile.mkdtemp + backups = [] + + def record_backup(*args, **kwargs): + path = original_mkdtemp(*args, **kwargs) + if kwargs.get("prefix") == "speckit-integration-rollback-": + backups.append(Path(path)) + return path + + monkeypatch.setattr(_lifecycle.tempfile, "mkdtemp", record_backup) + return backups + + +def test_builtin_journal_never_writes_a_different_file_open_returned(tmp_path, monkeypatch, capsys): + """A descriptor that is not the snapshotted file is neither truncated nor written.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + decoy = tmp_path / "decoy" + decoy.write_text("decoy\n", encoding="utf-8") + from contextlib import contextmanager + + from specify_cli.file_helper import FileHelper + + real_open_rewrite = FileHelper.open_rewrite + opened = [] + + @contextmanager + def open_decoy(self, path): + # Patched here, not at os.open: Windows opens through CreateFileW. + if Path(self.root) / path != target: + with real_open_rewrite(self, path) as descriptor: + yield descriptor + return + opened.append(path) + descriptor = os.open(decoy, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + try: + yield descriptor + finally: + os.close(descriptor) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(target, "generated\n") + monkeypatch.setattr(FileHelper, "open_rewrite", open_decoy) + raise OSError("disk full") + + assert opened + assert decoy.read_text(encoding="utf-8") == "decoy\n" + # A descriptor on another file means the path cannot be trusted, so it is + # kept as a conflict, with its snapshot, rather than recreated. + assert target.read_text(encoding="utf-8") == "generated\n" + assert not os.path.samefile(target, decoy) + assert "Preserved concurrent edits" in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + for backup in backups: + shutil.rmtree(backup) + + +def test_builtin_journal_keeps_restoring_after_a_metadata_refusal(tmp_path, monkeypatch, capsys): + """A file whose times cannot be set still gets its bytes, and later entries are restored.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import make_directories, write_text + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + first = project / ".specify" / "templates" / "spec.md" + first.parent.mkdir(parents=True) + first.write_text("first original\n", encoding="utf-8") + created = project / ".specify" / "templates" / "new" + refused = project / ".specify" / "templates" / "plan.md" + refused.write_text("refused original\n", encoding="utf-8") + refused_inode = refused.stat().st_ino + from specify_cli.file_helper import FileHelper + + real_utime = FileHelper.utime + real_futime = _lifecycle.futime + + def refuse_refused(self, path, **kwargs): + if Path(self.root) / path == refused: + raise PermissionError("not the owner") + return real_utime(self, path, **kwargs) + + def refuse_refused_descriptor(descriptor, **kwargs): + if os.fstat(descriptor).st_ino == refused_inode: + raise PermissionError("not the owner") + return real_futime(descriptor, **kwargs) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(first, "first generated\n") + make_directories(created) + write_text(created / "file.md", "new\n") + # Restored first, as rollback runs newest first. + write_text(refused, "refused generated\n") + monkeypatch.setattr(FileHelper, "utime", refuse_refused) + monkeypatch.setattr(_lifecycle, "futime", refuse_refused_descriptor) + raise OSError("disk full") + + assert refused.read_text(encoding="utf-8") == "refused original\n" + assert refused.stat().st_ino == refused_inode + assert first.read_text(encoding="utf-8") == "first original\n" + assert not created.exists() + assert _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX modes and symlinks") +def test_builtin_journal_never_restores_metadata_through_a_path_swapped_for_a_symlink( + tmp_path, monkeypatch, capsys, +): + """Times set by path after the copy cannot be redirected by a path swapped for a symlink.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + target.chmod(0o600) + os.utime(target, ns=(1_000_000_000, 1_000_000_000)) + witness = tmp_path / "witness" + os.link(target, witness) + victim = tmp_path / "victim" + victim.write_text("victim\n", encoding="utf-8") + victim.chmod(0o644) + victim_before = victim.stat() + real_copy = _lifecycle._copy_descriptor + + def copy_then_swap(source, destination): + # Once the bytes are back, swap the path for a symlink, so any + # metadata restored by path from here on lands on the victim. + real_copy(source, destination) + target.unlink() + target.symlink_to(victim) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(target, "generated\n") + monkeypatch.setattr(_lifecycle, "_copy_descriptor", copy_then_swap) + raise OSError("disk full") + + victim_after = victim.stat() + assert stat.S_IMODE(victim_after.st_mode) == 0o644 + assert victim_after.st_mtime_ns == victim_before.st_mtime_ns + assert victim.read_text(encoding="utf-8") == "victim\n" + assert witness.read_text(encoding="utf-8") == "original\n" + # The times were not restored by path through the swapped-in symlink. + assert witness.stat().st_mtime_ns != 1_000_000_000 + assert _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +@pytest.mark.skipif(os.name != "nt", reason="Windows sharing semantics") +def test_windows_open_file_cannot_be_replaced_while_rollback_holds_it(tmp_path): + """Rollback sets times by path on Windows only while its verified handle pins that path.""" + parent = tmp_path / "parent" + parent.mkdir() + target = parent / "plan.md" + target.write_text("original\n", encoding="utf-8") + replacement = tmp_path / "replacement" + replacement.write_text("replacement\n", encoding="utf-8") + descriptor = os.open(target, os.O_WRONLY | getattr(os, "O_BINARY", 0)) + try: + with pytest.raises(PermissionError): + os.replace(replacement, target) + with pytest.raises(PermissionError): + os.remove(target) + with pytest.raises(PermissionError): + os.rename(parent, tmp_path / "moved") + os.utime(target, ns=(1_000_000_000, 2_000_000_000)) + os.chmod(target, stat.S_IREAD | stat.S_IWRITE) + finally: + os.close(descriptor) + assert target.stat().st_mtime_ns == 2_000_000_000 + assert target.read_text(encoding="utf-8") == "original\n" + + +def _user_xattrs(path): + return { + name: os.getxattr(path, name) + for name in os.listxattr(path) + if name.startswith("user.") + } + + +@pytest.mark.skipif(not hasattr(os, "setxattr"), reason="no extended-attribute API in the os module") +def test_builtin_journal_restores_extended_attributes_in_place(tmp_path): + """Attributes a journalled copy2() put onto an existing file are put back.""" + import errno + + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import after_file_change, before_file_change + + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + try: + os.setxattr(target, "user.origin", b"original") + except OSError as exc: + if exc.errno in (errno.ENOTSUP, errno.EOPNOTSUPP): + pytest.skip("filesystem has no user extended attributes") + raise + os.setxattr(target, "user.kept", b"kept") + witness = tmp_path / "witness" + os.link(target, witness) + source = tmp_path / "source" + source.write_text("generated\n", encoding="utf-8") + os.setxattr(source, "user.origin", b"generated") + os.setxattr(source, "user.added", b"added") + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + before_file_change(target) + shutil.copy2(source, target) + after_file_change(target) + assert _user_xattrs(target)["user.added"] == b"added" + raise OSError("disk full") + + assert os.path.samefile(target, witness) + assert target.read_text(encoding="utf-8") == "original\n" + assert _user_xattrs(target) == {"user.origin": b"original", "user.kept": b"kept"} + + +@pytest.mark.skipif(not hasattr(os, "setxattr"), reason="no extended-attribute API in the os module") +def test_builtin_journal_restores_other_attributes_after_one_is_refused(tmp_path, monkeypatch, capsys): + """One refused attribute is reported without leaving the others changed.""" + import errno + + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import after_file_change, before_file_change + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + try: + os.setxattr(target, "user.a", b"original") + except OSError as exc: + if exc.errno in (errno.ENOTSUP, errno.EOPNOTSUPP): + pytest.skip("filesystem has no user extended attributes") + raise + os.setxattr(target, "user.z", b"original") + source = tmp_path / "source" + source.write_text("generated\n", encoding="utf-8") + for name in ("user.a", "user.z", "user.added"): + os.setxattr(source, name, b"generated") + real_setxattr = os.setxattr + + def refuse_a(target, name, *args, **kwargs): + if name == "user.a": + raise PermissionError("refused") + return real_setxattr(target, name, *args, **kwargs) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + before_file_change(target) + shutil.copy2(source, target) + after_file_change(target) + monkeypatch.setattr(_lifecycle.os, "setxattr", refuse_a) + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "original\n" + assert _user_xattrs(target) == {"user.a": b"generated", "user.z": b"original"} + assert _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +def test_builtin_journal_never_writes_through_a_replacement_that_reuses_the_inode(tmp_path): + """An unlinked original cannot lend its inode to a replacement while rollback relies on it.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import after_file_change, before_file_change + + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + other = tmp_path / "other-link" + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + before_file_change(target) + # No other link keeps the original alive, so without a pin its + # inode is free for the replacement created straight after. + target.unlink() + target.write_text("generated\n", encoding="utf-8") + os.link(target, other) + after_file_change(target) + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "original\n" + assert not os.path.samefile(target, other) + assert other.read_text(encoding="utf-8") == "generated\n" + + +_PINS_FILES = os.name != "nt" + +@pytest.mark.skipif(not _PINS_FILES, reason="Windows files are never pinned") +def test_builtin_journal_recreates_and_reports_a_file_it_could_not_pin(tmp_path, monkeypatch, capsys): + """A file without a pin is recreated from its snapshot, not written in place, and reported.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + backups = _record_rollback_backups(monkeypatch) + monkeypatch.setattr(_lifecycle, "_MAX_PINNED_FILES", 0) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + witness = tmp_path / "witness" + os.link(target, witness) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + write_text(target, "generated\n") + raise OSError("disk full") + + assert target.read_text(encoding="utf-8") == "original\n" + assert not os.path.samefile(target, witness) + assert witness.read_text(encoding="utf-8") == "generated\n" + assert _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +@pytest.mark.skipif(not _PINS_FILES or not os.path.isdir("/dev/fd"), reason="no pins, or no /dev/fd to count them") +@pytest.mark.parametrize("fails", [True, False]) +def test_builtin_journal_releases_its_pins(tmp_path, fails): + """The descriptors pinning snapshotted files close whether the operation fails or commits.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import write_text + + project = tmp_path / "plain" + targets = [project / ".specify" / "templates" / f"{name}.md" for name in ("plan", "spec")] + targets[0].parent.mkdir(parents=True) + for target in targets: + target.write_text("original\n", encoding="utf-8") + before = len(os.listdir("/dev/fd")) + + try: + with _lifecycle.builtin_journal(project, "claude", {}): + for target in targets: + write_text(target, "generated\n") + assert len(os.listdir("/dev/fd")) >= before + len(targets) + if fails: + raise OSError("disk full") + except OSError: + assert fails + + assert len(os.listdir("/dev/fd")) == before + expected = "original\n" if fails else "generated\n" + assert all(target.read_text(encoding="utf-8") == expected for target in targets) + + +@pytest.mark.skipif( + not hasattr(os, "chflags") or not hasattr(stat, "UF_NODUMP"), reason="no BSD file flags", +) +@pytest.mark.parametrize( + "source_flags", [0, stat.UF_NODUMP if hasattr(stat, "UF_NODUMP") else 0], ids=["cleared", "kept"], +) +def test_builtin_journal_reports_file_flags_it_cannot_restore(tmp_path, monkeypatch, capsys, source_flags): + """BSD flags a journalled copy2() cleared are reported, with the snapshots kept.""" + from specify_cli.integrations import _lifecycle + from specify_cli.integrations._file_changes import after_file_change, before_file_change + + backups = _record_rollback_backups(monkeypatch) + project = tmp_path / "plain" + target = project / ".specify" / "templates" / "plan.md" + target.parent.mkdir(parents=True) + target.write_text("original\n", encoding="utf-8") + try: + os.chflags(target, stat.UF_NODUMP) + except OSError: + pytest.skip("filesystem refuses UF_NODUMP") + witness = tmp_path / "witness" + os.link(target, witness) + source = tmp_path / "source" + source.write_text("generated\n", encoding="utf-8") + os.chflags(source, source_flags) + + with pytest.raises(OSError, match="disk full"): + with _lifecycle.builtin_journal(project, "claude", {}): + before_file_change(target) + shutil.copy2(source, target) + after_file_change(target) + assert target.stat().st_flags & stat.UF_NODUMP == source_flags + raise OSError("disk full") + + assert os.path.samefile(target, witness) + assert target.read_text(encoding="utf-8") == "original\n" + warned = _INCOMPLETE_WARNING in " ".join(capsys.readouterr().out.split()) + if source_flags: + assert not warned + assert backups and not backups[0].exists() + else: + assert warned + assert len(backups) == 1 and backups[0].is_dir() + shutil.rmtree(backups[0]) + + +_ACCESS_ACL = "system.posix_acl_access" + + +def _access_acl(uid: int, owner: int = 6) -> bytes: + """A POSIX access ACL granting ``uid`` read access, with mask and mode bits ``owner``-r--r--.""" + import struct + + undefined = 0xFFFFFFFF + entries = [(0x01, owner, undefined), (0x02, 4, uid), (0x04, 4, undefined), (0x10, 4, undefined), + (0x20, 4, undefined)] + return struct.pack(" fail_after: + raise OSError(errno.EIO, "I/O error") + return real_write(fd, bytes(data[:3])) + + monkeypatch.setattr(os, "write", write) + return calls + + +def test_rewrite_descriptor_retries_short_writes(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + calls = _short_writes(monkeypatch) + FileHelper.rewrite_descriptor(fd, b"replacement\n") + monkeypatch.undo() + assert len(calls) > 1 + assert target.read_bytes() == b"replacement\n" + + +def test_create_private_bytes_retries_short_writes(tmp_path, monkeypatch): + calls = _short_writes(monkeypatch) + with FileHelper(tmp_path) as helper: + helper.create_private_bytes("backup", b"private content\n") + monkeypatch.undo() + assert len(calls) > 1 + assert (tmp_path / "backup").read_bytes() == b"private content\n" + + +def test_create_private_bytes_removes_its_file_after_a_short_write_then_an_error(tmp_path, monkeypatch): + _short_writes(monkeypatch, fail_after=1) + with FileHelper(tmp_path) as helper: + with pytest.raises(OSError, match="I/O error"): + helper.create_private_bytes("backup", b"private content\n") + monkeypatch.undo() + assert not (tmp_path / "backup").exists()