repositories

NixDaemon

NixOS pentest workstation as one flake — IceBreaker's successor

clonegit clone https://git.daemon-sec.xyz/NixDaemon.git
rcx.test.pyPython274 lines14.9 KiBraw download
#!/usr/bin/env python3
"""Functional rcx checks. Every transfer stays inside a temporary directory."""
import importlib.machinery
import importlib.util
import os
from pathlib import Path
import subprocess
import tempfile
import unittest

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


class RcxTest(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory(prefix="rcx-test-")
        self.root = Path(self.tmp.name)
        self.src = self.root / "source dir"
        self.dst = self.root / "dest dir"
        (self.src / "media").mkdir(parents=True)
        (self.src / "index").mkdir()
        self.dst.mkdir()
        (self.src / "media/a.bin").write_bytes(b"a" * 4096)
        (self.src / "media/b.bin").write_bytes(b"b" * 2048)
        os.link(self.src / "media/a.bin", self.src / "index/a.bin")
        self.env = dict(os.environ, NO_COLOR="1")
        self.env.pop("RCX_PLAIN", None)
        self.addCleanup(self.tmp.cleanup)

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

    # ── the far side ────────────────────────────────────────────────────────

    def test_remote_syntax_recognition(self):
        for remote in ("gdrive:", "gdrive:Backup/Media", "s3-eu:bucket/x"):
            self.assertTrue(module.is_remote(remote), remote)
        for local in ("/tmp/x", "./x", "~/x", "relative/path", str(self.src)):
            self.assertFalse(module.is_remote(local), local)
        # a Windows-style or user@host: argument is not an rclone remote here
        self.assertFalse(module.is_remote("./copy:me"))
        self.assertEqual(module.remote_name("gdrive:Personal"), "gdrive")
        self.assertIsNone(module.remote_name("/tmp/x"))

    def test_cloud_mount_guard(self):
        info = self.root / "mountinfo"
        info.write_text(
            f"22 1 259:2 / {self.root}/plain rw shared:1 - btrfs /dev/mapper/root rw\n"
            f"43 25 0:12 / {self.root}/GDrive rw - fuse.rclone gdrive: rw,user_id=1000\n"
            f"44 25 0:13 / {self.root}/pCloudDrive rw - fuse pCloud.fs rw,user_id=1000\n"
            f"45 25 0:14 / {self.root}/Vault rw - fuse.gocryptfs gocryptfs@x rw\n")
        mounts = module.cloud_mounts(str(info))
        self.assertEqual(mounts, [f"{self.root}/GDrive", f"{self.root}/pCloudDrive"])
        self.assertEqual(module.mount_of(f"{self.root}/GDrive/Notes", mounts),
                         f"{self.root}/GDrive")
        self.assertIsNone(module.mount_of(f"{self.root}/Vault/x", mounts))
        self.assertIsNone(module.mount_of("gdrive:Notes", mounts))
        self.assertIsNone(module.mount_of(f"{self.root}/plain/x", mounts))
        with self.assertRaises(ValueError) as caught:
            module.guard_paths([f"{self.root}/GDrive/Notes", "gdrive:Notes"], mounts)
        self.assertIn("--no-guard", str(caught.exception))
        module.guard_paths([str(self.src), "gdrive:Notes"], mounts)   # no raise

    # ── building the call ───────────────────────────────────────────────────

    def test_defaults_and_drive_flag(self):
        types = {"gdrive": "drive", "box": "s3"}
        drive = module.build_command("copy", ["a", "gdrive:b"], "/usr/bin/rclone", types)
        self.assertEqual(drive[1], "copy")
        for flag in module.DEFAULTS + module.DRIVE_FLAGS:
            self.assertIn(flag, drive)
        self.assertEqual(drive[-2:], ["a", "gdrive:b"])
        other = module.build_command("copy", ["a", "box:b"], "/usr/bin/rclone", types)
        self.assertNotIn("--drive-stop-on-upload-limit", other)
        self.assertIn("--dry-run", module.build_command(
            "preview", ["a", "gdrive:b"], "/usr/bin/rclone", types))
        self.assertEqual(module.build_command(
            "mirror", ["a", "b"], "/usr/bin/rclone", types)[1], "sync")
        self.assertEqual(module.build_command(
            "move", ["a", "b"], "/usr/bin/rclone", types)[1], "move")
        detached = module.build_command("copy", ["a", "b"], "/usr/bin/rclone",
                                        types, progress=False)
        self.assertIn("--stats-one-line", detached)
        self.assertNotIn("--progress", detached)

    def test_wrapper_flags_are_positional_free(self):
        for argv in (["--command", "copy", "a", "b"], ["copy", "--command", "a", "b"],
                     ["copy", "a", "b", "--command"]):
            mode, rest, options = module.parse_cli(argv)
            self.assertEqual((mode, rest), ("copy", ["a", "b"]), argv)
            self.assertTrue(options["command"], argv)
        mode, rest, options = module.parse_cli(["job", "--name", "media", "a", "b"])
        self.assertEqual((mode, options["name"], rest), ("job", "media", ["a", "b"]))
        # everything after -- belongs to rclone, wrapper flags included
        mode, rest, options = module.parse_cli(["copy", "a", "b", "--", "--command"])
        self.assertFalse(options["command"])
        self.assertEqual(rest, ["a", "b", "--", "--command"])
        with self.assertRaises(ValueError):
            module.parse_cli(["copy", "a", "b", "--name"])

    def test_destructive_modes_need_consent(self):
        for mode in ("mirror", "move"):
            result = self.run_rcx(mode, self.src, self.dst, expected=2)
            self.assertIn("--yes", result.stderr)
            self.assertEqual(list(self.dst.iterdir()), [])
        self.assertIn("sync", self.run_rcx("mirror", "--yes", "--command",
                                           self.src, self.dst).stdout)

    def test_job_units(self):
        self.assertEqual(module.unit_name("gdrive:Backup/Media/Video Library"),
                         "rcx-video-library")
        self.assertEqual(module.unit_name("/mnt/ssd/Media/"), "rcx-media")
        self.assertEqual(module.unit_name("gdrive:"), "rcx-gdrive")
        result = self.run_rcx("job", "--command", "--name", "unit test",
                              self.src, "gdrive:x")
        self.assertIn("systemd-run --user --unit=rcx-unit-test", result.stdout)
        self.assertIn("--stats-one-line", result.stdout)
        self.assertNotIn("--progress", result.stdout)
        # relative paths are resolved, since the unit does not inherit the cwd
        relative = subprocess.run([str(RCX), "job", "--command", "source dir", "gdrive:x"],
                                  env=self.env, cwd=self.root, capture_output=True,
                                  text=True, timeout=60)
        self.assertIn(str(self.src), relative.stdout)

    # ── real transfers, all local ───────────────────────────────────────────

    def test_copy_check_and_mirror(self):
        self.run_rcx(self.src, self.dst)
        self.assertEqual((self.dst / "media/a.bin").read_bytes(), b"a" * 4096)
        self.assertEqual((self.dst / "index/a.bin").read_bytes(), b"a" * 4096)
        self.run_rcx("check", self.src, self.dst)
        (self.dst / "extra.bin").write_bytes(b"x")
        self.run_rcx("check", "--both", self.src, self.dst, expected=1)
        self.run_rcx("check", self.src, self.dst)          # --one-way ignores extras
        self.run_rcx("mirror", "--yes", self.src, self.dst)
        self.assertFalse((self.dst / "extra.bin").exists())

    def test_preview_changes_nothing_and_counts_hardlinks(self):
        result = self.run_rcx("preview", self.src, self.dst)
        self.assertEqual(list(self.dst.iterdir()), [])
        self.assertIn("hardlinks:", result.stdout)
        self.assertIn("4.0 KiB", result.stdout)            # the linked copy, once
        report = module.hardlink_report(str(self.src))
        self.assertEqual(report["duplicated"], 4096)
        self.assertEqual(report["wire"], 4096 * 2 + 2048)
        self.assertEqual(report["disk"], 4096 + 2048)
        self.assertIsNone(module.hardlink_report("gdrive:x"))

    def test_move_removes_sources_only_with_consent(self):
        self.run_rcx("move", "--yes", self.src / "media", self.dst)
        self.assertFalse((self.src / "media/a.bin").exists())
        self.assertTrue((self.dst / "a.bin").exists())

    def test_raw_and_help_and_cheat(self):
        native = subprocess.run(["rclone", "version"], capture_output=True, text=True)
        self.assertEqual(self.run_rcx("raw", "version").stdout, native.stdout)
        self.assertIn("rcx", self.run_rcx("--version").stdout)
        self.assertIn("usage:", self.run_rcx("--help").stdout)
        self.assertIn("job ·", self.run_rcx("cheat", "job").stdout)
        self.run_rcx("cheat", "nonexistent", expected=2)
        alias = subprocess.run([str(RCX.with_name("rcx-cheat")), "limits"],
                               env=self.env, capture_output=True, text=True, timeout=30)
        self.assertEqual(alias.returncode, 0, alias.stderr)
        self.assertIn("750 GB per day", alias.stdout)

    def test_missing_endpoints_are_refused(self):
        self.run_rcx(self.src, expected=2)
        self.run_rcx("copy", expected=2)

    # ── installed systemd units ─────────────────────────────────────────────

    def test_unit_escape_and_names(self):
        self.assertEqual(module.unit_escape("/tmp/plain"), "/tmp/plain")
        self.assertEqual(module.unit_escape("/tmp/with space"), '"/tmp/with space"')
        self.assertEqual(module.unit_escape("100%"), "100%%")          # systemd eats %
        self.assertEqual(module.unit_escape('say "hi"'), '"say \\"hi\\""')
        for good in ("notes", "media-backup", "a.b_c"):
            self.assertEqual(module.valid_name(good), good)
        for bad in ("", "../escape", "has/slash", "-leading", "space name"):
            with self.assertRaises(ValueError, msg=bad):
                module.valid_name(bad)

    def test_render_service_unit(self):
        options = {"command": False, "schedule": None, "boot": False}
        body = module.render_service("notes", "copy", [str(self.src), "gdrive:Notes"],
                                     "/usr/bin/rclone", {"gdrive": "drive"}, options)
        self.assertTrue(body.startswith("# managed by rcx"))
        self.assertIn("Type=oneshot", body)
        # the 90 s default start timeout would kill a multi-hour transfer
        self.assertIn("TimeoutStartSec=infinity", body)
        self.assertIn("Nice=10", body)
        self.assertIn("--drive-stop-on-upload-limit", body)
        self.assertIn("--stats-one-line", body)
        self.assertNotIn("--progress", body)
        self.assertIn(f'"{self.src}"', body)               # quoted: the path has a space
        self.assertNotIn("[Install]", body)                # manual start unless asked
        booted = module.render_service("notes", "copy", [str(self.src), "gdrive:Notes"],
                                       "/usr/bin/rclone", {}, dict(options, boot=True))
        self.assertIn("WantedBy=default.target", booted)
        mirror = module.render_service("m", "mirror", ["a", "b"], "/usr/bin/rclone", {}, options)
        self.assertIn("rclone_sync", mirror)               # Documentation= matches the verb

    def test_render_timer_and_mount_units(self):
        timer = module.render_timer("notes", "daily")
        self.assertIn("OnCalendar=daily", timer)
        self.assertIn("Persistent=true", timer)            # fires late if the machine was off
        self.assertIn("Unit=rcx-notes.service", timer)
        self.assertIn("WantedBy=timers.target", timer)
        mount = module.render_mount("gdrive", "gdrive:", "/home/u/GDrive")
        self.assertIn("Type=notify", mount)
        self.assertIn("--vfs-cache-mode=full", mount)
        self.assertIn("AssertPathIsDirectory=/home/u/GDrive", mount)
        self.assertIn("fusermount3 -uz", mount)

    def test_service_create_dry_run_writes_nothing(self):
        module.UNIT_DIR = str(self.root / "units")
        result = self.run_rcx("service", "create", "--command", "--schedule", "daily",
                              "--name", "notes", self.src, "gdrive:Notes")
        self.assertIn("OnCalendar=daily", result.stdout)
        self.assertIn("TimeoutStartSec=infinity", result.stdout)
        self.assertFalse((self.root / "units").exists())

    def test_service_write_show_and_remove(self):
        module.UNIT_DIR = str(self.root / "units")
        options = {"command": False, "schedule": None, "boot": False, "now": False,
                   "force": False}
        module.service_create("notes", "copy", [str(self.src), str(self.dst)],
                              "/usr/bin/rclone", {}, options, False)
        path = module.unit_path("notes")
        self.assertTrue(os.path.exists(path))
        self.assertTrue(module.is_ours(path))
        with self.assertRaises(ValueError):                # no silent clobbering
            module.service_create("notes", "copy", [str(self.src), str(self.dst)],
                                  "/usr/bin/rclone", {}, options, False)
        module.service_create("notes", "copy", [str(self.src), str(self.dst)],
                              "/usr/bin/rclone", {}, dict(options, force=True), False)
        module.service_show("notes", False)
        module.service_remove("notes", False)
        self.assertFalse(os.path.exists(path))
        with self.assertRaises(ValueError):
            module.service_remove("notes", False)

    def test_hand_written_units_are_never_touched(self):
        module.UNIT_DIR = str(self.root / "units")
        os.makedirs(module.UNIT_DIR, exist_ok=True)
        foreign = module.unit_path("foreign")
        Path(foreign).write_text("[Unit]\nDescription=mine\n[Service]\nExecStart=/bin/true\n")
        self.assertFalse(module.is_ours(foreign))
        options = {"command": False, "schedule": None, "boot": False, "now": False,
                   "force": True}
        with self.assertRaises(ValueError) as caught:
            module.service_create("foreign", "copy", [str(self.src), str(self.dst)],
                                  "/usr/bin/rclone", {}, options, False)
        self.assertIn("not written by rcx", str(caught.exception))
        with self.assertRaises(ValueError):
            module.service_remove("foreign", False)
        self.assertTrue(os.path.exists(foreign))           # still there, untouched

    def test_scheduled_mirror_service_needs_consent(self):
        result = self.run_rcx("service", "create", "mirror", "--schedule", "daily",
                              self.src, self.dst, expected=2)
        self.assertIn("--yes", result.stderr)


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