1#!/usr/bin/env python3
2"""Mac VM protocol and failure tests; no real guest or credentials required."""
3import contextlib
4import fcntl
5from importlib import import_module
6import io
7import json
8import os
9from pathlib import Path
10import signal
11import subprocess
12import sys
13import tempfile
14import time
15import unittest
16from unittest.mock import patch
17
18bridge = import_module("mac-vm-bridge")
19backend = import_module("mac-vms")
20
21
22class MacVMTests(unittest.TestCase):
23 def test_protocol_rejects_arbitrary_commands_and_unbounded_clipboards(self):
24 for request in [{"action": "exec", "command": "id"}, {"action": "status", "name": "other"},
25 {"action": "clipboard", "text": "a" * 262145}, ["status"],
26 {"action": "clipboard", "text": 42}]:
27 with self.subTest(request=str(request)[:80]), \
28 patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \
29 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "lifecycle") as lifecycle:
30 with self.assertRaises(ValueError):
31 bridge.main()
32 tart.assert_not_called()
33 lifecycle.assert_not_called()
34
35 def test_unicode_clipboard_is_stdin_and_accepts_full_byte_limit(self):
36 value = "🦊" * (262144 // 4)
37 request = json.dumps({"action": "clipboard", "text": value}).encode() + b"\n"
38 with patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(request))), \
39 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "respond") as respond:
40 bridge.main()
41 self.assertEqual(tart.call_args.args, ("exec", "-i", "gui-agent", "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy"))
42 self.assertEqual(tart.call_args.kwargs["input"], value.encode())
43 respond.assert_called_once_with({"value": None})
44
45 def test_offline_inventory_keeps_identity_and_last_observed_hardware(self):
46 @contextlib.contextmanager
47 def connected(*args, **kwargs):
48 yield {"state": "running", "vcpus": 28, "memory": 48 * 2**30, "agent": "connected",
49 "pendingAction": None, "disk": {"capacity": 128 * 2**30, "allocation": 42 * 2**30},
50 "mac": "00:11:22:33:44:55"}, None
51 with tempfile.TemporaryDirectory() as directory, \
52 patch.object(backend, "CONFIG", {"name": "mac-fixture", "owner": "fixture-owner"}), \
53 patch.object(backend, "CACHE", Path(directory) / "cache.json"):
54 with patch.object(backend, "connect", side_effect=ValueError("offline")):
55 first = backend.domain()[0]
56 self.assertIsNone(first["memory"])
57 self.assertEqual(first["state"], "unreachable")
58 with patch.object(backend, "connect", connected):
59 live = backend.domain()[0]
60 self.assertEqual(live["state"], "running")
61 self.assertEqual(backend.CACHE.stat().st_mode & 0o777, 0o600)
62 with patch.object(backend.os, "replace", side_effect=OSError("disk full")):
63 self.assertEqual(backend.domain()[0]["state"], "running")
64 with patch.object(backend, "connect", side_effect=ValueError("offline")):
65 offline = backend.domain()[0]
66 self.assertEqual(offline["name"], "mac-fixture")
67 self.assertEqual(offline["owner"], "fixture-owner")
68 self.assertTrue(offline["ownerOnly"])
69 self.assertEqual(backend.handle("owner", {}), {"owner": "fixture-owner", "ownerOnly": True})
70 self.assertEqual(offline["memory"], live["memory"])
71 self.assertEqual(offline["state"], "unreachable")
72 self.assertIsNone(offline["agent"])
73 self.assertIsNone(offline["pendingAction"])
74
75 def test_unsupported_operations_never_contact_mac(self):
76 with patch.object(backend, "connect") as connect:
77 for action in ["delete", "update", "preset", "media"]:
78 with self.subTest(action=action), self.assertRaises(ValueError):
79 backend.handle(action, {"name": "mac-fixture"})
80 with self.assertRaises(ValueError):
81 backend.handle("act", {"action": "destroy"})
82 connect.assert_not_called()
83
84 def test_lifecycle_timeout_reaps_commands_but_preserves_detached_runner(self):
85 with tempfile.TemporaryDirectory() as directory:
86 root = Path(directory)
87 fixture = root / "lifecycle.py"
88 fixture.write_text('''import fcntl, os, pathlib, subprocess, sys, time
89root = pathlib.Path(__file__).parent
90lock = (root / "lock").open("w")
91fcntl.flock(lock, fcntl.LOCK_EX)
92child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"])
93runner = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True)
94(root / "pids").write_text(str(child.pid) + " " + str(runner.pid))
95time.sleep(60)
96''')
97 original = subprocess.Popen
98 def start(*args, **kwargs):
99 process = original(*args, **kwargs)
100 wait = process.wait
101 process.wait = lambda timeout=None: wait(timeout=0.5 if timeout == 210 else timeout)
102 return process
103 try:
104 with patch.object(bridge.vm, "__file__", str(fixture)), patch.object(bridge.subprocess, "Popen", start):
105 with self.assertRaises(subprocess.TimeoutExpired):
106 bridge.lifecycle("suspend")
107 child, runner = map(int, (root / "pids").read_text().split())
108 os.kill(runner, 0)
109 deadline = time.monotonic() + 5
110 while time.monotonic() < deadline:
111 state = subprocess.run(["ps", "-p", str(child), "-o", "stat="], capture_output=True, text=True).stdout.strip()
112 if not state or state.startswith("Z"):
113 break
114 time.sleep(0.02)
115 else:
116 self.fail("unfinished lifecycle command survived its helper")
117 with (root / "lock").open("r") as lock:
118 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
119 finally:
120 if (root / "pids").exists():
121 for pid in map(int, (root / "pids").read_text().split()):
122 try:
123 os.kill(pid, signal.SIGKILL)
124 except ProcessLookupError:
125 pass
126
127
128if __name__ == "__main__":
129 unittest.main()