跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

macos_guest_e2e_test.go

340 行 · 13.6 KB历史下载
1//go:build darwin && arm64 && cgo && e2e && !no_vz
2
3package vm
4
5import (
6 "bytes"
7 "context"
8 "encoding/json"
9 "github.com/google/uuid"
10 "image/png"
11 "io"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "strings"
16 "testing"
17 "time"
18
19 "al.essio.dev/pkg/shellescape"
20 "github.com/sylvinus/agent-vm/internal/cage"
21 "github.com/sylvinus/agent-vm/internal/guestos"
22 "github.com/sylvinus/agent-vm/internal/managedproxy"
23)
24
25// Run the signed test binary with CAGE_TEST_MACOS_IPSW pointing to an Apple
26// restore image. CAGE_TEST_CLAUDE_DMG optionally exercises the official app.
27func TestMacOSGuest(t *testing.T) {
28 image := os.Getenv("CAGE_TEST_MACOS_IPSW")
29 if image == "" {
30 t.Skip("set CAGE_TEST_MACOS_IPSW to a local Apple restore image")
31 }
32 if !filepath.IsAbs(image) {
33 t.Fatal("CAGE_TEST_MACOS_IPSW must be absolute")
34 }
35 if info, err := os.Stat(image); err != nil || !info.Mode().IsRegular() {
36 t.Fatalf("invalid restore image %q: %v", image, err)
37 }
38 ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
39 defer cancel()
40 profile, err := os.MkdirTemp("/tmp", "cgmac-")
41 if err != nil {
42 t.Fatal(err)
43 }
44 t.Cleanup(func() {
45 if t.Failed() && os.Getenv("CAGE_TEST_KEEP_FAILED_VM") == "1" {
46 t.Log("Retained this test's private VM for diagnosis:", profile)
47 return
48 }
49 if err := os.RemoveAll(profile); err != nil {
50 t.Error(err)
51 }
52 })
53 configPath := filepath.Join(profile, "config.json")
54 state := filepath.Join(profile, "state")
55 t.Setenv(cage.ConfigEnv, configPath)
56 t.Setenv("AGENT_VM_STATE_DIR", state)
57 t.Setenv("LIMA_HOME", filepath.Join(state, "lima"))
58 t.Setenv("LIMA_CACHE_HOME", filepath.Join(profile, "cache"))
59 t.Setenv("AGENT_VM_UNSAFE_OPEN_NETWORK", "")
60 t.Setenv("AGENT_VM_UNSAFE_WRITABLE_GIT", "")
61 t.Setenv("AGENT_VM_UNSAFE_DISABLE_SECURITY_PROMPTS", "")
62 // Use a private, unstarted proxy configuration. Installation uses local
63 // media and SSH. No part of this test requires external guest traffic.
64 proxy, err := managedproxy.Load(profile)
65 if err != nil {
66 t.Fatal(err)
67 }
68 if err := proxy.Import("offline", "", []byte("proxies: [{name: offline, type: socks5, server: 127.0.0.1, port: 9}]"), "offline", 0, ""); err != nil {
69 t.Fatal(err)
70 }
71 proxy.Selected = proxy.Sources[0].Nodes[0].ID
72 proxy.Revision = "offline"
73 if err := proxy.Save(profile); err != nil {
74 t.Fatal(err)
75 }
76 cfg := cage.DefaultConfig()
77 cfg.ProxyURL, cfg.ProxyRevision = proxy.Endpoint(), proxy.Revision
78 writeJSON := func(path string, value any) {
79 t.Helper()
80 data, err := json.Marshal(value)
81 if err != nil {
82 t.Fatal(err)
83 }
84 if err := os.WriteFile(path, data, 0600); err != nil {
85 t.Fatal(err)
86 }
87 }
88 writeJSON(configPath, cfg)
89 writeJSON(cage.ResourceAllocationPath(configPath), cage.ResourceAllocation{MemoryGiB: 4, CPUs: 2})
90 l, err := NewLima(filepath.Join(state, "lima"), state)
91 if err != nil {
92 t.Fatal(err)
93 }
94 const name = "mac"
95 if err := l.CreateMacOSFromIPSW(ctx, name, image, Settings{CPUs: 2, MemoryGiB: 4, DiskGiB: 64}, os.Stderr); err != nil {
96 t.Fatal(err)
97 }
98 t.Cleanup(func() {
99 cleanup, cancel := context.WithTimeout(context.Background(), time.Minute)
100 defer cancel()
101 if err := l.Stop(cleanup, name); err != nil {
102 t.Error(err)
103 }
104 })
105 t.Log("Restoring a new macOS test VM from local media")
106 if err := l.Start(ctx, name, os.Stderr); err != nil {
107 t.Fatal(err)
108 }
109 run := func(script string, input io.Reader) string {
110 t.Helper()
111 var out bytes.Buffer
112 code, err := l.Shell(ctx, name, ShellOpts{Args: []string{"/bin/sh", "-ec", script}, Stdin: input, Stdout: &out, Stderr: &out})
113 if err != nil || code != 0 {
114 t.Fatalf("guest command failed (%d): %v\n%s", code, err, out.String())
115 }
116 return strings.TrimSpace(out.String())
117 }
118 t.Log(run("test \"$(uname -s)\" = Darwin && /usr/bin/sw_vers && test \"$HOME\" = /Users/cageprovision", nil))
119 run("cd \"$HOME\" && /usr/bin/osacompile -l JavaScript -o cage-qa.scpt -e '6*7' && test \"$(/usr/bin/osascript cage-qa.scpt)\" = 42", nil)
120 serialKey, err := guestos.MacOSInstallHostKey(profile)
121 if err != nil {
122 t.Fatal(err)
123 }
124 guestKey := run("cat /etc/ssh/ssh_host_ed25519_key.pub", nil)
125 if !strings.HasPrefix(guestKey+" ", strings.TrimSpace(string(serialKey))+" ") {
126 t.Fatal("VZ serial key differs from the restored guest identity")
127 }
128 if kit := os.Getenv("CAGE_TEST_MACOS_AUTOMATION_KIT"); kit != "" {
129 // Minimal first-run experiment: the production account receipt and session
130 // configuration run in a newly restored VM, with no daily guest data.
131 tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".")
132 pipe, err := tar.StdoutPipe()
133 if err != nil {
134 t.Fatal(err)
135 }
136 if err := tar.Start(); err != nil {
137 t.Fatal(err)
138 }
139 run(`mkdir "$HOME/automation-kit"; cd "$HOME/automation-kit"; tar -xf -`, pipe)
140 if err := tar.Wait(); err != nil {
141 t.Fatal(err)
142 }
143 password := "Aa7!" + uuid.NewString()
144 run(`umask 077; cat > "$HOME/automation-input"`, strings.NewReader(password+"\n"))
145 admin := func(script string) string {
146 return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
147 }
148 installation := uuid.NewString()
149 admin(`echo macos > /var/db/cage-guest-os; chmod 600 /var/db/cage-guest-os; chown -R root:wheel /Users/cageprovision/automation-kit;
150printf '%s\n' "$(cat /Users/cageprovision/automation-input)" | sysadminctl -addUser cage -fullName cage -password - -home /Users/cage;
151createhomedir -c -u cage >/dev/null;
152/Users/cageprovision/automation-kit/cage-finish-initial-setup prepare ` + installation + ` < /Users/cageprovision/automation-input;
153/bin/bash /Users/cageprovision/automation-kit/configure-macos-session.sh cage ` + installation + ` < /Users/cageprovision/automation-input`)
154 run(`test "$(sudo -S -p '' defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser < "$HOME/password")" = cage`, nil)
155 if err := l.Stop(ctx, name); err != nil {
156 t.Fatal(err)
157 }
158 if err := l.Start(ctx, name, os.Stderr); err != nil {
159 t.Fatal(err)
160 }
161 loggedIn := false
162 for i := 0; i < 60; i++ {
163 if run(`stat -f '%Su' /dev/console`, nil) == "cage" {
164 loggedIn = true
165 break
166 }
167 time.Sleep(time.Second)
168 }
169 if !loggedIn {
170 t.Fatal("guest did not automatically log in")
171 }
172 admin(`! pgrep -x 'Setup Assistant' >/dev/null; uid=$(id -u cage); launchctl print gui/$uid >/dev/null;
173/Users/cageprovision/automation-kit/cage-finish-initial-setup;
174! id -Gn cage | grep -qw admin; ! id -Gn cagesetup | grep -qw admin;
175test "$(stat -f %OLp /etc/kcpassword)" = 600`)
176 t.Log("Fresh guest: automatic graphical login, skipped optional Setup Assistant, standard account and retired temporary administrator verified")
177 return
178 }
179 if kit, media := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_KIT"), os.Getenv("CAGE_TEST_MACOS_WORKBENCH_MEDIA"); kit != "" && media != "" {
180 // Exercise the shipped provisioning script in this disposable fresh VM.
181 tar := exec.CommandContext(ctx, "/usr/bin/tar", "--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", media, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "claude.dmg", "cli", "macfuse.pkg")
182 pipe, err := tar.StdoutPipe()
183 if err != nil {
184 t.Fatal(err)
185 }
186 tar.Stderr = os.Stderr
187 if err := tar.Start(); err != nil {
188 t.Fatal(err)
189 }
190 run(`mkdir "$HOME/kit"; cd "$HOME/kit"; tar -xf -; mv macfuse.pkg project/macfuse.pkg`, pipe)
191 if err := tar.Wait(); err != nil {
192 t.Fatal(err)
193 }
194 password := "Aa7!" + uuid.NewString()
195 run(`umask 077; cat > "$HOME/login-input"`, strings.NewReader(password+"\n"))
196 admin := func(script string) string {
197 return run("sudo -S -p '' /bin/bash -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
198 }
199 stage := admin(`mktemp -d /private/var/tmp/cage-install.XXXXXXXX`)
200 admin(`mv /Users/cageprovision/kit ` + stage + `/kit; chown -R root:wheel ` + stage + `; cd /; /bin/bash ` + stage + `/kit/provision-macos-workbench.sh ` + stage + `/kit ` + uuid.NewString() + ` cageprovision < /Users/cageprovision/login-input`)
201 run(`/usr/bin/dscl /Local/Default -authonly cage >/dev/null`, strings.NewReader(password+"\n"))
202 admin(`test "$(dscl . -read /Users/cage NFSHomeDirectory)" = 'NFSHomeDirectory: /Users/cage'; if id -Gn cage | grep -qw admin; then exit 1; fi; dscl . -read /Users/cageprovision IsHidden | grep -q ": 1$"; /usr/local/libexec/cage-finish-initial-setup`)
203 admin(`if id -Gn cagesetup | grep -qw admin; then exit 1; fi; dscl . -read /Users/cagesetup UserShell | grep -q /usr/bin/false`)
204 t.Log("Fresh cage account, user-selected password, ordinary privileges and temporary administrator retirement verified")
205 }
206 verifyMacOSGuestNetwork(t, ctx, filepath.Join(state, "lima", name), run)
207 verifyMacOSProjectTransfer(t, ctx, l, name)
208 if err := l.Stop(ctx, name); err != nil {
209 t.Fatal(err)
210 }
211 if err := l.Start(ctx, name, os.Stderr); err != nil {
212 t.Fatal(err)
213 }
214 run("test \"$(/usr/bin/osascript \"$HOME/cage-qa.scpt\")\" = 42", nil)
215 t.Log("Native compilation, closed external connection and persistent disk verified")
216 if dmg := os.Getenv("CAGE_TEST_CLAUDE_DMG"); dmg != "" {
217 h, err := os.ReadFile("../../scripts/guest-os/claude-desktop-macos.sh")
218 if err != nil {
219 t.Fatal(err)
220 }
221 run("umask 077; cat > \"$HOME/claude-desktop-qa.sh\"", bytes.NewReader(h))
222 f, err := os.Open(dmg)
223 if err != nil {
224 t.Fatal(err)
225 }
226 defer f.Close()
227 run("umask 077; cat > \"$HOME/Claude.dmg\"", f)
228 // Lima generates a random password inside this new VM. Use it only
229 // for this guest's privileged setup, without transferring it to the host.
230 admin := func(script string) string {
231 t.Helper()
232 return run("sudo -S -p '' -- /bin/sh -ec "+shellescape.Quote(script)+` < "$HOME/password"`, nil)
233 }
234 admin("umask 022; echo macos > /var/db/cage-guest-os")
235 t.Log(admin("/bin/bash /Users/cageprovision/claude-desktop-qa.sh install /Users/cageprovision/Claude.dmg"))
236 t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" inspect", nil))
237 if helper := os.Getenv("CAGE_TEST_CLAUDE_WINDOW"); helper != "" {
238 t.Log(run("/bin/bash \"$HOME/claude-desktop-qa.sh\" launch", nil))
239 f, err := os.Open(helper)
240 if err != nil {
241 t.Fatal(err)
242 }
243 defer f.Close()
244 run(`umask 077; cat > "$HOME/window-helper"`, f)
245 admin("mkdir -p /usr/local/libexec && install -o root -g wheel -m 755 /Users/cageprovision/window-helper /usr/local/libexec/cage-claude-window")
246 var frame, stderr bytes.Buffer
247 code, err := l.Shell(ctx, name, ShellOpts{
248 Args: []string{"/bin/sh", "-ec", `sudo -S -p '' /bin/launchctl asuser "$(id -u)" sudo -nu "$(id -un)" -- /usr/local/libexec/cage-claude-window < "$HOME/password"`},
249 Stdout: &frame, Stderr: &stderr,
250 })
251 if err != nil || code != 0 {
252 t.Fatalf("single-window capture (%d): %v %s", code, err, stderr.String())
253 }
254 img, err := png.DecodeConfig(&frame)
255 if err != nil || img.Width <= 0 || img.Height <= 0 {
256 t.Fatalf("invalid window PNG: %v", err)
257 }
258 t.Logf("Verified Claude window PNG, %d × %d", img.Width, img.Height)
259 }
260 }
261}
262
263// A failed request alone could mean that the guest network is misconfigured.
264// Check that each guest probe reached the closed gate for this instance.
265func verifyMacOSGuestNetwork(t *testing.T, ctx context.Context, instance string, run func(string, io.Reader) string) {
266 t.Helper()
267 client, err := cage.OpenGateClient(instance)
268 if err != nil {
269 t.Fatal(err)
270 }
271 status := func() cage.GateStatus {
272 t.Helper()
273 s, err := client.Status(ctx)
274 if err != nil {
275 t.Fatal(err)
276 }
277 if s.Mode != cage.GateClosed {
278 t.Fatalf("expected a closed network gate, got %q", s.Mode)
279 }
280 return s
281 }
282 check := func(label, script string, denied func(cage.GateCounters) uint64) {
283 t.Helper()
284 before := status()
285 run(script, nil)
286 deadline := time.Now().Add(3 * time.Second)
287 for {
288 after := status()
289 if after.RunID != before.RunID || after.Epoch != before.Epoch {
290 t.Fatalf("network gate changed during %s probe", label)
291 }
292 if n := denied(after.Counters); n > denied(before.Counters) {
293 t.Logf("Closed gate denied guest %s (%d → %d)", label, denied(before.Counters), n)
294 return
295 }
296 if time.Now().After(deadline) {
297 t.Fatalf("host gate did not record the guest %s probe", label)
298 }
299 time.Sleep(100 * time.Millisecond)
300 }
301 }
302 check("TCP", "if /usr/bin/nc -G 2 -z 1.1.1.1 443; then exit 1; fi", func(c cage.GateCounters) uint64 { return c.TCPDenied })
303 // Sending a UDP datagram can succeed locally even when the host drops it.
304 check("UDP", "printf cage | /usr/bin/nc -u -w 1 1.1.1.1 3478", func(c cage.GateCounters) uint64 { return c.UDPDenied })
305 check("DNS", `resolver=$(awk '/^nameserver[[:space:]]/{print $2; exit}' /etc/resolv.conf)
306test -n "$resolver"
307response=$(/usr/bin/dig @"$resolver" +time=2 +tries=1 +noall +comments +answer "cage-check-$(uuidgen).example.com." A) || :
308if printf '%s\n' "$response" | grep -Eq 'status: NOERROR|[[:space:]]IN[[:space:]]+A[[:space:]]'; then exit 1; fi`, func(c cage.GateCounters) uint64 { return c.DNSDenied })
309
310 if _, err := client.BeginCheck(ctx); err != nil {
311 t.Fatal(err)
312 }
313 defer func() {
314 if _, err := client.Close(ctx, "guest network test finished"); err != nil {
315 t.Error(err)
316 }
317 }()
318 probe := func(path, want string) {
319 t.Helper()
320 response := run("curl --noproxy '*' -sS --max-time 15 -o /dev/null -w '%{http_code}' http://"+cage.DiagnosticHost+path, nil)
321 if response != want {
322 t.Fatalf("guest diagnostic %s: got %q, want %q", path, response, want)
323 }
324 }
325 probe("/", "200")
326 before, err := client.SetFault(ctx, true)
327 if err != nil {
328 t.Fatal(err)
329 }
330 probe("/egress", "503")
331 probe("/dns", "503")
332 after, err := client.Status(ctx)
333 if err != nil {
334 t.Fatal(err)
335 }
336 if after.Counters.FaultTCP <= before.Counters.FaultTCP || after.Counters.FaultDNS <= before.Counters.FaultDNS {
337 t.Fatal("missing proxy fault observations for guest TCP or DNS")
338 }
339 t.Log("Guest diagnostic service reachable; both fixed probes reported injected proxy failure")
340}