diff --git a/design/file-helper.md b/design/file-helper.md index b9fca560b7..488514aaa3 100644 --- a/design/file-helper.md +++ b/design/file-helper.md @@ -250,6 +250,33 @@ 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. The + root is checked against the one established on construction: on POSIX by + path, after a no-follow `lstat` shows it is still that directory, and on + Windows through a non-reparse handle. A missing root raises and a root + replaced by a link or another directory is refused. The POSIX root check is + not atomic, since querying `.` under a descriptor would also need search + permission: a root swapped for a link after the check can be answered for its + target. On POSIX 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. + On Windows, `os.access` checks only existence and the read-only attribute, + not the DACL, so `W_OK` can be granted where the DACL denies writing. 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 +299,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 the file + this call created, best effort: 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 +377,31 @@ 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, permission bits, ACL and + hard links. POSIX may clear the set-user-ID and set-group-ID bits when the + caller writes or truncates through it, as for any unprivileged write; the + helper keeps that OS behaviour and does not restore them. 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. +- `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. Like + any write, it may clear the set-user-ID and set-group-ID bits on POSIX, and + they are not restored. 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,10 +537,11 @@ 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 -can redirect those opens; they do not have the read path's parent-relative -handle protection. +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` and `access` query their leaf the same way. +Attribute-only reparse updates can redirect those opens and queries; they do not have the read path's +parent-relative handle protection. The helper does not constrain subprocesses or third-party code. Existing safe-write mechanisms informed this helper, but existing shared 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..720d1202a5 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, ) @@ -33,6 +34,99 @@ _POSIX_OPEN = os.open +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: """Normalize Windows extended drive/UNC spellings for comparison only.""" raw = str(path) @@ -381,6 +475,78 @@ 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 on POSIX; on Windows it reflects only existence + and the read-only attribute, not the DACL. It is advisory: act through a + descriptor and handle its errors. On POSIX the root is checked by path + after confirming it is still the established root, so a root swapped for + a link in between can be answered for its target. + """ + destination = self._path(path) + if os.name == "nt": + # Pin the hierarchy as ``stat`` does; Windows ``os.access`` has no ``dir_fd``. + # The root's own handle refuses a root since replaced by a reparse point. + 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) + if destination == self._canonical_root: + # Check the entry itself, not ``.`` under a descriptor, which would also + # need search permission. A missing root raises; one replaced by a link + # or another directory is refused rather than followed. + current = os.stat(destination, follow_symlinks=False) + if stat.S_ISLNK(current.st_mode): + raise OSError(errno.ELOOP, "The root was replaced by a link", str(destination)) + if not os.path.samestat(self._root_stat, current): + raise FileHelperError(f"Established root changed: {destination}") + return os.access(destination, mode) + 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: @@ -582,6 +748,114 @@ 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 the file this call created, best effort: + the name is unlinked only if it still has the created file's identity, but + that check is not atomic with the unlink, so a file another process swaps + in between the two can be removed instead. + """ + 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 +894,53 @@ 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, permission bits + and links are unchanged. On POSIX, the caller's write or truncate may clear + the set-user-ID and set-group-ID bits, as any unprivileged write does; the + helper keeps that behaviour and does not restore them. + """ + 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. On POSIX the + write may clear the set-user-ID and set-group-ID bits; they are not + restored. 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 +950,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 +958,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: diff --git a/tests/test_file_helper.py b/tests/test_file_helper.py index 1448be9121..b150a8f163 100644 --- a/tests/test_file_helper.py +++ b/tests/test_file_helper.py @@ -776,7 +776,8 @@ def denied(*args, **kwargs): raise PermissionError("denied") if os.name == "nt": - def denied_windows(path): + def denied_windows(path, *, create=True): + assert create assert path == root / "new" calls.append(path) raise PermissionError("denied") diff --git a/tests/test_file_helper_overwrite.py b/tests/test_file_helper_overwrite.py index 2a785a32d5..6dfb6f9a24 100644 --- a/tests/test_file_helper_overwrite.py +++ b/tests/test_file_helper_overwrite.py @@ -540,7 +540,8 @@ def pin(path, *, directory): events.append(("unpin", path)) @contextmanager - def open_leaf(path): + def open_leaf(path, *, create=True): + assert create assert active == [tmp_path, parent] assert leaf.read_text() == "old" fd = os.open(path, os.O_WRONLY) @@ -582,12 +583,12 @@ def test_native_windows_overwrite_holds_every_parent_and_leaf(tmp_path, monkeypa parents_checked = [] @contextmanager - def open_while_pinned(path): + def open_while_pinned(path, *, create=True): for directory in (root, parent): with pytest.raises(PermissionError): directory.rename(directory.with_name(directory.name + "-moved")) parents_checked.append(directory) - with open_leaf(path) as fd: + with open_leaf(path, create=create) as fd: yield fd def truncate(fd, length): @@ -630,11 +631,11 @@ def test_native_windows_leaf_swap_at_open_never_follows_new_link( original = file_helper._windows_overwrite_fd @contextmanager - def swap(path): + def swap(path, *, create=True): if existing: leaf.rename(root / "original") leaf.symlink_to(outside) - with original(path) as fd: + with original(path, create=create) as fd: yield fd monkeypatch.setattr(file_helper, "_windows_overwrite_fd", swap) diff --git a/tests/test_file_helper_rewrite.py b/tests/test_file_helper_rewrite.py new file mode 100644 index 0000000000..a5374f5b57 --- /dev/null +++ b/tests/test_file_helper_rewrite.py @@ -0,0 +1,1339 @@ +"""Public in-place byte rewrite, owner-only creation and stat on FileHelper.""" + +import errno +import os +import shutil +import stat +import subprocess +import sys +import types +from contextlib import contextmanager + +import pytest + +from specify_cli import _file_handles +from specify_cli.file_helper import ( + FileHelper, FileHelperError, SymlinkDeniedError, UnsupportedPathError, +) + + +REL = "parent/file" +# What open(O_NOFOLLOW | O_DIRECTORY) of a symlink raises: Linux/macOS, FreeBSD, NetBSD. +_NOFOLLOW_REFUSALS = { + errno.ELOOP, errno.ENOTDIR, errno.EMLINK, getattr(errno, "EFTYPE", errno.ELOOP), +} + + +def _symlinks_available(tmp_path): + probe = tmp_path / "probe" + try: + probe.symlink_to(tmp_path, target_is_directory=True) + probe.unlink() + except (OSError, NotImplementedError) as exc: + pytest.skip(f"Symlink creation unavailable: {exc}") + + +def _seed(tmp_path, content=b"0123456789"): + path = tmp_path / REL + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(content) + return path + + +# stat + + +def test_stat_matches_the_entry(tmp_path): + path = _seed(tmp_path) + with FileHelper(tmp_path) as files: + info = files.stat(REL) + native = path.stat() + assert (info.st_dev, info.st_ino, info.st_size) == (native.st_dev, native.st_ino, 10) + assert stat.S_ISREG(info.st_mode) + + +def test_stat_reports_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + assert stat.S_ISDIR(files.stat("parent").st_mode) + + +def test_stat_of_a_missing_entry_raises(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.stat("missing") + + +def test_stat_refuses_a_symlink_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + files.stat("link") + with FileHelper(tmp_path, allow_symlinks=True) as files: + assert files.stat("link").st_ino == path.stat().st_ino + + +def test_stat_refuses_a_path_outside_the_root(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(ValueError): + files.stat("../outside") + + +# access and canonical_root + + +def test_access_grants_an_accessible_entry(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK | os.W_OK) + assert files.access("parent", os.X_OK) + assert files.access(tmp_path, os.W_OK) + + +@pytest.mark.skipif(os.name == "nt", reason="the retained root handle withholds delete sharing") +def test_access_refuses_a_root_replaced_by_another_directory(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.mkdir() + with pytest.raises(FileHelperError): + files.access(".", os.R_OK) + + +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX permissions enforced for the current user", +) +def test_access_refuses_what_the_mode_denies(tmp_path): + path = _seed(tmp_path) + path.chmod(0o444) + try: + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK) + assert not files.access(REL, os.W_OK) + finally: + path.chmod(0o644) + + +@pytest.mark.skipif(os.name != "nt", reason="the read-only attribute is Windows-only") +def test_access_reports_the_windows_read_only_attribute(tmp_path): + path = _seed(tmp_path) + path.chmod(stat.S_IREAD) + try: + with FileHelper(tmp_path) as files: + assert not files.access(REL, os.W_OK) + finally: + path.chmod(stat.S_IREAD | stat.S_IWRITE) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX checks through the parent descriptor") +def test_access_makes_a_plain_faccessat(tmp_path, monkeypatch): + # Without faccessat2, libc emulates AT_SYMLINK_NOFOLLOW from mode bits. + _seed(tmp_path) + calls = [] + real_access = os.access + + def access(path, mode, **kwargs): + calls.append(kwargs) + return real_access(path, mode, **kwargs) + + monkeypatch.setattr(os, "access", access) + monkeypatch.setattr(os, "supports_dir_fd", os.supports_dir_fd | {access}) + monkeypatch.setattr(os, "supports_follow_symlinks", os.supports_follow_symlinks - {real_access}) + with FileHelper(tmp_path) as files: + assert files.access(REL, os.R_OK) + assert len(calls) == 1 + assert "dir_fd" in calls[0] and "follow_symlinks" not in calls[0] + + +def test_access_of_a_missing_entry_raises(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.access("missing", os.R_OK) + + +def test_access_refuses_a_symlink_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + files.access("link", os.R_OK) + with FileHelper(tmp_path, allow_symlinks=True) as files: + assert files.access("link", os.R_OK) + + +def test_access_refuses_a_path_outside_the_root(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(ValueError): + files.access("../outside", os.R_OK) + + +def test_canonical_root_resolves_a_root_alias(tmp_path): + _symlinks_available(tmp_path) + real = tmp_path / "real" + real.mkdir() + alias = tmp_path / "alias" + alias.symlink_to(real, target_is_directory=True) + with FileHelper(alias) as files: + assert files.root == alias + assert files.canonical_root == real.resolve() + + +# open_rewrite + + +def test_open_rewrite_writes_in_place_without_truncating(tmp_path): + path = _seed(tmp_path) + inode = path.stat().st_ino + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.lseek(fd, 0, os.SEEK_CUR) == 0 + assert os.fstat(fd).st_size == 10 + os.write(fd, b"ab\r\n") + assert path.read_bytes() == b"ab\r\n456789" + assert path.stat().st_ino == inode + + +def test_open_rewrite_keeps_the_mode(tmp_path): + path = _seed(tmp_path) + path.chmod(0o640) + before = stat.S_IMODE(path.stat().st_mode) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + os.ftruncate(fd, 0) + os.write(fd, b"new") + assert path.read_bytes() == b"new" + assert stat.S_IMODE(path.stat().st_mode) == before + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX set-user-ID and set-group-ID bits") +def test_open_rewrite_leaves_setid_clearing_to_the_os(tmp_path): + # POSIX lets a write by a process without privilege clear these bits. The + # helper keeps that behaviour rather than restoring them: its result must + # match a plain write to an identical file, with permission bits unchanged. + path = _seed(tmp_path) + control = tmp_path / "control" + control.write_bytes(path.read_bytes()) + for target in (path, control): + target.chmod(0o6750) + before = stat.S_IMODE(path.stat().st_mode) + if not before & (stat.S_ISUID | stat.S_ISGID): + pytest.skip("The filesystem did not keep the set-user-ID or set-group-ID bit") + assert stat.S_IMODE(control.stat().st_mode) == before + + fd = os.open(control, os.O_WRONLY) + try: + os.write(fd, b"new") + os.ftruncate(fd, 3) + finally: + os.close(fd) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + FileHelper.rewrite_descriptor(fd, b"new") + + after = stat.S_IMODE(path.stat().st_mode) + assert path.read_bytes() == b"new" + assert after & 0o777 == before & 0o777 + assert after == stat.S_IMODE(control.stat().st_mode) + + +def test_open_rewrite_closes_the_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files: + with files.open_rewrite(REL) as fd: + pass + with pytest.raises(OSError) as raised: + os.fstat(fd) + assert raised.value.errno == errno.EBADF + + +def test_open_rewrite_never_creates(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not (tmp_path / REL).exists() + + +def test_open_rewrite_does_not_create_a_leaf_removed_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path) + original = FileHelper._overwrite_descriptor + + @contextmanager + def remove_first(self, destination, **kwargs): + path.unlink() + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", remove_first) + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + with files.open_rewrite(REL): + pass + assert not path.exists() + + +def test_open_rewrite_refuses_a_directory(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite("parent"): + pass + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_open_rewrite_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._overwrite_descriptor + + @contextmanager + def swap_first(self, destination, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + with files.open_rewrite(REL) as fd: + os.write(fd, b"written") + assert raised.value.errno in _NOFOLLOW_REFUSALS + assert (outside / "file").read_bytes() == b"outside" + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_fifo_without_blocking(tmp_path): + (tmp_path / "parent").mkdir() + os.mkfifo(tmp_path / REL) + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + pass + + +def test_open_rewrite_refuses_a_symlinked_leaf_unless_allowed(tmp_path): + _symlinks_available(tmp_path) + path = _seed(tmp_path) + (tmp_path / "link").symlink_to(path) + with FileHelper(tmp_path) as files, pytest.raises(SymlinkDeniedError): + with files.open_rewrite("link"): + pass + with FileHelper(tmp_path, allow_symlinks=True) as files, files.open_rewrite("link") as fd: + os.write(fd, b"ab") + assert (tmp_path / "link").is_symlink() + assert path.read_bytes() == b"ab23456789" + + +# create_private_bytes + + +def test_create_private_bytes_creates_exclusively(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"first") + with pytest.raises(FileExistsError): + files.create_private_bytes(REL, b"second") + assert (tmp_path / REL).read_bytes() == b"first" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") +def test_create_private_bytes_is_owner_only(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert stat.S_IMODE((tmp_path / REL).stat().st_mode) & 0o077 == 0 + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX ownership") +def test_create_private_bytes_refuses_a_file_owned_by_another_user(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + monkeypatch.setattr(os, "geteuid", lambda: os.stat(tmp_path).st_uid + 1) + with FileHelper(tmp_path) as files, pytest.raises(PermissionError) as raised: + files.create_private_bytes(REL, b"private") + assert "owned by uid" in str(raised.value) + assert not (tmp_path / REL).exists() + + +def test_create_private_bytes_needs_an_existing_parent(tmp_path): + with FileHelper(tmp_path) as files, pytest.raises(FileNotFoundError): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / "parent").exists() + + +def test_create_private_bytes_refuses_a_dangling_link(tmp_path): + _symlinks_available(tmp_path) + (tmp_path / "parent").mkdir() + (tmp_path / REL).symlink_to(tmp_path / "target") + with FileHelper(tmp_path, allow_symlinks=True) as files, pytest.raises(FileExistsError): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / "target").exists() + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_create_private_bytes_refuses_a_symlinked_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + project = tmp_path / "project" + project.mkdir() + (project / "parent").symlink_to(outside) + with FileHelper(project) as files, pytest.raises(SymlinkDeniedError): + files.create_private_bytes(REL, b"secret") + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_create_private_bytes_refuses_a_parent_swapped_for_a_symlink(tmp_path, monkeypatch): + outside = tmp_path / "outside" + outside.mkdir() + parent = tmp_path / "parent" + parent.mkdir() + original = FileHelper._creation_directory + + @contextmanager + def swap_first(self, directory): + parent.rename(tmp_path / "moved") + parent.symlink_to(outside, target_is_directory=True) + with original(self, directory) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_creation_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.create_private_bytes(REL, b"secret") + assert raised.value.errno in _NOFOLLOW_REFUSALS + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_create_private_bytes_refuses_a_junctioned_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + project = tmp_path / "project" + project.mkdir() + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], + check=True, capture_output=True, + ) + with FileHelper(project) as files, pytest.raises(UnsupportedPathError): + files.create_private_bytes(REL, b"secret") + assert not list(outside.iterdir()) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("step", ["write", "fsync", "close"]) +def test_posix_create_private_bytes_uses_one_descriptor_and_removes_a_partial_file( + tmp_path, monkeypatch, step +): + # Reopening the file by name could block on a FIFO swapped in for it. + (tmp_path / "parent").mkdir() + real_open, real_step = os.open, getattr(os, step) + leaf: list[int] = [] + live: set[int] = set() + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + live.add(fd) + return fd + + def fail(fd, *args): + if fd not in live: + return real_step(fd, *args) + if step == "close": + # Its number may be reused once closed. + live.discard(fd) + real_step(fd) + raise OSError("disk full") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, step, fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert len(leaf) == 1 + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_keeps_a_replacement_it_did_not_create(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def replace_then_fail(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + (tmp_path / REL).unlink() + (tmp_path / REL).write_bytes(b"someone else's") + raise OSError("disk full") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", replace_then_fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).read_bytes() == b"someone else's" + # The caller is told the name was left, rather than cleanup failing silently. + assert any( + "Left file" in note and "not removed" in note for note in raised.value.__notes__ + ) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_flushes_the_file_and_its_directory(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_open, real_fsync, real_creation = os.open, os.fsync, FileHelper._creation_directory + leaf: list[int] = [] + pinned: list[int] = [] + synced: list[tuple[int, bool]] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + @contextmanager + def creation_directory(self, directory): + with real_creation(self, directory) as anchored: + pinned.append(anchored) + yield anchored + + def fsync(fd): + synced.append((fd, stat.S_ISDIR(os.fstat(fd).st_mode))) + return real_fsync(fd) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "fsync", fsync) + monkeypatch.setattr(FileHelper, "_creation_directory", creation_directory) + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert len(leaf) == 1 and (leaf[0], False) in synced + # The pinned descriptor may be O_PATH, which fsync rejects, so a readable one is used. + directories = [fd for fd, is_dir in synced if is_dir] + assert len(directories) == 1 and directories[0] not in pinned + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_succeeds_when_the_directory_cannot_be_flushed( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def fsync(fd): + if stat.S_ISDIR(os.fstat(fd).st_mode): + raise OSError(errno.EBADF, "Bad file descriptor") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(os.name != "nt", reason="Windows creation path") +def test_windows_create_private_bytes_removes_a_partial_file(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + created: list[int] = [] + real_create = _file_handles._windows_create_private_fd + + def create(path): + fd = real_create(path) + created.append(fd) + return fd + + def fsync(fd): + if fd in created: + raise OSError("disk full") + return real_fsync(fd) + + from specify_cli import file_helper + + monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert not (tmp_path / REL).exists() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows creation path") +def test_windows_create_private_bytes_leaves_no_file_if_no_descriptor_is_made( + tmp_path, monkeypatch +): + import msvcrt + + def fail(handle, flags): + raise OSError("too many open files") + + (tmp_path / "parent").mkdir() + monkeypatch.setattr(msvcrt, "open_osfhandle", fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="too many open files"): + files.create_private_bytes(REL, b"content") + assert not (tmp_path / REL).exists() + monkeypatch.undo() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + assert (tmp_path / REL).read_bytes() == b"content" + + +def _simulate_windows_create(monkeypatch, calls, *, marked=True, volume_flags=0x8): + """Fake the Windows calls ``_windows_create_private_fd`` makes, so it runs everywhere.""" + import ctypes + + class Attributes(ctypes.Structure): + _fields_ = [("nLength", ctypes.c_ulong), ("descriptor", ctypes.c_void_p), + ("inherit", ctypes.c_int)] + + class Kernel: + def CreateFileW(self, path, access, share, attributes, disposition, flags, template): + calls.append(("CreateFileW", access, share, disposition)) + return 1234 + + def GetVolumeInformationByHandleW(self, handle, *args): + args[4]._obj.value = volume_flags # lpFileSystemFlags + return 1 + + def SetFileInformationByHandle(self, handle, kind, info, size): + calls.append(("SetFileInformationByHandle", handle, kind, bytes(info._obj))) + if marked is None: + raise ctypes.ArgumentError("bad argument") + return int(marked) + + def CloseHandle(self, handle): + calls.append(("CloseHandle", handle)) + return 1 + + def LocalFree(self, pointer): + return None + + class Advapi: + def ConvertStringSecurityDescriptorToSecurityDescriptorW(self, *args): + return 1 + + def open_osfhandle(handle, flags): + calls.append(("open_osfhandle", handle)) + raise OSError("too many open files") + + monkeypatch.setattr( + _file_handles, "_windows_security_api", lambda: (Kernel(), Advapi(), Attributes) + ) + monkeypatch.setattr(_file_handles, "_windows_owner_only_sddl", lambda: "O:S-1-0D:P") + monkeypatch.setattr(ctypes, "get_last_error", lambda: 5, raising=False) + monkeypatch.setattr(ctypes, "WinError", lambda code=None: OSError(code, "denied"), raising=False) + monkeypatch.setitem(sys.modules, "msvcrt", types.SimpleNamespace(open_osfhandle=open_osfhandle)) + monkeypatch.setattr(os, "O_BINARY", 0x8000, raising=False) + + +@pytest.mark.parametrize("marked", [True, False, None]) +def test_windows_private_fd_removes_its_file_through_the_handle_if_no_descriptor_is_made( + tmp_path, monkeypatch, marked +): + # Simulates the Windows calls, so this runs everywhere; the test above + # makes the real ones. + calls = [] + _simulate_windows_create(monkeypatch, calls, marked=marked) + with pytest.raises(OSError, match="too many open files") as raised: + _file_handles._windows_create_private_fd(tmp_path / "file") + delete, create_new = 0x00010000, 1 + access, share, disposition = calls[0][1:] + assert access & delete and share == 0 and disposition == create_new + # FileDispositionInfo with DeleteFile set, before the handle closes. + assert calls[1:] == [ + ("open_osfhandle", 1234), + ("SetFileInformationByHandle", 1234, 4, b"\x01"), + ("CloseHandle", 1234), + ] + # If it cannot be marked, the error names the empty file so it can be deleted. + noted = any(str(tmp_path / "file") in note for note in getattr(raised.value, "__notes__", [])) + assert noted is not bool(marked) + + +def test_windows_private_fd_refuses_a_volume_without_persistent_acls(tmp_path, monkeypatch): + # FAT and exFAT accept the security descriptor but do not keep it. + calls = [] + _simulate_windows_create(monkeypatch, calls, volume_flags=0) + with pytest.raises(PermissionError, match="does not keep access-control lists"): + _file_handles._windows_create_private_fd(tmp_path / "file") + # Refused before a descriptor exists; the empty file is removed through its handle. + assert [call[0] for call in calls] == [ + "CreateFileW", "SetFileInformationByHandle", "CloseHandle", + ] + + +@pytest.mark.skipif(sys.platform != "win32", reason="Windows access-control lists") +def test_windows_create_private_bytes_sets_an_owner_only_protected_acl(tmp_path): + (tmp_path / "parent").mkdir() + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"content") + # A step's PowerShell 7 puts its own module paths in PSModulePath, and Windows + # PowerShell then fails to load Microsoft.PowerShell.Security for Get-Acl. + # Prefer pwsh, and let either shell rebuild its default module path. + env = {key: value for key, value in os.environ.items() if key.upper() != "PSMODULEPATH"} + # SDDL abbreviates well-known accounts (the built-in Administrator is "LA"), + # so compare resolved SIDs rather than the descriptor string. + script = ( + f"$acl = Get-Acl -LiteralPath '{str(tmp_path / REL).replace(chr(39), chr(39) * 2)}'; " + "$sid = [System.Security.Principal.SecurityIdentifier]; " + "$acl.GetOwner($sid).Value; " + "$acl.AreAccessRulesProtected; " + "$acl.GetAccessRules($true, $true, $sid) | ForEach-Object { " + "\"$($_.IdentityReference.Value) $($_.AccessControlType) $($_.FileSystemRights)\" }" + ) + result = subprocess.run( + [shutil.which("pwsh") or "powershell", "-NoProfile", "-NonInteractive", "-Command", script], + capture_output=True, text=True, env=env, + ) + assert result.returncode == 0, result.stderr + owner, protected, *rules = result.stdout.strip().splitlines() + sid = _file_handles._windows_current_user_sid() + assert owner == sid + assert protected == "True" + assert rules == [f"{sid} Allow FullControl"] + + +# Review regressions + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside, longer") + original = FileHelper._posix_directory + + @contextmanager + def swap_first(self, directory, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, directory, **kwargs) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.stat(REL) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX anchors through parent descriptors") +def test_access_is_not_redirected_by_a_parent_swapped_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._posix_directory + + @contextmanager + def swap_first(self, directory, **kwargs): + path.parent.rename(tmp_path / "moved") + path.parent.symlink_to(outside, target_is_directory=True) + with original(self, directory, **kwargs) as anchored: + yield anchored + + monkeypatch.setattr(FileHelper, "_posix_directory", swap_first) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.access(REL, os.R_OK) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_access_is_not_redirected_by_a_parent_junctioned_after_resolution(tmp_path, monkeypatch): + path = _seed(tmp_path, b"inside") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + original = FileHelper._path + + def swap_after(self, *args, **kwargs): + resolved = original(self, *args, **kwargs) + path.parent.rename(tmp_path / "moved") + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(path.parent), str(outside)], + check=True, capture_output=True, + ) + return resolved + + monkeypatch.setattr(FileHelper, "_path", swap_after) + with FileHelper(tmp_path) as files, pytest.raises(OSError) as raised: + files.access(REL, os.R_OK) + assert raised.value.errno == errno.ELOOP + + +@pytest.mark.skipif(os.name == "nt", reason="the retained root handle withholds delete sharing") +def test_access_of_a_missing_root_raises(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.rmdir() + with pytest.raises(FileNotFoundError): + files.access(".", os.R_OK) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_access_refuses_a_root_replaced_by_a_symlink(tmp_path): + root = tmp_path / "root" + root.mkdir() + other = tmp_path / "other" + other.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.symlink_to(other, target_is_directory=True) + with pytest.raises(OSError) as raised: + files.access(".", os.R_OK) + assert raised.value.errno in _NOFOLLOW_REFUSALS + + +def test_access_of_the_root(tmp_path): + with FileHelper(tmp_path) as files: + assert files.access(".", os.R_OK) + + +@pytest.mark.skipif( + os.name == "nt" or (hasattr(os, "geteuid") and os.geteuid() == 0), + reason="needs POSIX permission bits and an unprivileged user", +) +def test_access_of_a_readable_root_without_search_permission(tmp_path): + root = tmp_path / "root" + root.mkdir() + with FileHelper(root) as files: + root.chmod(0o444) + try: + assert files.access(".", os.R_OK) is os.access(root, os.R_OK) + assert files.access(".", os.R_OK) + finally: + root.chmod(0o755) + + +def test_stat_of_the_root(tmp_path): + with FileHelper(tmp_path) as files: + assert files.stat(tmp_path).st_ino == tmp_path.stat().st_ino + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX descriptors") +def test_open_rewrite_yields_a_blocking_descriptor(tmp_path): + _seed(tmp_path) + with FileHelper(tmp_path) as files, files.open_rewrite(REL) as fd: + assert os.get_blocking(fd) + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") +def test_create_private_bytes_refuses_a_directory_with_inheritable_acl_entries(tmp_path): + parent = tmp_path / "parent" + parent.mkdir() + subprocess.run( + ["chmod", "+a", "everyone allow read,file_inherit", str(parent)], + check=True, capture_output=True, + ) + (parent / "plain").write_bytes(b"") + inherited = subprocess.run( + ["ls", "-le", str(parent / "plain")], check=True, capture_output=True, text=True, + ).stdout + if "everyone" not in inherited: + pytest.skip("filesystem did not apply the inheritable ACE") + with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="inheritable ACL entries allow"): + files.create_private_bytes(REL, b"secret") + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX mode bits") +def test_create_private_bytes_refuses_a_filesystem_that_ignores_the_mode(tmp_path, monkeypatch): + (tmp_path / "parent").mkdir() + real_fstat = os.fstat + + def fstat(fd): + info = real_fstat(fd) + if stat.S_ISREG(info.st_mode): + values = list(info) + values[0] = stat.S_IFREG | 0o777 + return os.stat_result(values) + return info + + monkeypatch.setattr(os, "fstat", fstat) + with FileHelper(tmp_path) as files, pytest.raises(PermissionError, match="owner-only"): + files.create_private_bytes(REL, b"secret") + monkeypatch.undo() + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_notes_a_partial_file_it_could_not_remove( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fsync, real_unlink = os.fsync, os.unlink + + def fsync(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError(errno.ENOSPC, "No space left") + return real_fsync(fd) + + def unlink(path, *args, **kwargs): + if os.fspath(path) == "file": + raise PermissionError(errno.EACCES, "denied") + return real_unlink(path, *args, **kwargs) + + monkeypatch.setattr(os, "fsync", fsync) + monkeypatch.setattr(os, "unlink", unlink) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("Could not remove partial file" in note for note in raised.value.__notes__) + assert (tmp_path / REL).exists() + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_never_removes_a_name_it_could_not_identify( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_fstat = os.fstat + leaf: list[int] = [] + real_open = os.open + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def fstat(fd): + if fd in leaf: + raise OSError(errno.EIO, "fstat failed") + return real_fstat(fd) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "fstat", fstat) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="fstat failed") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).exists() + assert any("delete it before retrying" in note for note in raised.value.__notes__) + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("replaced", [False, True]) +def test_posix_create_private_bytes_notes_a_partial_file_moved_before_cleanup( + tmp_path, monkeypatch, replaced +): + (tmp_path / "parent").mkdir() + real_fsync = os.fsync + + def move_then_fail(fd): + if stat.S_ISREG(os.fstat(fd).st_mode): + (tmp_path / REL).rename(tmp_path / "parent" / "moved") + if replaced: + (tmp_path / REL).write_bytes(b"someone else's") + raise OSError("disk full") + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", move_then_fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + notes = raised.value.__notes__ + # Neither case is a removal failure, and both say the partial file may remain. + assert not any("Could not remove" in note for note in notes) + assert any("may still exist" in note for note in notes) + assert (tmp_path / "parent" / "moved").exists() + if replaced: + assert (tmp_path / REL).read_bytes() == b"someone else's" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_reports_a_failed_close_of_the_last_descriptor( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_open, real_dup, real_close = os.open, os.dup, os.close + leaf: list[int] = [] + duplicates: list[int] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def dup(fd): + copy_ = real_dup(fd) + if fd in leaf: + duplicates.append(copy_) + return copy_ + + def close(fd): + real_close(fd) + if fd in duplicates: + duplicates.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "dup", dup) + monkeypatch.setattr(os, "close", close) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="Input/output") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("check its content" in note for note in raised.value.__notes__) + # The write completed, so the file is left for the caller to inspect. + assert (tmp_path / REL).read_bytes() == b"content" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +def test_posix_create_private_bytes_keeps_the_write_error_when_close_also_fails( + tmp_path, monkeypatch +): + (tmp_path / "parent").mkdir() + real_open, real_write, real_close = os.open, os.write, os.close + leaf: list[int] = [] + + def open_(path, flags, *args, **kwargs): + fd = real_open(path, flags, *args, **kwargs) + if os.fspath(path) == "file": + leaf.append(fd) + return fd + + def write(fd, data): + if fd in leaf: + raise OSError(errno.ENOSPC, "No space left") + return real_write(fd, data) + + def close(fd): + real_close(fd) + if fd in leaf: + leaf.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "write", write) + monkeypatch.setattr(os, "close", close) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="No space left") as raised: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert any("Could not close" in note for note in raised.value.__notes__) + assert not (tmp_path / REL).exists() + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS extended ACLs") +def test_create_private_bytes_accepts_inherited_deny_only_acl_entries(tmp_path): + parent = tmp_path / "parent" + parent.mkdir() + subprocess.run( + ["chmod", "+a", "everyone deny delete,file_inherit", str(parent)], + check=True, capture_output=True, + ) + try: + with FileHelper(tmp_path) as files: + files.create_private_bytes(REL, b"secret") + assert (tmp_path / REL).read_bytes() == b"secret" + finally: + subprocess.run(["chmod", "-RN", str(parent)], check=False, capture_output=True) + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") +@pytest.mark.parametrize(("code", "raises"), [(errno.ENOTSUP, False), (errno.EINVAL, False), + (errno.EIO, True)]) +def test_create_private_bytes_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): + import fcntl + + (tmp_path / "parent").mkdir() + real_fcntl = fcntl.fcntl + + def fail(fd, command, *args): + if command == fcntl.F_FULLFSYNC and stat.S_ISREG(os.fstat(fd).st_mode): + raise OSError(code, os.strerror(code)) + return real_fcntl(fd, command, *args) + + monkeypatch.setattr(fcntl, "fcntl", fail) + with FileHelper(tmp_path) as files: + if raises: + with pytest.raises(OSError) as raised: + files.create_private_bytes(REL, b"content") + assert raised.value.errno == code + else: + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert (tmp_path / REL).exists() is not raises + + +def test_windows_create_private_notes_a_close_failure_after_a_complete_write( + tmp_path, monkeypatch +): + # Drives the Windows branch with a real descriptor so it runs everywhere. + from specify_cli import file_helper + + target = tmp_path / "file" + real_close = os.close + opened: list[int] = [] + + def create(path): + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + opened.append(fd) + return fd + + def close(fd): + real_close(fd) + if fd in opened: + opened.remove(fd) + raise OSError(errno.EIO, "Input/output error") + + monkeypatch.setattr(file_helper, "_windows_create_private_fd", create) + monkeypatch.setattr(os, "close", close) + with pytest.raises(OSError, match="Input/output error") as raised: + FileHelper._windows_create_private(target, b"content") + monkeypatch.undo() + assert any("may need deleting" in note for note in raised.value.__notes__) + assert target.read_bytes() == b"content" + + +@pytest.mark.skipif(os.name != "nt", reason="needs Windows junctions") +def test_stat_refuses_a_junctioned_parent(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (outside / "file").write_bytes(b"outside") + project = tmp_path / "project" + project.mkdir() + subprocess.run( + ["cmd", "/c", "mklink", "/J", str(project / "parent"), str(outside)], + check=True, capture_output=True, + ) + with FileHelper(project) as files, pytest.raises(UnsupportedPathError): + files.stat(REL) + + +@pytest.mark.skipif(sys.platform != "win32", reason="NTFS named streams") +def test_windows_create_private_bytes_refuses_a_named_stream(tmp_path): + # A stream shares its base file's security descriptor, so it cannot be owner-only. + path = _seed(tmp_path, b"base") + with FileHelper(tmp_path) as files, pytest.raises(FileHelperError): + files.create_private_bytes(REL + ":backup", b"secret") + assert path.read_bytes() == b"base" + with pytest.raises(FileNotFoundError): + open(f"{path}:backup", "rb").close() + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX symlinks") +def test_stat_does_not_follow_a_root_replaced_by_a_symlink(tmp_path): + root = tmp_path / "root" + root.mkdir() + other = tmp_path / "other" + other.mkdir() + with FileHelper(root) as files: + root.rename(tmp_path / "moved") + root.symlink_to(other, target_is_directory=True) + assert stat.S_ISLNK(files.stat(".").st_mode) + + +@pytest.mark.skipif(os.name == "nt", reason="needs POSIX FIFOs") +def test_open_rewrite_refuses_a_nonregular_leaf_swapped_in_after_preflight(tmp_path, monkeypatch): + # A FIFO with a reader opens for writing, so only the descriptor check can refuse it. + path = _seed(tmp_path) + real_open = os.open + original = FileHelper._overwrite_descriptor + leaf: list[int] = [] + readers: list[int] = [] + + def open_(name, flags, *args, **kwargs): + fd = real_open(name, flags, *args, **kwargs) + if os.fspath(name) == "file": + leaf.append(fd) + return fd + + @contextmanager + def swap_first(self, destination, **kwargs): + path.unlink() + os.mkfifo(path) + readers.append(real_open(path, os.O_RDONLY | os.O_NONBLOCK)) + with original(self, destination, **kwargs) as fd: + yield fd + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(FileHelper, "_overwrite_descriptor", swap_first) + entered = False + try: + with FileHelper(tmp_path) as files, pytest.raises(UnsupportedPathError): + with files.open_rewrite(REL): + entered = True + finally: + for fd in readers: + os.close(fd) + monkeypatch.undo() + assert not entered + assert len(leaf) == 1 + with pytest.raises(OSError) as raised: + os.fstat(leaf[0]) + assert raised.value.errno == errno.EBADF + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX creation path") +@pytest.mark.parametrize("step", ["write", "fsync", "close"]) +def test_posix_create_private_bytes_keeps_the_inode_pinned_during_cleanup( + tmp_path, monkeypatch, step +): + # Once nothing holds the created inode its number can be reused, and a + # replacement could then pass the identity check and be removed. + (tmp_path / "parent").mkdir() + real_open, real_dup, real_close, real_stat = os.open, os.dup, os.close, os.stat + real_step = {"write": os.write, "fsync": os.fsync, "close": real_close}[step] + pinned: set[int] = set() + leaf: list[int] = [] + pinned_at_check: list[bool] = [] + + def open_(name, flags, *args, **kwargs): + fd = real_open(name, flags, *args, **kwargs) + if os.fspath(name) == "file": + leaf.append(fd) + pinned.add(fd) + return fd + + def dup(fd): + copy = real_dup(fd) + if fd in pinned: + pinned.add(copy) + return copy + + def close(fd): + pinned.discard(fd) + real_close(fd) + if step == "close" and leaf and fd == leaf[0]: + raise OSError("disk full") + + def fail(fd, *args): + if leaf and fd == leaf[0]: + raise OSError("disk full") + return real_step(fd, *args) + + def stat_(name, *args, **kwargs): + if os.fspath(name) == "file" and kwargs.get("dir_fd") is not None: + pinned_at_check.append(bool(pinned)) + return real_stat(name, *args, **kwargs) + + monkeypatch.setattr(os, "open", open_) + monkeypatch.setattr(os, "dup", dup) + monkeypatch.setattr(os, "stat", stat_) + monkeypatch.setattr(os, "close", close) + if step != "close": + monkeypatch.setattr(os, step, fail) + with FileHelper(tmp_path) as files, pytest.raises(OSError, match="disk full"): + files.create_private_bytes(REL, b"content") + monkeypatch.undo() + assert pinned_at_check == [True] + assert not (tmp_path / REL).exists() + + +def test_rewrite_descriptor_replaces_and_truncates_from_any_offset(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"a much longer original\n") + inode = target.stat().st_ino + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + os.lseek(fd, 0, os.SEEK_END) + FileHelper.rewrite_descriptor(fd, b"short\n") + assert target.read_bytes() == b"short\n" + assert target.stat().st_ino == inode + + +def test_rewrite_descriptor_flushes_after_writing(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + seen = [] + real_fsync = os.fsync + + def fsync(fd): + seen.append(os.fstat(fd).st_size) + return real_fsync(fd) + + monkeypatch.setattr(os, "fsync", fsync) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + FileHelper.rewrite_descriptor(fd, b"newer\n") + assert seen == [len(b"newer\n")] + + +def test_rewrite_descriptor_raises_when_a_write_makes_no_progress(tmp_path, monkeypatch): + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + monkeypatch.setattr(os, "write", lambda fd, data: 0) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + with pytest.raises(OSError, match="no progress"): + FileHelper.rewrite_descriptor(fd, b"new\n") + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS F_FULLFSYNC") +@pytest.mark.parametrize("code, raises", [(errno.ENOTSUP, False), (errno.EIO, True)]) +def test_rewrite_descriptor_raises_only_real_full_fsync_errors(tmp_path, monkeypatch, code, raises): + import fcntl + + target = tmp_path / "file.txt" + target.write_bytes(b"old\n") + real_fcntl = fcntl.fcntl + + def fail(fd, command, *args): + if command == fcntl.F_FULLFSYNC: + raise OSError(code, os.strerror(code)) + return real_fcntl(fd, command, *args) + + monkeypatch.setattr(fcntl, "fcntl", fail) + with FileHelper(tmp_path) as helper, helper.open_rewrite("file.txt") as fd: + if raises: + with pytest.raises(OSError): + FileHelper.rewrite_descriptor(fd, b"new\n") + else: + FileHelper.rewrite_descriptor(fd, b"new\n") + if not raises: + assert target.read_bytes() == b"new\n" + + +@pytest.mark.skipif(os.name == "nt", reason="POSIX append-mode descriptors") +def test_rewrite_descriptor_refuses_an_append_mode_descriptor(tmp_path): + target = tmp_path / "file.txt" + target.write_bytes(b"original bytes") + fd = os.open(target, os.O_WRONLY | os.O_APPEND) + try: + with pytest.raises(OSError, match="append-mode"): + FileHelper.rewrite_descriptor(fd, b"new") + finally: + os.close(fd) + assert target.read_bytes() == b"original bytes" + + +def _short_writes(monkeypatch, fail_after=None): + """Make ``os.write`` accept at most 3 bytes a call, optionally failing after some calls.""" + real_write = os.write + calls = [] + + def write(fd, data): + calls.append(fd) + if fail_after is not None and len(calls) > 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()