Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
073af65
feat(file-helper): add public stat, in-place byte rewrite and owner-o…
echarrod Nov 19, 2026
bcf331e
fix(file-helper): anchor stat and harden owner-only create cleanup
echarrod Nov 19, 2026
8bbe552
fix(file-helper): refuse private files others can open, anchor stat p…
echarrod Nov 19, 2026
3543a08
fix(file-helper): refuse only inherited allow entries, surface real f…
echarrod Nov 19, 2026
7e9de98
feat(file-helper): add access() and canonical_root
echarrod Nov 19, 2026
68809dd
fix(file-helper): check access with a plain faccessat
echarrod Nov 19, 2026
14f6190
test(file-helper): pin access to a plain faccessat
echarrod Nov 19, 2026
7d825c6
fix(file-helper): refuse unprotectable private creates, pin the inode…
echarrod Nov 20, 2026
238365f
Merge upstream/main into feat/file-helper-public-rewrite-create
echarrod Nov 20, 2026
e5c0597
fix(file-helper): refuse a private create owned by another user
echarrod Nov 20, 2026
6e9eb84
fix(file-helper): name a replaced partial file instead of skipping it…
echarrod Nov 20, 2026
e097fe7
fix(file-helper): note a moved partial file and report a failed final…
echarrod Nov 20, 2026
a53bb54
test(file-helper): compare the Windows private-file ACL by resolved SID
echarrod Nov 20, 2026
59728c4
feat(file-helper): add rewrite_descriptor and document the owner refusal
echarrod Nov 20, 2026
22b4adb
fix(file-helper): refuse an append-mode descriptor in rewrite_descriptor
echarrod Nov 20, 2026
4ed8dcf
refactor(file-helper): narrow to stat, open_rewrite and rewrite_descr…
echarrod Nov 27, 2026
dc6a02e
docs(file-helper): note POSIX may clear setuid/setgid on rewrite
echarrod Nov 27, 2026
2821804
feat(file-helper): add owner-only create, access and canonical_root
echarrod Nov 27, 2026
264c7e9
fix(file-helper): validate the root in access and scope its claims
echarrod Nov 27, 2026
a795171
fix(file-helper): check root access without requiring search permission
echarrod Nov 30, 2026
070e0f6
fix(file-helper): document the POSIX root access window and test a sw…
echarrod Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 95 additions & 4 deletions design/file-helper.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
219 changes: 218 additions & 1 deletion src/specify_cli/_file_handles.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from collections.abc import Iterator
from contextlib import contextmanager
import errno
import functools
import os
import secrets
import stat
Expand Down Expand Up @@ -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."""
Expand All @@ -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
Expand Down Expand Up @@ -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
Loading
Loading