| 1 | #!/usr/bin/env python3 |
| 2 | """Mac VM protocol and failure tests; no real guest or credentials required.""" |
| 3 | import contextlib |
| 4 | import fcntl |
| 5 | from importlib import import_module |
| 6 | import io |
| 7 | import json |
| 8 | import os |
| 9 | from pathlib import Path |
| 10 | import signal |
| 11 | import subprocess |
| 12 | import sys |
| 13 | import tempfile |
| 14 | import time |
| 15 | import unittest |
| 16 | from unittest.mock import patch |
| 17 | |
| 18 | bridge = import_module("mac-vm-bridge") |
| 19 | backend = import_module("mac-vms") |
| 20 | |
| 21 | |
| 22 | FIXTURE = {"vms": [{"name": "mac-fixture", "owner": "fixture-owner", "console": True, "suspend": True}, |
| 23 | {"name": "locked-fixture", "owner": "fixture-owner", "console": False, "suspend": False}]} |
| 24 | |
| 25 | |
| 26 | class MacVMTests(unittest.TestCase): |
| 27 | def test_protocol_rejects_arbitrary_commands_and_unbounded_clipboards(self): |
| 28 | for request in [{"action": "exec", "command": "id"}, {"action": "status", "name": "other"}, |
| 29 | {"action": "clipboard", "text": "a" * 262145}, ["status"], |
| 30 | {"action": "clipboard", "text": 42}, {"action": "status", "vm": "other"}, |
| 31 | {"action": "status", "vm": ["m3-devbox"]}]: |
| 32 | with self.subTest(request=str(request)[:80]), \ |
| 33 | patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \ |
| 34 | patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "lifecycle") as lifecycle: |
| 35 | with self.assertRaises(ValueError): |
| 36 | bridge.main() |
| 37 | tart.assert_not_called() |
| 38 | lifecycle.assert_not_called() |
| 39 | |
| 40 | def test_unicode_clipboard_is_stdin_and_accepts_full_byte_limit(self): |
| 41 | value = "🦊" * (262144 // 4) |
| 42 | request = json.dumps({"action": "clipboard", "text": value}).encode() + b"\n" |
| 43 | with patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(request))), \ |
| 44 | patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "respond") as respond: |
| 45 | bridge.main() |
| 46 | self.assertEqual(tart.call_args.args, ("exec", "-i", "gui-agent", "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy")) |
| 47 | self.assertEqual(tart.call_args.kwargs["input"], value.encode()) |
| 48 | respond.assert_called_once_with({"value": None}) |
| 49 | |
| 50 | def test_offline_inventory_keeps_identity_and_last_observed_hardware(self): |
| 51 | @contextlib.contextmanager |
| 52 | def connected(*args, **kwargs): |
| 53 | yield {"state": "running", "vcpus": 28, "memory": 48 * 2**30, "agent": "connected", |
| 54 | "pendingAction": None, "disk": {"capacity": 128 * 2**30, "allocation": 42 * 2**30}, |
| 55 | "mac": "00:11:22:33:44:55"}, None |
| 56 | with tempfile.TemporaryDirectory() as directory, \ |
| 57 | patch.object(backend, "CONFIG", FIXTURE), \ |
| 58 | patch.object(backend, "CACHE", Path(directory) / "cache.json"): |
| 59 | with patch.object(backend, "connect", side_effect=ValueError("offline")): |
| 60 | first = backend.domain()[0] |
| 61 | self.assertIsNone(first["memory"]) |
| 62 | self.assertEqual(first["state"], "unreachable") |
| 63 | with patch.object(backend, "connect", connected): |
| 64 | live = backend.domain()[0] |
| 65 | self.assertEqual(live["state"], "running") |
| 66 | self.assertEqual(backend.CACHE.stat().st_mode & 0o777, 0o600) |
| 67 | with patch.object(backend.os, "replace", side_effect=OSError("disk full")): |
| 68 | self.assertEqual(backend.domain()[0]["state"], "running") |
| 69 | with patch.object(backend, "connect", side_effect=ValueError("offline")): |
| 70 | offline = backend.domain()[0] |
| 71 | self.assertEqual(offline["name"], "mac-fixture") |
| 72 | self.assertEqual(offline["owner"], "fixture-owner") |
| 73 | self.assertTrue(offline["ownerOnly"]) |
| 74 | self.assertEqual(backend.handle("owner", {"name": "mac-fixture"}), {"owner": "fixture-owner", "ownerOnly": True}) |
| 75 | self.assertEqual(offline["memory"], live["memory"]) |
| 76 | self.assertEqual(offline["state"], "unreachable") |
| 77 | self.assertIsNone(offline["agent"]) |
| 78 | self.assertIsNone(offline["pendingAction"]) |
| 79 | |
| 80 | def test_unsupported_operations_never_contact_mac(self): |
| 81 | with patch.object(backend, "CONFIG", FIXTURE), patch.object(backend, "connect") as connect: |
| 82 | for action in ["delete", "update", "preset", "media"]: |
| 83 | with self.subTest(action=action), self.assertRaises(ValueError): |
| 84 | backend.handle(action, {"name": "mac-fixture"}) |
| 85 | with self.assertRaises(ValueError): |
| 86 | backend.handle("act", {"name": "mac-fixture", "action": "destroy"}) |
| 87 | connect.assert_not_called() |
| 88 | |
| 89 | def test_each_vm_keeps_its_own_features_and_requests_name_it(self): |
| 90 | @contextlib.contextmanager |
| 91 | def connected(name, request, timeout=10): |
| 92 | yield {"state": "running", "vcpus": 8, "memory": 2**34, "agent": None, "pendingAction": None, |
| 93 | "disk": {"capacity": 2**36, "allocation": 2**35}, "mac": "00:11:22:33:44:55", "name": name}, None |
| 94 | with tempfile.TemporaryDirectory() as directory, patch.object(backend, "CONFIG", FIXTURE), \ |
| 95 | patch.object(backend, "CACHE", Path(directory) / "cache.json"): |
| 96 | with patch.object(backend, "connect", connected): |
| 97 | full, locked = backend.domain() |
| 98 | self.assertEqual((full["name"], full["console"], "suspend" in full["capabilities"]), ("mac-fixture", True, True)) |
| 99 | self.assertEqual((locked["name"], locked["console"], "suspend" in locked["capabilities"]), ("locked-fixture", False, False)) |
| 100 | self.assertIn("computer", locked["capabilities"]) |
| 101 | self.assertTrue(backend.owns("locked-fixture") and not backend.owns("other")) |
| 102 | with patch.object(backend, "connect") as connect: |
| 103 | for action, payload in [("console", {}), ("act", {"action": "suspend"}), ("act", {"action": "resume"})]: |
| 104 | with self.subTest(operation=action, payload=payload), self.assertRaises(ValueError): |
| 105 | backend.handle(action, {"name": "locked-fixture", **payload}) |
| 106 | connect.assert_not_called() |
| 107 | self.assertEqual(backend.handle("console", {"name": "mac-fixture"}), {"remote": True, "name": "mac-fixture"}) |
| 108 | with patch.object(backend, "connect", connected), patch.object(backend, "CACHE", Path(directory) / "cache.json"): |
| 109 | self.assertEqual(backend.handle("computer", {"name": "locked-fixture", "request": {"action": "status"}})["name"], "locked-fixture") |
| 110 | with patch.object(backend, "connect", side_effect=ValueError("offline")) as offline: |
| 111 | self.assertEqual([value["state"] for value in backend.domain()], ["unreachable", "unreachable"]) |
| 112 | self.assertEqual([value["memory"] for value in backend.domain()], [2**34, 2**34]) |
| 113 | self.assertEqual({call.args[0] for call in offline.call_args_list}, {"mac-fixture", "locked-fixture"}) |
| 114 | |
| 115 | def test_bridge_serves_only_named_vms_and_hosts_without_a_name_get_the_devbox(self): |
| 116 | def run(request): |
| 117 | with patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \ |
| 118 | patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "respond") as respond, \ |
| 119 | patch.object(bridge, "status", return_value={"state": "devbox"}) as status, \ |
| 120 | patch.object(bridge, "locked_status", return_value={"state": "locked"}) as locked_status, \ |
| 121 | patch.object(bridge, "lifecycle") as lifecycle, patch.object(bridge, "locked_power") as locked_power: |
| 122 | bridge.main() |
| 123 | return tart, respond, status, locked_status, lifecycle, locked_power |
| 124 | _, respond, status, locked_status, *_ = run({"action": "status"}) |
| 125 | respond.assert_called_once_with({"value": {"state": "devbox", "name": "gui-agent"}}) |
| 126 | _, respond, status, locked_status, *_ = run({"action": "status", "vm": "m3-phoenix-box"}) |
| 127 | respond.assert_called_once_with({"value": {"state": "locked", "name": "m3-phoenix-box"}}) |
| 128 | locked_status.assert_called_once_with("m3-phoenix-box") |
| 129 | status.assert_not_called() |
| 130 | tart, *_ = run({"action": "clipboard", "text": "x", "vm": "m3-phoenix-box"}) |
| 131 | self.assertEqual(tart.call_args.args[:3], ("exec", "-i", "m3-phoenix-box")) |
| 132 | *_, lifecycle, locked_power = run({"action": "reboot", "vm": "m3-phoenix-box"}) |
| 133 | locked_power.assert_called_once_with("m3-phoenix-box", "reboot") |
| 134 | lifecycle.assert_not_called() |
| 135 | *_, lifecycle, locked_power = run({"action": "shutdown", "vm": "m3-devbox"}) |
| 136 | lifecycle.assert_called_once_with("stop") |
| 137 | locked_power.assert_not_called() |
| 138 | for request in [{"action": "suspend", "vm": "m3-phoenix-box"}, {"action": "resume", "vm": "m3-phoenix-box"}, |
| 139 | {"action": "console", "vm": "m3-phoenix-box"}]: |
| 140 | with self.subTest(request=request), self.assertRaises(ValueError): |
| 141 | run(request) |
| 142 | |
| 143 | def test_locked_vm_start_waits_until_tart_reports_it_running(self): |
| 144 | states = iter([False, False, True]) |
| 145 | def tart(*args, **kwargs): |
| 146 | if args[0] == "get": |
| 147 | return subprocess.CompletedProcess(args, 0, stdout=json.dumps({"Running": next(states)})) |
| 148 | with patch.object(bridge.vm, "tart", side_effect=tart) as run, patch.object(bridge.subprocess, "run") as launch, \ |
| 149 | patch.object(bridge.time, "sleep"): |
| 150 | bridge.locked_power("m3-phoenix-box", "reboot") |
| 151 | self.assertEqual(run.call_args_list[0].args, ("stop", "m3-phoenix-box")) |
| 152 | launch.assert_called_once() |
| 153 | self.assertEqual(sum(call.args[0] == "get" for call in run.call_args_list), 3) |
| 154 | |
| 155 | def test_lifecycle_timeout_reaps_commands_but_preserves_detached_runner(self): |
| 156 | with tempfile.TemporaryDirectory() as directory: |
| 157 | root = Path(directory) |
| 158 | fixture = root / "lifecycle.py" |
| 159 | fixture.write_text('''import fcntl, os, pathlib, subprocess, sys, time |
| 160 | root = pathlib.Path(__file__).parent |
| 161 | lock = (root / "lock").open("w") |
| 162 | fcntl.flock(lock, fcntl.LOCK_EX) |
| 163 | child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) |
| 164 | runner = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True) |
| 165 | (root / "pids").write_text(str(child.pid) + " " + str(runner.pid)) |
| 166 | time.sleep(60) |
| 167 | ''') |
| 168 | original = subprocess.Popen |
| 169 | def start(*args, **kwargs): |
| 170 | process = original(*args, **kwargs) |
| 171 | wait = process.wait |
| 172 | process.wait = lambda timeout=None: wait(timeout=0.5 if timeout == 210 else timeout) |
| 173 | return process |
| 174 | try: |
| 175 | with patch.object(bridge.vm, "__file__", str(fixture)), patch.object(bridge.subprocess, "Popen", start): |
| 176 | with self.assertRaises(subprocess.TimeoutExpired): |
| 177 | bridge.lifecycle("suspend") |
| 178 | child, runner = map(int, (root / "pids").read_text().split()) |
| 179 | os.kill(runner, 0) |
| 180 | deadline = time.monotonic() + 5 |
| 181 | while time.monotonic() < deadline: |
| 182 | state = subprocess.run(["ps", "-p", str(child), "-o", "stat="], capture_output=True, text=True).stdout.strip() |
| 183 | if not state or state.startswith("Z"): |
| 184 | break |
| 185 | time.sleep(0.02) |
| 186 | else: |
| 187 | self.fail("unfinished lifecycle command survived its helper") |
| 188 | with (root / "lock").open("r") as lock: |
| 189 | fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) |
| 190 | finally: |
| 191 | if (root / "pids").exists(): |
| 192 | for pid in map(int, (root / "pids").read_text().split()): |
| 193 | try: |
| 194 | os.kill(pid, signal.SIGKILL) |
| 195 | except ProcessLookupError: |
| 196 | pass |
| 197 | |
| 198 | |
| 199 | if __name__ == "__main__": |
| 200 | unittest.main() |