跳到主要内容

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

浏览文件

macos_workbench_e2e_test.go

401 行 · 14.5 KB历史下载
1//go:build e2e && darwin && arm64
2
3package workbench
4
5import (
6 "bytes"
7 "context"
8 _ "embed"
9 "encoding/base64"
10 "encoding/json"
11 "fmt"
12 "io"
13 "net/http"
14 "net/http/httptest"
15 "net/url"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "strings"
20 "testing"
21 "time"
22
23 "al.essio.dev/pkg/shellescape"
24 "github.com/gorilla/websocket"
25 "github.com/sylvinus/agent-vm/internal/guestos"
26)
27
28//go:embed testdata/macos_editor_file.swift
29var macOSEditorFileLocator []byte
30
31// Exercises the same local-view HTTP admission, SSH PTY and WebSocket stream
32// as the installed Mac workbench. Requires an already started, bound guest.
33func TestMacOSWorkbenchTerminal(t *testing.T) {
34 profile := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_PROFILE")
35 if profile == "" {
36 t.Skip("select a prepared test profile with CAGE_TEST_MACOS_WORKBENCH_PROFILE")
37 }
38 binding, err := guestos.LoadMacOSProfile(profile)
39 if err != nil || binding == nil {
40 t.Fatalf("unavailable macOS test profile: %v", err)
41 }
42 s := testServer(t)
43 s.profile, s.macosGuest = profile, binding
44 s.token, s.session = randomToken(), randomToken()
45 s.preferences.Workspace = s.environmentDir()
46 ctx, cancel := s.controlContext()
47 defer cancel()
48 if err := s.checkMacOSGuest(ctx); err != nil {
49 t.Fatal(err)
50 }
51 s.ready = true
52 defer s.terminals.close()
53 server := httptest.NewServer(s.handler())
54 defer server.Close()
55 s.origin = server.URL
56 cookie := s.cookieName() + "=" + s.session + "; " + s.cookieName() + "-desktop=" + trustedViewProof(s.token)
57 post := func(route string, body map[string]any) (int, string) {
58 t.Helper()
59 data, err := json.Marshal(body)
60 if err != nil {
61 t.Fatal(err)
62 }
63 r, err := http.NewRequest("POST", server.URL+"/api/"+route, bytes.NewReader(data))
64 if err != nil {
65 t.Fatal(err)
66 }
67 r.Header.Set("Content-Type", "application/json")
68 r.Header.Set("Origin", server.URL)
69 r.Header.Set("Cookie", cookie)
70 resp, err := http.DefaultClient.Do(r)
71 if err != nil {
72 t.Fatal(err)
73 }
74 defer resp.Body.Close()
75 out, err := io.ReadAll(io.LimitReader(resp.Body, 5<<20))
76 if err != nil {
77 t.Fatal(err)
78 }
79 return resp.StatusCode, string(out)
80 }
81 defer s.closeProjectShares()
82 project := os.Getenv("CAGE_TEST_MACOS_WORKBENCH_PROJECT")
83 var fixture string
84 if project != "" {
85 fixture, err = os.MkdirTemp(project, ".cage-live-workbench-")
86 if err != nil {
87 t.Fatal(err)
88 }
89 defer os.RemoveAll(fixture)
90 if err = os.Mkdir(filepath.Join(fixture, ".git"), 0700); err != nil {
91 t.Fatal(err)
92 }
93 if err = os.WriteFile(filepath.Join(fixture, "from-host"), []byte("host-data"), 0600); err != nil {
94 t.Fatal(err)
95 }
96 deadline := time.Now().Add(4 * time.Minute)
97 for {
98 code, message := post("projects/open", map[string]any{"workspace": project, "add": true})
99 if code == 200 && !strings.Contains(message, `"approval":`) {
100 break
101 }
102 if code == 200 && strings.Contains(message, `"approval":`) && time.Now().Before(deadline) {
103 time.Sleep(2 * time.Second)
104 continue
105 }
106 if strings.TrimSpace(message) != errMacOSProjectApproval.Error() || time.Now().After(deadline) {
107 if strings.Contains(message, `"approval":`) {
108 t.Fatal("waiting for guest project approval timed out")
109 }
110 t.Fatalf("mount: %d %s", code, message)
111 }
112 time.Sleep(2 * time.Second)
113 }
114 }
115 code, reply := post("terminals", map[string]any{"kind": "shell", "workspace": project})
116 if code != 200 {
117 t.Fatalf("terminal: %d %s", code, reply)
118 }
119 var tab struct{ ID string }
120 if err := json.Unmarshal([]byte(reply), &tab); err != nil || tab.ID == "" {
121 t.Fatalf("invalid terminal response: %v", err)
122 }
123 h := http.Header{"Origin": {s.origin}, "Cookie": {cookie}}
124 ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/api/terminals/"+tab.ID+"/stream", h)
125 if err != nil {
126 t.Fatal(err)
127 }
128 defer ws.Close()
129 if err := ws.WriteJSON(map[string]any{"type": "resize", "cols": 92, "rows": 31}); err != nil {
130 t.Fatal(err)
131 }
132 // The literal expected string is absent from the submitted command; an
133 // echoed keystroke cannot satisfy the guest identity or compilation check.
134 cmd := `d=$(mktemp -d) && printf '%s\n' 'return 6 * 7' > "$d/source.applescript" && /usr/bin/osacompile -o "$d/test.scpt" "$d/source.applescript" && printf 'CAGE_TRIAL_%s_%s_%s_END\n' "$(uname -s)" "$(sw_vers -productVersion)" "$(osascript "$d/test.scpt")"; rm -f "$d/source.applescript" "$d/test.scpt"; rmdir "$d"`
135 expected := "_42_END"
136 if project != "" {
137 base := filepath.Base(fixture)
138 cmd = fmt.Sprintf(`d=%s; test "$(cat "$d/from-host")" = host-data && ! touch "$d/.git/forbidden" && printf guest-data > "$d/from-guest.tmp" && mv "$d/from-guest.tmp" "$d/from-guest" && printf 'CAGE_PROJECT_%%s_%%s_%%s_END\n' "$(uname -s)" "$(./run.sh)" "$(stty size)"`, base)
139 expected = "CAGE_PROJECT_Darwin_132_31 92_END"
140 }
141 if err := ws.WriteJSON(map[string]string{"type": "input", "data": cmd + "\r"}); err != nil {
142 t.Fatal(err)
143 }
144 _ = ws.SetReadDeadline(time.Now().Add(35 * time.Second))
145 var output strings.Builder
146 for !strings.Contains(output.String(), expected) {
147 _, chunk, err := ws.ReadMessage()
148 if err != nil {
149 t.Fatal(err)
150 }
151 output.Write(chunk)
152 }
153 if project != "" {
154 data, err := os.ReadFile(filepath.Join(fixture, "from-guest"))
155 if err != nil || string(data) != "guest-data" {
156 t.Fatal("lost atomic guest save")
157 }
158 if _, err = os.Stat(filepath.Join(fixture, ".git", "forbidden")); !os.IsNotExist(err) {
159 t.Fatal("guest modified protected Git metadata")
160 }
161 if os.Getenv("CAGE_TEST_MACOS_WORKBENCH_BOUNDARY") == "1" {
162 ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second)
163 defer cancel()
164 probe, err := os.CreateTemp(project, ".cage-share-probe-*")
165 if err != nil {
166 t.Fatal(err)
167 }
168 defer os.Remove(probe.Name())
169 challenge := randomToken()
170 _, err = probe.WriteString(challenge)
171 probe.Close()
172 if err != nil {
173 t.Fatal(err)
174 }
175 private, err := os.CreateTemp(s.profile, ".cage-private-probe-*")
176 if err != nil {
177 t.Fatal(err)
178 }
179 private.Close()
180 defer os.Remove(private.Name())
181 client, err := s.gateClient()
182 if err != nil {
183 t.Fatal(err)
184 }
185 before, err := client.Status(ctx)
186 if err != nil || before.Mode != "closed" {
187 t.Fatal("require an offline test guest")
188 }
189 boundary, err := s.guestObservation(ctx, boundaryProbeInput(17777, randomToken()[:16], private.Name(), probe.Name(), challenge))
190 if err != nil {
191 t.Fatal(err)
192 }
193 after, err := client.Status(ctx)
194 if err != nil || after.Mode != "closed" {
195 t.Fatal("test network unexpectedly opened")
196 }
197 files, network := s.inspectVMLayout()
198 t.Logf("policy files=%t network=%t; shared=%t private=%s process TZ=%s locale=%s system TZ=%s locale=%s; IPv6 default routes=%d connected=%t; UDP attempted=%t; denied tcp/udp/dns counters %d/%d/%d -> %d/%d/%d", files, network, boundary.SharedFile, boundary.PrivateFile, boundary.TZ, boundary.ProcessLocale, boundary.SystemTimezone, boundary.SystemLocale, boundary.IPv6DefaultRoutes, boundary.IPv6Connected, boundary.UDPAttempted, before.Counters.TCPDenied, before.Counters.UDPDenied, before.Counters.DNSDenied, after.Counters.TCPDenied, after.Counters.UDPDenied, after.Counters.DNSDenied)
199 if !files || !network || !boundary.SharedFile || boundary.PrivateFile != "unreachable" || boundary.PublicConnected || boundary.ManagementConnected || boundary.PublicDNSAnswered || !boundary.UDPAttempted || after.Counters.UDPDenied <= before.Counters.UDPDenied || after.Counters.DNSDenied <= before.Counters.DNSDenied {
200 t.Fatal("guest boundary evidence incomplete")
201 }
202 }
203
204 if os.Getenv("CAGE_TEST_MACOS_WORKBENCH_EDITOR") == "1" {
205 defer s.closeWindowsBrowser()
206 doc, err := os.CreateTemp(project, "qa-*.txt")
207 if err != nil {
208 t.Fatal(err)
209 }
210 doc.Close()
211 defer os.Remove(doc.Name())
212 base := filepath.Base(doc.Name())
213 code, raw := post("macos-browser/action", map[string]any{"action": "editor", "workspace": project})
214 var opened struct {
215 OK bool
216 Error string
217 }
218 if code != 200 || json.Unmarshal([]byte(raw), &opened) != nil || !opened.OK {
219 t.Fatalf("guest editor could not open the authorized folder: status=%d error=%q", code, opened.Error)
220 }
221 code, raw = post("macos-browser/action", map[string]any{"action": "frame"})
222 var frame struct {
223 URL, Image string
224 Width, Height int
225 }
226 if err := json.Unmarshal([]byte(raw), &frame); code != 200 || err != nil {
227 t.Fatalf("editor frame: status=%d err=%v", code, err)
228 }
229 guestURL, err := url.Parse(frame.URL)
230 img, imgErr := base64.StdEncoding.DecodeString(frame.Image)
231 if err != nil || guestURL.Hostname() != filepath.Base(macOSProjectPath(binding.User, project))+".cage-editor.localhost" || guestURL.Query().Get("folder") != macOSProjectPath(binding.User, project) || imgErr != nil || len(img) < 1024 || frame.Width < 1 || frame.Height < 1 {
232 t.Fatal("browser did not show the expected guest-local project")
233 }
234
235 action := func(body map[string]any) map[string]any {
236 t.Helper()
237 status, raw := post("macos-browser/action", body)
238 var result map[string]any
239 if status != 200 || json.Unmarshal([]byte(raw), &result) != nil || result["error"] != nil {
240 t.Fatalf("browser %s: %d %v", body["action"], status, result["error"])
241 }
242 return result
243 }
244 snapshot := func(name string) map[string]any {
245 result := action(map[string]any{"action": "frame"})
246 if dir := os.Getenv("CAGE_TEST_MACOS_EDITOR_FRAMES"); dir != "" {
247 jpg, _ := result["image"].(string)
248 data, err := base64.StdEncoding.DecodeString(jpg)
249 if err != nil {
250 t.Fatal(err)
251 }
252 if err = os.WriteFile(filepath.Join(dir, name+".jpg"), data, 0600); err != nil {
253 t.Fatal(err)
254 }
255 }
256 return result
257 }
258 deadline := time.Now().Add(18 * time.Second)
259 for {
260 state := snapshot("ready")
261 title, _ := state["title"].(string)
262 if strings.Contains(title, "code-server") {
263 break
264 }
265 if time.Now().After(deadline) {
266 t.Fatal("workspace window did not initialize")
267 }
268 time.Sleep(450 * time.Millisecond)
269 }
270 scratch := t.TempDir()
271 source := filepath.Join(scratch, "find.swift")
272 finder := filepath.Join(scratch, "find")
273 if err := os.WriteFile(source, macOSEditorFileLocator, 0600); err != nil {
274 t.Fatal(err)
275 }
276 if out, err := exec.Command("/usr/bin/xcrun", "swiftc", source, "-o", finder).CombinedOutput(); err != nil {
277 t.Fatalf("Vision file locator: %v %s", err, out)
278 }
279 jpeg := filepath.Join(scratch, "editor.jpg")
280 deadline = time.Now().Add(22 * time.Second)
281 for {
282 state := snapshot("explorer")
283 data, err := base64.StdEncoding.DecodeString(state["image"].(string))
284 if err != nil {
285 t.Fatal(err)
286 }
287 if err := os.WriteFile(jpeg, data, 0600); err != nil {
288 t.Fatal(err)
289 }
290 result, err := exec.Command(finder, jpeg, base).Output()
291 var x, y int
292 if _, scan := fmt.Sscanf(string(result), "%d %d", &x, &y); err == nil && scan == nil {
293 action(map[string]any{"action": "click", "double": true, "x": x, "y": y})
294 break
295 }
296 if time.Now().After(deadline) {
297 t.Fatal("temporary file not visible in the guest editor Explorer")
298 }
299 time.Sleep(400 * time.Millisecond)
300 }
301
302 deadline = time.Now().Add(15 * time.Second)
303 for {
304 frame := snapshot("file-editor")
305 title, _ := frame["title"].(string)
306 if strings.Contains(title, base) {
307 break
308 }
309 if time.Now().After(deadline) {
310 t.Fatalf("unique test file did not acquire editor focus (title=%q)", title)
311 }
312 time.Sleep(450 * time.Millisecond)
313 }
314 marker := "guest-editor-write-" + randomToken()[:12]
315 action(map[string]any{"action": "text", "text": marker})
316 action(map[string]any{"action": "key", "meta": true, "key": "s"})
317 deadline = time.Now().Add(10 * time.Second)
318 for {
319 content, err := os.ReadFile(doc.Name())
320 if err == nil && strings.TrimSpace(string(content)) == marker {
321 break
322 }
323 if time.Now().After(deadline) {
324 t.Fatal("browser editor save was not observed on host")
325 }
326 time.Sleep(150 * time.Millisecond)
327 }
328 t.Log("Selected a unique project file in the guest editor, confirmed its title and read its saved contents back on the host")
329
330 t.Logf("guest-local code-server opened the selected project; JPEG %dx%d, %d bytes", frame.Width, frame.Height, len(img))
331 }
332 t.Log(expected)
333 return
334 }
335 got := output.String()
336 from := strings.Index(got, "CAGE_TRIAL_Darwin_")
337 if from < 0 {
338 t.Fatal("guest did not report Darwin")
339 }
340 to := strings.Index(got[from:], "_42_END")
341 if to < 0 {
342 t.Fatal("guest program output did not match")
343 }
344 t.Log(got[from : from+to+len("_42_END")])
345}
346
347func TestMacOSGuestIPv6LinkDrop(t *testing.T) {
348 profile := os.Getenv("CAGE_TEST_MACOS_LINK_PROFILE")
349 if profile == "" {
350 t.Skip("select a bound, closed macOS test instance")
351 }
352 binding, err := guestos.LoadMacOSProfile(profile)
353 if err != nil || binding == nil {
354 t.Fatal("invalid macOS test profile")
355 }
356 s := &Server{profile: profile, macosGuest: binding}
357 client, err := s.gateClient()
358 if err != nil {
359 t.Fatal(err)
360 }
361 ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)
362 defer cancel()
363 original, err := client.Status(ctx)
364 if err != nil || original.Mode != "closed" {
365 t.Fatal("test requires a closed gate")
366 }
367 state, err := client.BeginCheck(ctx)
368 if err != nil {
369 t.Fatal(err)
370 }
371 defer func() {
372 closeCtx, stop := context.WithTimeout(context.Background(), 3*time.Second)
373 defer stop()
374 closed, err := client.Close(closeCtx, "链路验证结束,外网关闭")
375 if err != nil || closed.Mode != "closed" {
376 t.Error("gate closure could not be verified")
377 }
378 }()
379 // Both IDs come from the selected instance's gate controller. No general
380 // diagnostic request can publish observed-frame evidence.
381 command := `iface=$(/sbin/route -n get -inet 198.18.0.254 | /usr/bin/awk '/interface:/{print $2}'); [[ "$iface" =~ ^en[0-9]+$ ]] || exit 1; /usr/local/libexec/cage-macos-ipv6-check link "$iface" ` + shellescape.Quote(state.RunID) + " " + shellescape.Quote(state.CheckID)
382 out, err := s.guest(ctx, command)
383 if err != nil || strings.TrimSpace(string(out)) != "sent" {
384 t.Fatalf("guest failed to submit the one-hop datagram: %v", err)
385 }
386 for i := 0; i < 15; i++ {
387 after, err := client.Status(ctx)
388 if err != nil {
389 t.Fatal(err)
390 }
391 if after.Mode != state.Mode || after.RunID != state.RunID || after.CheckID != state.CheckID {
392 t.Fatal("checking epoch changed during observation")
393 }
394 if after.IPv6LinkProbeCheck == state.CheckID {
395 t.Log("guest sent the live nonce on its VZ link; host IPv4-only stack confirmed the matching ingress drop")
396 return
397 }
398 time.Sleep(120 * time.Millisecond)
399 }
400 t.Fatal("no matching IPv6 ingress evidence on the current host agent")
401}