#!/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())