mergerfs/tests/TEST_rename_exdev_portable

335 lines
14 KiB
Text
Raw Normal View History

fix: make the rename-exdev fallback safe and transactional rename-exdev (opt-in; the default is passthrough) moves a source it cannot rename across branches into a staging tree and publishes a symlink at the destination. This reworks that fallback so a rename either completes or leaves both names as they were. - Staging opens every component relative to a pinned parent with O_NOFOLLOW, requires a daemon-owned staging root, and refuses when the tree can't be trusted. - Staged names are taken without replacement and must be free on every configured branch, not only those holding the source, so a later lookup cannot reach another rename's payload. Over-long names are shortened. Fallback renames are serialized. - Destinations: a compatible existing destination is replaced, kept under a temporary name until every branch is published, and restored if a later branch fails. A destination on a read-only branch, or a no-create one where the link can't be created, is refused before anything moves. Temporary and restore names never replace an entry, and a restore that fails is reported. - An ordinary rename (rename-exdev=passthrough) also refuses with EXDEV when the destination exists on a read-only branch that does not hold the source: that copy could neither be replaced nor removed and would shadow the renamed file there. It is never scheduled for removal either. - The replacement symlink is prepared in a daemon-private directory, its UID and GID are verified through a pinned descriptor, and it is published without replacement, before any source moves. A sticky, world-writable destination directory under Linux protected symlinks is refused. Each prepared link is tracked by identity for cleanup. - Symlink sources are recreated with their original text, owner and times instead of staged, since staging changes where a relative target resolves. Sources of different types on different branches are refused. A hidden source that cannot be removed fails the rename. - libfuse re-parents the kernel's node onto the staged inode, using a name allocated before publication, so open handles and cached dentries keep working and nothing can fail after the rename commits. - Without renameat2 (FreeBSD 14.4 and 15.0, or seccomp), regular files and directories use a portable layout: a fresh daemon-owned wrapper, access gates that mirror the source's parents with the source's GID and its read and execute bits only, and the payload directory inside the last gate. Foreign-owned parents, unsettable group ownership and non-trivial ACLs are refused before the source moves. A namespace the source never entered is removed. A portable directory that can't be restored stays staged with its path logged, and an existing directory destination is refused before a portable source moves: keeping it aside would need the no-replace rename the portable layout lacks. - Document the fallback, its refusals and FreeBSD limits. - TEST_rename_exdev_publication, TEST_rename_exdev_portable and tests.cpp cover publication rollback, shadows, collisions, ownership, sticky directories, mixed source types, a refused portable directory destination and the portable layout through a mounted pool. TEST_rename_exdev_publication keeps its fixture if its tmpfs can't be detached. Performance: an ordinary rename only adds an lstat per read-only branch, and only when one is configured. The fallback adds about two lstats per branch plus the staging work, and fallback renames run one at a time.
2026-11-25 13:45:42 -05:00
#!/usr/bin/env python3
import ctypes
import errno
import os
import re
import shutil
import subprocess
import sys
import uuid
from os.path import join
import posix_parity
from posix_parity import fail
from posix_parity import mergerfs_get_option
from posix_parity import mergerfs_set_option
from posix_parity import touch
SKIP = 77
class CheckError(Exception):
pass
class SkipTest(Exception):
pass
def require(condition, message):
if not condition:
raise CheckError(message)
def get_errno(func):
try:
func()
return 0
except OSError as exc:
return exc.errno
def portable_relocation(link_path, pool_dst, mount, mode, src_rel):
require(os.path.islink(link_path), f"missing backend symlink: {link_path}")
target = os.readlink(link_path)
if mode == "rel-symlink":
require(not os.path.isabs(target), f"relative mode returned {target!r}")
pool_target = os.path.normpath(join(os.path.dirname(pool_dst), target))
else:
pool_target = target
mount_prefix = mount.rstrip(os.sep) + os.sep
require(pool_target.startswith(mount_prefix), f"target escaped pool: {pool_target!r}")
relocated = os.path.relpath(pool_target, mount)
suffix = join(os.path.dirname(src_rel), ".payload", os.path.basename(src_rel))
match = re.fullmatch(
re.escape(join(".mergerfs_rename_exdev", ""))
+ r"(\.p-[0-9a-f]{16})/" + re.escape(suffix),
relocated,
)
require(match is not None, f"not a portable relocation: {relocated!r}")
expected = (
os.path.relpath(pool_target, os.path.dirname(pool_dst))
if mode == "rel-symlink"
else pool_target
)
require(target == expected, f"target {target!r} != {expected!r}")
return relocated, match.group(1)
def mode_bits(st):
return st.st_mode & 0o7777
def disable_renameat2():
# This test process and the daemon it launches inherit the restriction.
# Unlike a tracer, this does not prevent LeakSanitizer checking daemon exit.
try:
lib = ctypes.CDLL("libseccomp.so.2")
except OSError as exc:
raise SkipTest("libseccomp is needed for the forced portable case") from exc
ptr, uint, sint = ctypes.c_void_p, ctypes.c_uint32, ctypes.c_int
lib.seccomp_init.argtypes = [uint]
lib.seccomp_init.restype = ptr
lib.seccomp_syscall_resolve_name.argtypes = [ctypes.c_char_p]
lib.seccomp_rule_add.argtypes = [ptr, uint, sint, ctypes.c_uint]
lib.seccomp_load.argtypes = [ptr]
lib.seccomp_release.argtypes = [ptr]
lib.seccomp_release.restype = None
number = lib.seccomp_syscall_resolve_name(b"renameat2")
if number < 0:
raise SkipTest("libseccomp does not recognize renameat2 on this architecture")
allow = 0x7fff0000 # SCMP_ACT_ALLOW
deny = 0x00050000 | errno.ENOSYS # SCMP_ACT_ERRNO(ENOSYS)
ctx = lib.seccomp_init(allow)
if not ctx:
raise CheckError("could not allocate syscall filter")
try:
require(lib.seccomp_rule_add(ctx, deny, number, 0) == 0, "cannot restrict renameat2")
rc = lib.seccomp_load(ctx)
if rc in (-errno.EPERM, -errno.EACCES, -errno.EOPNOTSUPP):
raise SkipTest("kernel does not allow the test's syscall filter")
require(rc == 0, f"seccomp_load returned {rc}")
finally:
lib.seccomp_release(ctx)
def run_case(mount, branches, mode, directory, sequence):
rel_base = f".mergerfs_portable_test_{os.getpid()}_{uuid.uuid4().hex}"
name = f"case_{sequence}"
# A user component named .payload must not collide with an internal link.
parent = join(rel_base, ".payload")
src_rel = join(parent, name + ".src") if directory else f"{rel_base}_{name}.src"
dst_rel = join(rel_base, "dst", "nested", name)
src = join(mount, src_rel)
dst = join(mount, dst_rel)
os.makedirs(join(branches[0], os.path.dirname(src_rel)), exist_ok=True)
os.makedirs(join(branches[1], os.path.dirname(dst_rel)), exist_ok=True)
if directory:
os.chmod(join(branches[0], parent), 0o700)
source_parent_stat = os.stat(join(branches[0], parent))
os.mkdir(join(branches[0], src_rel), 0o751)
touch(join(branches[0], src_rel, "child"), b"src")
else:
source_parent_stat = None
touch(join(branches[0], src_rel), b"src")
source_stat = os.lstat(join(branches[0], src_rel))
legacy = join(branches[0], ".mergerfs_rename_exdev", src_rel)
os.makedirs(os.path.dirname(legacy), exist_ok=True)
touch(legacy, b"legacy-must-survive")
mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(src, dst))
require(err == 0, f"{mode}, directory={directory}: rename errno={err}")
relocated, wrapper = portable_relocation(
join(branches[1], dst_rel), dst, mount, mode, src_rel
)
staged = join(branches[0], relocated)
require(not os.path.lexists(join(branches[0], src_rel)), "source remains after rename")
require(os.stat(staged).st_ino == source_stat.st_ino, "source inode changed")
with open(join(staged, "child") if directory else staged, "rb") as fp:
require(fp.read() == b"src", "staged payload mismatch")
with open(join(dst, "child") if directory else dst, "rb") as fp:
require(fp.read() == b"src", "pool payload mismatch")
with open(legacy, "rb") as fp:
require(fp.read() == b"legacy-must-survive", "legacy entry was overwritten")
wrapper_path = join(branches[0], ".mergerfs_rename_exdev", wrapper)
wrapper_stat = os.stat(wrapper_path)
require(wrapper_stat.st_uid == os.geteuid(), "wrapper is not daemon owned")
require(mode_bits(wrapper_stat) == 0o555, "wrapper is publicly writable or restrictive")
parent_rel = os.path.dirname(src_rel)
gate_path = join(wrapper_path, parent_rel)
# The payload must be below the mirrored parents, not available by
# a shorter route which omits their search permissions.
payload_dir = join(gate_path, ".payload")
payload_stat = os.lstat(payload_dir)
require(payload_stat.st_uid == os.geteuid(), "payload parent is not daemon owned")
require(mode_bits(payload_stat) == 0o555, "payload parent is not 0555")
require(os.path.isdir(payload_dir) and not os.path.islink(payload_dir),
"payload directory is not physically below its gates")
if source_parent_stat is not None:
require(not os.path.lexists(join(wrapper_path, ".payload")),
"payload is reachable without traversing the source's parents")
gate_stat = os.lstat(gate_path)
require(gate_stat.st_uid == source_parent_stat.st_uid, "gate UID mismatch")
require(gate_stat.st_gid == source_parent_stat.st_gid, "gate GID mismatch")
# The daemon keeps the ancestor's read/search permissions, not write access.
expect = mode_bits(source_parent_stat) & 0o555
require(mode_bits(gate_stat) == expect, "gate mode mismatch")
def rejected_setup_leaves_nothing(mount, branches):
# A rejected request must not leave a portable namespace behind. A
# nontrivial ACL on the source parent is refused before the move.
if shutil.which("setfacl") is None:
return
rel_base = f".mergerfs_portable_acl_{os.getpid()}_{uuid.uuid4().hex}"
src_rel = join(rel_base, "acl", "source")
dst_rel = join(rel_base, "dst", "source")
touch(join(branches[0], src_rel), b"acl")
os.makedirs(join(branches[1], os.path.dirname(dst_rel)), exist_ok=True)
acl = subprocess.run(["setfacl", "-m", f"u:{os.geteuid()}:rwx",
join(branches[0], os.path.dirname(src_rel))],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if acl.returncode:
return
def portable_namespaces():
staging = join(branches[0], ".mergerfs_rename_exdev")
if not os.path.isdir(staging):
return set()
return {name for name in os.listdir(staging) if name.startswith(".p-")}
before = portable_namespaces()
mergerfs_set_option(mount, "rename-exdev", "rel-symlink")
for _ in range(3):
err = get_errno(lambda: os.rename(join(mount, src_rel), join(mount, dst_rel)))
require(err == errno.EXDEV, f"ACL rejection returned errno={err}")
after = portable_namespaces()
require(after == before, f"rejected renames left {sorted(after - before)}")
with open(join(branches[0], src_rel), "rb") as fp:
require(fp.read() == b"acl", "rejected rename changed the source")
def foreign_parent_is_refused(mount, branches):
srcdir = join(branches[0], "foreign-parent")
src = join(srcdir, "source")
out = join(branches[1], "foreign-out")
touch(src, b"unchanged")
os.mkdir(out)
try:
os.chown(srcdir, 1 if os.geteuid() != 1 else 2, -1)
except OSError as exc:
if exc.errno not in (errno.EPERM, errno.EINVAL, errno.EACCES):
raise
print("SKIP foreign parent: needs a second mapped UID")
return
mergerfs_set_option(mount, "rename-exdev", "rel-symlink")
staging = join(branches[0], ".mergerfs_rename_exdev")
before = {name for name in os.listdir(staging) if name.startswith(".p-")}
err = get_errno(lambda: os.rename(join(mount, "foreign-parent", "source"),
join(mount, "foreign-out", "dest")))
require(err == errno.EXDEV, f"foreign-parent rename returned {err}, expected EXDEV")
with open(src, "rb") as fp:
require(fp.read() == b"unchanged", "refused rename changed the source")
require(not os.listdir(out), "refused rename published a destination")
after = {name for name in os.listdir(staging) if name.startswith(".p-")}
require(after == before, "refused rename left a portable namespace")
def portable_directory_destination_refused(mount, branches):
# An existing directory destination cannot be kept without atomic
# no-replace rename, and a moved portable directory cannot be
# unstaged. The fallback must refuse such a rename before the
# source moves, leaving source and destination exactly as they
# were, with no portable namespace and no replacement link behind.
rel_base = f".mergerfs_portable_refuse_{os.getpid()}_{uuid.uuid4().hex}"
src_rel = join(rel_base, "srcdir")
dst_rel = join(rel_base, "dst", "nested", "dstdir")
src = join(branches[0], src_rel)
dst = join(branches[1], dst_rel)
os.makedirs(join(branches[0], rel_base))
os.makedirs(join(branches[1], os.path.dirname(dst_rel)))
os.mkdir(src, 0o750)
touch(join(src, "child"), b"src")
os.mkdir(dst)
def residue():
paths = set()
for branch in branches:
for directory, prefix in ((".mergerfs_rename_exdev", ".p-"),
(os.path.dirname(dst_rel), ".mergerfs_rename_exdev_")):
path = join(branch, directory)
if os.path.isdir(path):
paths.update(join(path, n) for n in os.listdir(path) if n.startswith(prefix))
return paths
src_stat, dst_stat = os.lstat(src), os.lstat(dst)
before = residue()
for mode in ("rel-symlink", "abs-symlink"):
mergerfs_set_option(mount, "rename-exdev", mode)
err = get_errno(lambda: os.rename(join(mount, src_rel),
join(mount, dst_rel)))
require(os.path.isdir(src), f"{mode}: source directory missing after refusal (errno={err})")
require(os.path.samestat(src_stat, os.lstat(src)), f"{mode}: source directory changed")
require(os.path.samestat(dst_stat, os.lstat(dst)), f"{mode}: destination directory changed")
with open(join(mount, src_rel, "child"), "rb") as fp:
require(fp.read() == b"src", f"{mode}: source child bytes changed")
require(not os.listdir(dst), f"{mode}: destination is no longer empty")
require(residue() == before, f"{mode}: refusal left staging or replacement names")
require(err == errno.EXDEV, f"{mode}: expected EXDEV, got errno={err}")
def isolated():
options = "defaults,use_ino,category.create=mfs,minfreespace=0"
try:
if sys.platform.startswith("linux"):
disable_renameat2()
with posix_parity.mergerfs_mount(options=options) as (mount, branches):
original_create = mergerfs_get_option(mount, "category.create")
original_rename = mergerfs_get_option(mount, "rename-exdev")
try:
mergerfs_set_option(mount, "category.create", "epmfs")
sequence = 0
for directory in (False, True):
for mode in ("rel-symlink", "abs-symlink"):
run_case(mount, branches, mode, directory, sequence)
sequence += 1
rejected_setup_leaves_nothing(mount, branches)
foreign_parent_is_refused(mount, branches)
portable_directory_destination_refused(mount, branches)
finally:
mergerfs_set_option(mount, "category.create", original_create)
mergerfs_set_option(mount, "rename-exdev", original_rename)
return 0
except SkipTest as exc:
print(str(exc), end="")
return SKIP
except RuntimeError as exc:
if str(exc) in ("mergerfs binary not found", "fusermount3/fusermount not found"):
print(str(exc), end="")
return SKIP
return fail(f"portable EXDEV test failed: {exc}")
except (CheckError, OSError) as exc:
return fail(f"portable EXDEV test failed: {exc}")
def main():
if not sys.platform.startswith("linux"):
return isolated()
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
return isolated()
# The seccomp filter sets no_new_privs, which a setuid fusermount
# can't run under. Mount directly as root of a private namespace.
if shutil.which("unshare") is None:
print("unshare unavailable", end="")
return SKIP
namespace = ["unshare", "-Urm"]
probe = subprocess.run(namespace + ["true"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if probe.returncode:
print("private user/mount namespaces unavailable", end="")
return SKIP
return subprocess.run(namespace + [sys.executable, os.path.realpath(__file__),
"--isolated"]).returncode
if __name__ == "__main__":
raise SystemExit(main())