repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
rsx.test.pyPython322 lines15.7 KiBraw download
#!/usr/bin/env python3
"""Functional rsx checks. Real transfers are confined to a temporary tree."""
import hashlib
import importlib.machinery
import importlib.util
import os
from pathlib import Path
import pty
import select
import shutil
import signal
import subprocess
import tempfile
import time
import unittest

RSX = Path.home() / ".local/bin/rsx"
loader = importlib.machinery.SourceFileLoader("rsx", str(RSX))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)


class RsxTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory(prefix="rsx-test-")
        self.root = Path(self.tmp.name)
        self.src = self.root / "source with spaces"
        self.dst = self.root / "destination with spaces"
        self.src.mkdir()
        self.dst.mkdir()
        (self.src / "notes.txt").write_text("hello rsx\n")
        (self.src / "nested").mkdir()
        (self.src / "nested/data.txt").write_text("nested payload\n")
        (self.src / "link").symlink_to("notes.txt")
        (self.src / "notes.txt").chmod(0o640)
        self.env = os.environ.copy()
        for key in ("RSYNC_PARTIAL_DIR", "RICEFX_OFF", "RSX_PLAIN", "NO_COLOR"):
            self.env.pop(key, None)
        self.env["NO_COLOR"] = "1"
        self.addCleanup(self.tmp.cleanup)

    def run_rsx(self, *args, expected=0, input=None):
        result = subprocess.run([str(RSX), *map(str, args)], env=self.env,
                                cwd=self.root, input=input, capture_output=True,
                                text=True, timeout=15)
        self.assertEqual(result.returncode, expected, result.stdout + result.stderr)
        self.assertNotIn("\x1b", result.stdout + result.stderr)
        return result

    def paths(self):
        return str(self.src) + "/", str(self.dst) + "/"

    def snapshot(self):
        result = []
        for path in sorted(self.root.rglob("*")):
            st = path.lstat()
            data = os.readlink(path) if path.is_symlink() else (
                hashlib.sha256(path.read_bytes()).hexdigest() if path.is_file() else None)
            result.append((str(path.relative_to(self.root)), st.st_mode, st.st_mtime_ns, data))
        return result

    def test_copy_preserves_content_symlinks_permissions_and_extras(self):
        (self.dst / "keep.txt").write_text("keep me")
        self.run_rsx(*self.paths())
        self.assertEqual((self.dst / "notes.txt").read_bytes(), (self.src / "notes.txt").read_bytes())
        self.assertEqual((self.dst / "nested/data.txt").read_text(), "nested payload\n")
        self.assertEqual(os.readlink(self.dst / "link"), "notes.txt")
        self.assertEqual((self.dst / "notes.txt").stat().st_mode & 0o777, 0o640)
        self.assertTrue((self.dst / "keep.txt").exists())
        (self.src / "notes.txt").write_text("updated payload of a different size")
        self.run_rsx(*self.paths())
        self.assertEqual((self.dst / "notes.txt").read_bytes(), (self.src / "notes.txt").read_bytes())

    def test_trailing_slash_and_multiple_sources(self):
        self.run_rsx(self.src, str(self.dst) + "/")
        self.assertTrue((self.dst / self.src.name / "notes.txt").exists())
        self.run_rsx(self.src / "notes.txt", self.src / "nested/data.txt", self.dst)
        self.assertTrue((self.dst / "notes.txt").exists())
        self.assertTrue((self.dst / "data.txt").exists())

    def test_preview_never_changes_either_tree(self):
        (self.dst / "extra.txt").write_text("keep during preview")
        before = self.snapshot()
        result = self.run_rsx("preview", "--delete-delay", *self.paths())
        self.assertIn("*deleting", result.stdout)
        self.assertEqual(self.snapshot(), before)
        self.run_rsx("mirror", "-n", *self.paths())
        self.assertEqual(self.snapshot(), before)
        for flag in ("--no-dry-run", "--no-n"):
            self.run_rsx("preview", flag, *self.paths(), expected=2)
            self.assertEqual(self.snapshot(), before)

    def test_mirror_deletes_extras_but_protects_excluded_files(self):
        (self.dst / "extra.txt").write_text("delete me")
        (self.dst / "secret.tmp").write_text("keep me")
        (self.src / "skip.tmp").write_text("do not copy")
        self.run_rsx("mirror", "--exclude=*.tmp", *self.paths())
        self.assertFalse((self.dst / "extra.txt").exists())
        self.assertTrue((self.dst / "secret.tmp").exists())
        self.assertFalse((self.dst / "skip.tmp").exists())

    def test_native_stdin_and_exclusions(self):
        self.run_rsx("--files-from=-", *self.paths(), input="notes.txt\n")
        self.assertTrue((self.dst / "notes.txt").exists())
        self.assertFalse((self.dst / "nested").exists())

    def test_native_exit_status_and_quiet(self):
        self.run_rsx(self.root / "missing", self.dst, expected=23)
        result = self.run_rsx("-q", *self.paths())
        self.assertEqual(result.stdout, "")
        self.run_rsx("--not-an-rsync-option", *self.paths(), expected=1)

    def test_raw_matches_native_output(self):
        native = subprocess.run(["rsync", "--version"], capture_output=True, text=True, timeout=5)
        result = self.run_rsx("raw", "--version")
        self.assertEqual((result.stdout, result.stderr), (native.stdout, native.stderr))

    def test_command_only_and_remote_argument_boundaries(self):
        source = "user@[2001:db8::1]:/some path/with 'quotes'/"
        command, _ = module.build_command("copy", ["-e", "ssh -p 2222", source, "./dest/"], "/usr/bin/rsync")
        self.assertEqual(command[-4:], ["-e", "ssh -p 2222", source, "./dest/"])
        before = self.snapshot()
        result = self.run_rsx("--command", "mirror", *self.paths())
        self.assertIn("--delete-delay", result.stdout)
        self.assertEqual(self.snapshot(), before)

    def test_reserved_names_and_shell_metacharacters(self):
        weird = self.root / "$(touch SHOULD_NOT_EXIST); 'quoted'.txt"
        weird.write_text("literal name")
        (self.root / "copy").mkdir()
        (self.root / "copy/data").write_text("reserved directory")
        self.run_rsx("--", weird.name, "copy", self.dst)
        self.assertTrue((self.dst / weird.name).exists())
        self.assertTrue((self.dst / "copy/data").exists())
        self.assertFalse((self.root / "SHOULD_NOT_EXIST").exists())

    def test_inplace_and_local_delta_partial_reuse(self):
        self.run_rsx("--inplace", *self.paths())
        (self.src / "large.bin").write_bytes(os.urandom(512 * 1024))
        partial = self.dst / ".rsync-partial"
        partial.mkdir()
        (partial / "large.bin").write_bytes((self.src / "large.bin").read_bytes()[:256 * 1024])
        result = self.run_rsx("--no-whole-file", *self.paths())
        self.assertEqual((self.dst / "large.bin").read_bytes(), (self.src / "large.bin").read_bytes())
        self.assertNotIn("Matched data: 0 bytes", result.stdout)
        self.assertFalse((partial / "large.bin").exists())

    def test_alias_help_and_cheat(self):
        self.run_rsx("--help")
        self.run_rsx("cheat", "flags")
        self.run_rsx("cheat", "nonexistent", expected=2)
        result = subprocess.run([str(RSX.with_name("rxs")), "--version"],
                                capture_output=True, text=True, env=self.env, timeout=5)
        self.assertEqual(result.stdout.strip(), "rsx " + module.VERSION)
        result = subprocess.run([str(RSX.with_name("rsx-cheat")), "copy"],
                                capture_output=True, text=True, env=self.env, timeout=5)
        self.assertEqual(result.returncode, 0, result.stderr)
        self.assertIn("copy · local paths", result.stdout)

    def check_terminal_transfer(self, interrupt_signal=None):
        (self.src / "large.bin").write_bytes(os.urandom(2 * 1024 * 1024))
        master, slave = pty.openpty()
        env = dict(self.env)
        env.pop("NO_COLOR")
        env["TERM"] = "xterm-256color"
        process = subprocess.Popen([str(RSX), "--bwlimit=512k", *self.paths()], env=env,
                                   stdin=slave, stdout=slave, stderr=slave)
        os.close(slave)
        output = bytearray()
        interrupted = False
        deadline = time.monotonic() + 12
        try:
            while process.poll() is None and time.monotonic() < deadline:
                if select.select([master], [], [], 0.15)[0]:
                    try:
                        output.extend(os.read(master, 65536))
                    except OSError:
                        break
                if interrupt_signal and not interrupted and b"%" in output:
                    process.send_signal(interrupt_signal)
                    interrupted = True
            process.wait(timeout=6)
            while select.select([master], [], [], 0.1)[0]:
                try:
                    data = os.read(master, 65536)
                except OSError:
                    break
                if not data:
                    break
                output.extend(data)
        finally:
            if process.poll() is None:
                process.kill()
                process.wait()
            os.close(master)
        self.assertEqual(interrupted, bool(interrupt_signal), output[-2000:])
        self.assertEqual(process.returncode, 128 + interrupt_signal if interrupt_signal else 0,
                         output[-2000:])
        self.assertIn(b"\x1b[38;2;", output)
        self.assertNotIn(b"Traceback", output)
        if interrupt_signal:
            self.assertTrue((self.dst / ".rsync-partial/large.bin").exists(), output[-2000:])
            self.run_rsx("--no-whole-file", *self.paths())
        else:
            self.assertIn(b"rsync finished", output)
        self.assertEqual((self.src / "large.bin").read_bytes(), (self.dst / "large.bin").read_bytes())

    def test_theme_progress_and_interrupt_saves_partial(self):
        self.check_terminal_transfer(signal.SIGINT)

    def test_theme_sigterm_exit_status_and_partial(self):
        self.check_terminal_transfer(signal.SIGTERM)

    def test_theme_completes_transfer(self):
        self.check_terminal_transfer()

    # ── cloud folders: Google Drive / pCloud mounts ──────────────────────────

    MOUNTINFO = (
        "22 1 259:2 /@home /home rw,relatime shared:1 - btrfs /dev/mapper/root rw\n"
        "435 256 0:127 / {home}/GDrive rw,nosuid,nodev,relatime shared:530"
        " - fuse.rclone gdrive: rw,user_id=1000,group_id=1000\n"
        "436 256 0:128 / {home}/pCloudDrive rw,nosuid,nodev,relatime"
        " - fuse pCloud.fs rw,user_id=1000\n"
        "437 256 0:129 / {home}/My\\040Cloud rw,nosuid,nodev shared:5"
        " - fuse.rclone box: rw,user_id=1000\n"
        "438 256 0:130 / {home}/Vault rw,relatime shared:9"
        " - fuse.gocryptfs gocryptfs@{home}/.vault rw,user_id=1000\n"
    )

    def mountinfo(self):
        path = self.root / "mountinfo"
        path.write_text(self.MOUNTINFO.format(home=self.root))
        return str(path)

    def test_cloud_mounts_recognises_cloud_fuse_only(self):
        mounts = module.cloud_mounts(self.mountinfo())
        self.assertEqual(mounts, [f"{self.root}/GDrive", f"{self.root}/pCloudDrive",
                                  f"{self.root}/My Cloud"])
        self.assertNotIn(f"{self.root}/Vault", mounts)   # gocryptfs keeps POSIX metadata
        self.assertEqual(module.cloud_mounts(str(self.root / "absent")), [])

    def test_cloud_target_matches_paths_but_not_remotes_or_flags(self):
        mounts = module.cloud_mounts(self.mountinfo())
        target = lambda *args: module.cloud_target(list(args), mounts)
        self.assertEqual(target("./src/", f"{self.root}/GDrive/Notes/"), f"{self.root}/GDrive")
        self.assertEqual(target(f"{self.root}/My Cloud/x"), f"{self.root}/My Cloud")
        self.assertEqual(target(f"{self.root}/GDrive"), f"{self.root}/GDrive")
        self.assertIsNone(target("./src/", f"{self.root}/GDriveOther/x"))
        self.assertIsNone(target("./src/", str(self.dst)))
        self.assertIsNone(target("./src/", f"user@host:{self.root}/GDrive/x"))
        self.assertIsNone(target(f"--exclude={self.root}/GDrive/skip"))
        symlinked = self.root / "shortcut"
        symlinked.symlink_to(f"{self.root}/GDrive")
        self.assertEqual(target(f"{symlinked}/Notes"), f"{self.root}/GDrive")

    def test_cloud_mode_and_switch_build_the_flag_set(self):
        binary = "/usr/bin/rsync"
        command, _ = module.build_command("cloud", ["a/", "b/"], binary)
        for flag in module.CLOUD_FLAGS:
            self.assertIn(flag, command)
        self.assertIn("--archive", command)
        self.assertNotIn("--delete-delay", command)
        self.assertEqual(command[-2:], ["a/", "b/"])
        self.assertLess(command.index("--copy-links"), command.index("a/"))
        mirror, _ = module.build_command("mirror", ["a/", "b/"], binary, cloud=True)
        self.assertIn("--delete-delay", mirror)
        self.assertIn("--omit-dir-times", mirror)
        preview, _ = module.build_command("preview", ["a/", "b/"], binary, cloud=True)
        self.assertIn("--dry-run", preview)
        self.assertIn("--copy-links", preview)
        plain, _ = module.build_command("copy", ["a/", "b/"], binary)
        self.assertFalse([f for f in module.CLOUD_FLAGS if f in plain])
        raw, _ = module.build_command("raw", ["-av", "a/", "b/"], binary)
        self.assertEqual(raw, [binary, "-av", "a/", "b/"])

    def test_cloud_parse_precedence(self):
        self.assertEqual(module.parse_cli(["cloud", "a", "b"])[0], "cloud")
        self.assertEqual(module.parse_cli(["--cloud", "mirror", "a", "b"])[4], True)
        self.assertEqual(module.parse_cli(["--no-cloud", "a", "b"])[5], True)
        # --no-cloud silences detection; naming the mode still asks for the flags
        result = self.run_rsx("--command", "--no-cloud", "cloud", *self.paths())
        self.assertIn("--copy-links", result.stdout)
        result = self.run_rsx("--command", "--no-cloud", *self.paths())
        self.assertNotIn("--copy-links", result.stdout)

    def test_cloud_transfer_follows_links_and_leaves_permissions(self):
        result = self.run_rsx("cloud", *self.paths())
        self.assertNotIn("rsx:", result.stderr)          # explicit: no detection note
        link = self.dst / "link"
        self.assertFalse(link.is_symlink())
        self.assertEqual(link.read_text(), "hello rsx\n")
        again = self.run_rsx("cloud", "-i", *self.paths())
        self.assertEqual([l for l in again.stdout.splitlines()
                          if l[:1].strip() and l[0] in "<>ch.*"], [])
        # --no-perms means an existing destination keeps the mode it has. That is
        # what stops the endless re-chmod when the far side dictates its own modes.
        (self.dst / "notes.txt").chmod(0o600)
        quiet = self.run_rsx("cloud", "-i", *self.paths())
        self.assertNotIn("notes.txt", quiet.stdout)
        self.assertEqual((self.dst / "notes.txt").stat().st_mode & 0o777, 0o600)
        # a later rsync flag still wins over the ones rsx adds
        fixed = self.run_rsx("cloud", "--perms", "-i", *self.paths())
        self.assertIn("notes.txt", fixed.stdout)
        self.assertEqual((self.dst / "notes.txt").stat().st_mode & 0o777, 0o640)

    def test_cloud_detection_note_and_auto_flags(self):
        fake = self.root / "GDrive"
        fake.mkdir()
        mounts = [str(fake)]
        self.assertEqual(module.cloud_target([str(self.src) + "/", str(fake) + "/x/"], mounts),
                         str(fake))
        # end to end the detection reads the real mount table, so drive the
        # same code path the wrapper uses, with the switch supplied explicitly
        command, _ = module.build_command("copy", [str(self.src) + "/", str(fake) + "/x/"],
                                          "/usr/bin/rsync", cloud=True)
        self.assertIn("--copy-links", command)


if __name__ == "__main__":
    unittest.main(verbosity=2)