跳到主要内容

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

浏览文件

macos_workspace_test.go

502 行 · 16.6 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "crypto/ed25519"
6 "crypto/rand"
7 "encoding/json"
8 "encoding/pem"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "net/http/httptest"
15 "os"
16 "path"
17 "path/filepath"
18 "strings"
19 "sync"
20 "sync/atomic"
21 "testing"
22
23 "github.com/google/uuid"
24 "github.com/kballard/go-shellquote"
25 "github.com/pkg/sftp"
26 "github.com/sylvinus/agent-vm/internal/guestos"
27 "golang.org/x/crypto/ssh"
28)
29
30// This guest substitute uses the real bound OpenSSH transport and the confined
31// host SFTP server. FSKit approval and native application execution are simulated.
32type macWorkspaceGuest struct {
33 s *Server
34 hostPath string
35 guestPath string
36 approved atomic.Bool
37 resourceTicks atomic.Uint32
38 resourceFailure atomic.Bool
39 mu sync.Mutex
40 files *sftp.Client
41 command func(ssh.Channel, string) (uint32, bool)
42}
43
44func newMacWorkspaceGuest(t *testing.T, commands ...func(ssh.Channel, string) (uint32, bool)) *macWorkspaceGuest {
45 t.Helper()
46 if _, err := os.Stat(sshExecutable()); err != nil {
47 t.Skip("OpenSSH is unavailable")
48 }
49 s := testServer(t)
50 s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
51 hostPath, err := filepath.EvalSymlinks(t.TempDir())
52 if err != nil {
53 t.Fatal(err)
54 }
55 if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": hostPath}); err != nil {
56 t.Fatal(err)
57 }
58 s.preferences.Workspace, s.ready = hostPath, true
59 guest := &macWorkspaceGuest{s: s, hostPath: hostPath, guestPath: macOSProjectPath("cage", hostPath)}
60 if len(commands) > 0 {
61 guest.command = commands[0]
62 }
63 listener, err := net.Listen("tcp", "127.0.0.1:0")
64 if err != nil {
65 t.Fatal(err)
66 }
67 _, key, err := ed25519.GenerateKey(rand.Reader)
68 if err != nil {
69 t.Fatal(err)
70 }
71 signer, err := ssh.NewSignerFromKey(key)
72 if err != nil {
73 t.Fatal(err)
74 }
75 config := &ssh.ServerConfig{NoClientAuth: true}
76 config.AddHostKey(signer)
77 if err = os.MkdirAll(s.instanceDir(), 0700); err != nil {
78 t.Fatal(err)
79 }
80 identity, err := ssh.MarshalPrivateKey(key, "workspace-fixture")
81 if err != nil {
82 t.Fatal(err)
83 }
84 if err = os.MkdirAll(filepath.Join(s.profile, "state", "lima", "_config"), 0700); err != nil {
85 t.Fatal(err)
86 }
87 if err = os.WriteFile(filepath.Join(s.profile, "state", "lima", "_config", "user"), pem.EncodeToMemory(identity), 0600); err != nil {
88 t.Fatal(err)
89 }
90 for name, value := range map[string]string{
91 "state/lima/mac/ssh.config": fmt.Sprintf("Port %d\nUser cage\n", listener.Addr().(*net.TCPAddr).Port),
92 "macos-known-hosts": "cage-macos " + string(ssh.MarshalAuthorizedKey(signer.PublicKey())),
93 } {
94 if err = os.WriteFile(filepath.Join(s.profile, name), []byte(value), 0600); err != nil {
95 t.Fatal(err)
96 }
97 }
98 if err = writePrivate(filepath.Join(s.instanceDir(), "cage-running.json"), map[string]int{"pid": os.Getpid()}); err != nil {
99 t.Fatal(err)
100 }
101 var active sync.WaitGroup
102 acceptDone := make(chan struct{})
103 go func() {
104 defer close(acceptDone)
105 for {
106 conn, err := listener.Accept()
107 if err != nil {
108 return
109 }
110 active.Add(1)
111 go func() {
112 defer active.Done()
113 server, channels, requests, err := ssh.NewServerConn(conn, config)
114 if err != nil {
115 conn.Close()
116 return
117 }
118 defer server.Close()
119 go ssh.DiscardRequests(requests)
120 for incoming := range channels {
121 channel, requests, err := incoming.Accept()
122 if err != nil {
123 return
124 }
125 for request := range requests {
126 if request.Type != "exec" {
127 request.Reply(true, nil)
128 continue
129 }
130 var command struct{ Command string }
131 if ssh.Unmarshal(request.Payload, &command) != nil {
132 request.Reply(false, nil)
133 break
134 }
135 request.Reply(true, nil)
136 go ssh.DiscardRequests(requests)
137 status := guest.execute(channel, command.Command)
138 channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{status}))
139 break
140 }
141 channel.Close()
142 }
143 }()
144 }
145 }()
146 t.Cleanup(func() {
147 s.beginClose()
148 s.terminals.close()
149 s.closeWindowsBrowser()
150 s.closeProjectShares()
151 listener.Close()
152 <-acceptDone
153 active.Wait()
154 })
155 return guest
156}
157
158func (g *macWorkspaceGuest) execute(channel ssh.Channel, command string) uint32 {
159 if g.command != nil {
160 if status, handled := g.command(channel, command); handled {
161 return status
162 }
163 }
164 args, err := shellquote.Split(command)
165 if err != nil {
166 return 1
167 }
168 if strings.HasPrefix(command, "exec /bin/bash --noprofile --norc -c ") {
169 command = args[len(args)-1]
170 args, err = shellquote.Split(command)
171 if err != nil {
172 return 1
173 }
174 }
175 switch {
176 case strings.HasPrefix(command, "exec /usr/local/libexec/cage-cli/bin/python3 -I -c "):
177 if g.resourceFailure.Load() {
178 fmt.Fprintln(channel, `{}`)
179 return 0
180 }
181 ticks := g.resourceTicks.Add(10)
182 json.NewEncoder(channel).Encode(macOSResourceSample{Version: 1, Total: 4 << 30, Available: 2 << 30,
183 Free: 1 << 30, Inactive: 1 << 30, CPUs: 2, Boot: 10, CPUTicks: [4]uint32{ticks, 10, 80 + ticks, 0}})
184 return 0
185 case command == "/usr/bin/open -a /Applications/CageProjectAccess.app":
186 return 0
187 case strings.HasPrefix(command, "set -e;"):
188 return 0
189 case strings.HasPrefix(command, "exec /usr/local/libexec/cage-sshfs "):
190 files, err := sftp.NewClientPipe(channel, channel)
191 if err != nil {
192 return 1
193 }
194 g.mu.Lock()
195 g.files = files
196 g.mu.Unlock()
197 _ = files.Wait()
198 return 0
199 case len(args) == 5 && args[0] == macProjectAgent && args[1] == "probe":
200 if !g.approved.Load() {
201 return 75
202 }
203 g.mu.Lock()
204 files := g.files
205 g.mu.Unlock()
206 if files == nil || args[2] != g.guestPath {
207 return 1
208 }
209 file, err := files.Open(filepath.Join(g.hostPath, args[3]))
210 if err != nil {
211 return 1
212 }
213 body, err := io.ReadAll(file)
214 file.Close()
215 if err != nil || string(body) != args[4] {
216 return 1
217 }
218 fmt.Fprint(channel, "OK")
219 return 0
220 case strings.HasPrefix(command, "/sbin/mount |"):
221 fmt.Fprintf(channel, "macfuse://3c7e13b5-dc9f-4d09-b7c3-707987db4e34 on %s (fskit, nodev, nosuid, mounted by cage)\n", g.guestPath)
222 return 0
223 case strings.HasPrefix(command, "if test "):
224 return 0
225 case strings.HasPrefix(command, "exec /usr/local/libexec/cage-macos-terminal "):
226 if len(args) != 3 || args[2] != g.guestPath || !g.approved.Load() {
227 return 1
228 }
229 fmt.Fprintln(channel, "shared-workspace-ready")
230 var input strings.Builder
231 buffer := make([]byte, 1024)
232 for {
233 n, err := channel.Read(buffer)
234 if err != nil {
235 return 0
236 }
237 input.Write(buffer[:n])
238 if strings.Contains(input.String(), "fixture-boundary:guest") {
239 g.mu.Lock()
240 files := g.files
241 g.mu.Unlock()
242 file, err := files.OpenFile(filepath.Join(g.hostPath, ".cage-share-probe-boundary"), os.O_WRONLY|os.O_TRUNC)
243 if err != nil {
244 return 1
245 }
246 _, err = file.Write([]byte("fixture-boundary:guest"))
247 file.Close()
248 if err != nil {
249 return 1
250 }
251 return 0
252 }
253 }
254 case strings.Contains(command, "macos-native-browser.mjs"):
255 scanner := bufio.NewScanner(channel)
256 for scanner.Scan() {
257 var request struct {
258 Path string
259 Input map[string]any
260 }
261 if json.Unmarshal(scanner.Bytes(), &request) != nil {
262 return 1
263 }
264 json.NewEncoder(channel).Encode(map[string]any{"ok": true, "workspace": request.Input["workspace"]})
265 }
266 return 0
267 default:
268 fmt.Fprintln(channel.Stderr(), "unexpected fixture command")
269 return 1
270 }
271}
272
273func TestMacOSProjectOpenWithRequiresSSHFSCapability(t *testing.T) {
274 for _, capability := range []struct {
275 name string
276 output string
277 want bool
278 }{
279 {name: "legacy helper"},
280 {name: "supported helper", output: "\nCAGE_SSHFS_OPENWITH\n", want: true},
281 {name: "unrelated diagnostic", output: "unknown CAGE_SSHFS_OPENWITH option\n"},
282 } {
283 t.Run(capability.name, func(t *testing.T) {
284 mounts := make(chan string, 1)
285 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
286 if strings.Contains(command, "CAGE_SSHFS_OPENWITH") {
287 fmt.Fprint(channel, capability.output)
288 return 0, true
289 }
290 if strings.HasPrefix(command, "exec /usr/local/libexec/cage-sshfs ") {
291 mounts <- command
292 }
293 return 0, false
294 })
295 guest.approved.Store(true)
296 if err := guest.s.ensureMacOSProjectShare(guest.hostPath); err != nil {
297 t.Fatal(err)
298 }
299 command := <-mounts
300 args, err := shellquote.Split(command)
301 if err != nil {
302 t.Fatal(err)
303 }
304 found := false
305 for _, arg := range args {
306 if strings.HasPrefix(arg, "cage_openwith=") {
307 found = true
308 if arg != "cage_openwith=/Users/cage/Library/Caches/dev.cage.GuestClaudeWindow/openwith.data" {
309 t.Fatalf("unexpected guest metadata path %q", arg)
310 }
311 }
312 }
313 if found != capability.want {
314 t.Fatalf("OpenWith option present = %v, want %v", found, capability.want)
315 }
316 })
317 }
318}
319
320func TestMacOSDefaultWorkspaceUsesApprovedSharedProject(t *testing.T) {
321 guest := newMacWorkspaceGuest(t)
322 s := guest.s
323 marker := filepath.Join(guest.hostPath, "keep.txt")
324 if err := os.WriteFile(marker, []byte("original-host-data"), 0600); err != nil {
325 t.Fatal(err)
326 }
327 body, _ := json.Marshal(map[string]any{"workspace": guest.hostPath, "activate": true})
328 response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/projects/open", body)
329 var pending struct{ Workspace, Approval string }
330 if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &pending) != nil || pending.Approval == "" || pending.Workspace != guest.hostPath {
331 t.Fatalf("default workspace bypassed project approval: %d %s", response.Code, response.Body.String())
332 }
333 if s.projectShares[guest.hostPath].detach != nil {
334 t.Fatal("unapproved share was accepted")
335 }
336 guest.approved.Store(true)
337 response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/projects/open", body)
338 if response.Code != 200 || strings.Contains(response.Body.String(), "approval") || s.projectShares[guest.hostPath].detach == nil {
339 t.Fatalf("approved default workspace failed: %d %s", response.Code, response.Body.String())
340 }
341 if got := s.cliWorkspace(guest.hostPath); got != guest.guestPath {
342 t.Fatalf("Claude cwd=%q", got)
343 }
344 for _, route := range []string{"/api/browser/editor", "/api/macos-browser/action"} {
345 fields := map[string]string{"workspace": guest.hostPath}
346 if route == "/api/macos-browser/action" {
347 fields["action"] = "editor"
348 }
349 input, _ := json.Marshal(fields)
350 response = windowsBrowserRequestForTest(s, http.MethodPost, route, input)
351 if response.Code != 200 {
352 t.Fatalf("default editor %s: %d %s", route, response.Code, response.Body.String())
353 }
354 if route == "/api/browser/editor" && !strings.Contains(response.Body.String(), path.Base(guest.guestPath)) {
355 t.Fatal("editor lost shared project identity")
356 }
357 }
358 terminal, err := s.createTerminal(terminalRequest{Workspace: guest.hostPath, Kind: "shell"})
359 if err != nil {
360 t.Fatal(err)
361 }
362 sub := terminal.subscribe()
363 defer sub.Close()
364 readTerminalUntil(t, sub, "shared-workspace-ready")
365 probe := filepath.Join(guest.hostPath, ".cage-share-probe-boundary")
366 if err = os.WriteFile(probe, []byte("fixture-boundary"), 0600); err != nil {
367 t.Fatal(err)
368 }
369 if !s.checkMacOSSharedFile(t.Context(), probe, "fixture-boundary") {
370 t.Fatal("default workspace failed shared-file round trip")
371 }
372 got, err := os.ReadFile(marker)
373 if err != nil || string(got) != "original-host-data" {
374 t.Fatal("existing host data changed")
375 }
376}
377
378func TestMacOSDefaultWorkspaceRestoresWithVisibleFailureAndRetry(t *testing.T) {
379 guest := newMacWorkspaceGuest(t)
380 s := guest.s
381 s.restoreProjectShares()
382 if len(s.projectErrors) != 1 || s.projectErrors[0].Path != guest.hostPath || s.projectShares[guest.hostPath] == nil {
383 t.Fatal("default workspace restoration omitted its pending authorization")
384 }
385 guest.approved.Store(true)
386 if _, err := s.connectProject(guest.hostPath, false); err != nil {
387 t.Fatal(err)
388 }
389 if len(s.projectErrors) != 0 {
390 t.Fatal("successful retry retained the old project error")
391 }
392}
393
394func TestMacOSDefaultWorkspaceNewAndLegacyConversations(t *testing.T) {
395 s := testServer(t)
396 s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
397 host, _ := filepath.EvalSymlinks(t.TempDir())
398 if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": host}); err != nil {
399 t.Fatal(err)
400 }
401 s.preferences.Workspace = host
402 script, fresh, err := s.prepareTerminalConversation(host, claudeSelection{}, "")
403 if err != nil {
404 t.Fatal(err)
405 }
406 if fresh.GuestWorkspace != macOSProjectPath("cage", host) || !strings.Contains(script, "cage-macos-terminal --claude") || fresh.ConnectionNotice != "" {
407 t.Fatal("new default conversation did not use shared project")
408 }
409 legacyRoot := "/Users/cage/.local/share/cage/workspace"
410 for _, directory := range []string{legacyRoot, legacyRoot + "/nested"} {
411 id := uuid.NewString()
412 if _, err = s.mobileCLI.create(s.profile, host, id); err != nil {
413 t.Fatal(err)
414 }
415 record, err := s.mobileCLI.record(s.profile, id)
416 if err != nil {
417 t.Fatal(err)
418 }
419 record.Terminal, record.Resume, record.GuestWorkspace = true, true, directory
420 if err = writePrivate(mobileRecordPath(s.profile, id), record); err != nil {
421 t.Fatal(err)
422 }
423 script, resumed, err := s.prepareTerminalConversation(host, claudeSelection{}, id)
424 if err != nil {
425 t.Fatal(err)
426 }
427 if resumed.GuestWorkspace != directory || resumed.ConnectionNotice != macOSLegacyWorkspaceNotice || strings.Contains(script, "cage-macos-terminal") || !strings.Contains(script, "cd -- "+legacyRoot) {
428 t.Fatal("legacy conversation lost original directory or notice")
429 }
430 s.terminals.sessions = map[string]*terminalSession{"legacy": {id: "legacy", sharedID: id, workspace: host}}
431 if s.terminalSummaries()[0]["workspace_notice"] != macOSLegacyWorkspaceNotice {
432 t.Fatal("desktop terminal omitted the legacy workspace notice")
433 }
434 if _, _, err = s.prepareTerminalConversation(host+"/other", claudeSelection{}, id); err == nil {
435 t.Fatal("another project reused a legacy workspace binding")
436 }
437 }
438 for _, record := range []*mobileRecord{
439 {Terminal: true, GuestWorkspace: legacyRoot + "/../escape", mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
440 {Terminal: true, GuestWorkspace: legacyRoot + "-other", mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
441 {Terminal: true, GuestWorkspace: legacyRoot, mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host + "/other"}}},
442 {GuestWorkspace: legacyRoot, mobileSession: mobileSession{mobileSummary: mobileSummary{Workspace: host}}},
443 } {
444 if s.macOSLegacyWorkspace(record) != "" {
445 t.Fatal("legacy compatibility accepted an unrelated or unbound directory")
446 }
447 }
448}
449
450func TestMacOSProjectOpenRestoresPendingApprovalWindow(t *testing.T) {
451 var activations atomic.Int32
452 var activationFails atomic.Bool
453 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
454 if strings.Contains(command, "/usr/bin/open -a /Applications/CageProjectAccess.app") {
455 activations.Add(1)
456 if activationFails.Load() {
457 return 1, true
458 }
459 return 0, true
460 }
461 return 0, false
462 })
463 s := guest.s
464 s.restoreProjectShares()
465 share := s.projectShares[guest.hostPath]
466 if share == nil || share.approval == "" {
467 t.Fatal("expected a pending project authorization")
468 }
469 grant := share.approval
470 if err := s.ensureProjectShare(guest.hostPath); !errors.Is(err, errMacOSProjectApproval) {
471 t.Fatalf("background project probe: %v", err)
472 }
473 if activations.Load() != 0 {
474 t.Fatal("background project recovery stole guest focus")
475 }
476 body, _ := json.Marshal(map[string]any{"workspace": guest.hostPath, "add": false})
477 open := func() *httptest.ResponseRecorder {
478 return windowsBrowserRequestForTest(s, http.MethodPost, "/api/projects/open", body)
479 }
480 response := open()
481 var pending struct{ Workspace, Approval string }
482 if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &pending) != nil || pending.Approval != grant || pending.Workspace != guest.hostPath {
483 t.Fatalf("pending project open: %d %s", response.Code, response.Body.String())
484 }
485 if activations.Load() != 1 || share.detach != nil {
486 t.Fatal("explicit project open did not show the pending window without approving it")
487 }
488 activationFails.Store(true)
489 response = open()
490 if response.Code == http.StatusOK || share.approval != grant || s.projectShares[guest.hostPath] != share || share.detach != nil {
491 t.Fatal("failed window activation lost its pending grant or reported success")
492 }
493 activationFails.Store(false)
494 guest.approved.Store(true)
495 response = open()
496 if response.Code != http.StatusOK || strings.Contains(response.Body.String(), "approval") || share.detach == nil {
497 t.Fatalf("approved project open: %d %s", response.Code, response.Body.String())
498 }
499 if activations.Load() != 2 {
500 t.Fatal("opening an approved project stole guest focus")
501 }
502}