mergerfs/tests/TEST_teardown_safety
Antonio SJ Musumeci 330e453f43 test: never delete a fixture through a live mount
Fixture cleanup trusted fusermount's exit status, ignored unmount
failures and then ran rmtree over the fixture, through the mount if
it was still attached. unmount_mergerfs now checks the mount table
after each attempt, including the lazy -uz fallback, and raises
UnmountError if the mount stays attached. The fixture is then kept
and its path reported instead of deleted, without masking an
exception from the test body. TEST_teardown_safety checks both.
2026-11-29 23:10:57 -05:00

133 lines
5 KiB
Python
Executable file

#!/usr/bin/env python3
# Teardown safety regression: a busy mount must detach through the lazy
# `-uz` fallback with backing data intact, and a refused unmount must
# propagate while the fixture stays attached and un-removed (rmtree must
# never descend through a live mount).
import os
import shutil
import subprocess
import sys
import posix_parity
from posix_parity import UnmountError
from posix_parity import fail
from posix_parity import find_fusermount
from posix_parity import find_mergerfs
from posix_parity import is_mount_point
from posix_parity import mergerfs_mount
from posix_parity import touch
def test_busy_mount_lazy_detach():
"""Busy mount: plain -u refuses, -uz detaches, backing stays intact."""
with mergerfs_mount() as (mount, branches):
touch(os.path.join(mount, "busy"), b"BUSY")
holder = os.open(os.path.join(mount, "busy"), os.O_RDONLY)
try:
# Negative control: the open holder must defeat a plain -u,
# so the detach below can only come from the lazy fallback.
if subprocess.run([find_fusermount(), "-u", mount],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode == 0:
return fail("busy mount: plain fusermount -u unexpectedly succeeded")
posix_parity.unmount_mergerfs(mount)
if is_mount_point(mount):
return fail("busy mount: still attached after unmount_mergerfs")
backings = [b for b in branches if os.path.exists(os.path.join(b, "busy"))]
if len(backings) != 1:
return fail(f"busy mount: expected one backing file, found {len(backings)}")
with open(os.path.join(backings[0], "busy"), "rb") as stream:
if stream.read() != b"BUSY":
return fail("busy mount: backing content lost across lazy detach")
finally:
os.close(holder)
return 0
def test_refused_unmount_preserves_fixture():
"""A refused teardown propagates and never rmtrees the attachment."""
original_unmount = posix_parity.unmount_mergerfs
def refusing_unmount(mountpoint):
raise UnmountError("forced unmount failure (teardown safety probe)")
posix_parity.unmount_mergerfs = refusing_unmount
mount = None
branches = None
raised = None
try:
try:
with mergerfs_mount() as (mount, branches):
touch(os.path.join(mount, "keep"), b"PRESERVE")
except Exception as exc:
raised = exc
finally:
posix_parity.unmount_mergerfs = original_unmount
if mount is None:
# __enter__ never yielded: mergerfs_mount cleaned its own fixture.
return fail(f"refused unmount: teardown failure not propagated: {raised!r}")
tmpdir = os.path.dirname(mount)
msg = None
if not isinstance(raised, UnmountError):
msg = f"refused unmount: teardown failure not propagated: {raised!r}"
elif not is_mount_point(mount):
# The pre-contract teardown rmtree'd here, deleting the backing
# tree through the live mount.
msg = "refused unmount: fixture no longer attached"
else:
backings = [b for b in branches if os.path.exists(os.path.join(b, "keep"))]
if len(backings) != 1:
msg = "refused unmount: backing file missing"
else:
with open(os.path.join(backings[0], "keep"), "rb") as stream:
if stream.read() != b"PRESERVE":
msg = "refused unmount: backing content lost"
# Leave nothing attached on any exit path; never rmtree beneath a
# live mount.
note = ""
try:
if is_mount_point(mount):
posix_parity.unmount_mergerfs(mount)
except Exception as exc:
note = f"; probe cleanup failed ({exc}); fixture preserved at {tmpdir}"
else:
shutil.rmtree(tmpdir, ignore_errors=True)
if msg or note:
return fail(f"{msg or 'refused unmount: invariants held'}{note}")
return 0
def run_checks():
for test in (test_busy_mount_lazy_detach,
test_refused_unmount_preserves_fixture):
rv = test()
if rv:
return rv
return 0
def main():
if find_mergerfs() is None or find_fusermount() is None:
print("mergerfs or fusermount unavailable", end="")
return 77
if len(sys.argv) == 2 and sys.argv[1] == "--isolated":
return run_checks()
if shutil.which("unshare") is None:
print("unshare unavailable", end="")
return 77
probe = subprocess.run(["unshare", "-Urm", "true"],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if probe.returncode:
print("private user/mount namespaces unavailable", end="")
return 77
# Match the other mount tests: mount inside a private namespace so
# setuid fusermount works for non-root runs.
return subprocess.run(["unshare", "-Urm", sys.executable,
os.path.realpath(__file__), "--isolated"]).returncode
if __name__ == "__main__":
raise SystemExit(main())