跳到主要内容

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

浏览文件

macos_phone_desktop_test.go

214 行 · 7.2 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/base64"
8 "encoding/json"
9 "fmt"
10 "image"
11 "image/jpeg"
12 "net/http"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "github.com/google/uuid"
19 "github.com/sylvinus/agent-vm/internal/cage"
20 "golang.org/x/crypto/ssh"
21)
22
23func macPhoneFrame(t *testing.T, id string) []byte {
24 t.Helper()
25 var data bytes.Buffer
26 if err := jpeg.Encode(&data, image.NewRGBA(image.Rect(0, 0, 900, 600)), nil); err != nil {
27 t.Fatal(err)
28 }
29 body, err := json.Marshal(map[string]any{"id": id, "document": "captured-geometry", "width": 390, "height": 640,
30 "content_width": 900, "content_height": 600, "image": base64.StdEncoding.EncodeToString(data.Bytes()),
31 "focus": "real-ax-focus", "shared": true, "login_supported": false, "pixel_ratio_control": true})
32 if err != nil {
33 t.Fatal(err)
34 }
35 return body
36}
37
38func TestMacOSPhoneDesktopUsesPrivateRPCAndUTF8Envelope(t *testing.T) {
39 id := uuid.NewString()
40 frame := macPhoneFrame(t, id)
41 var mu sync.Mutex
42 var calls []macOSWindowRequest
43 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
44 if !strings.Contains(command, "window.sock") {
45 return 0, false
46 }
47 var input macOSWindowRequest
48 if err := json.NewDecoder(bufio.NewReader(channel)).Decode(&input); err != nil {
49 t.Error(err)
50 return 1, true
51 }
52 mu.Lock()
53 calls = append(calls, input)
54 mu.Unlock()
55 if input.Phone == nil || input.PhoneToken == "" {
56 t.Error("phone lease missing")
57 }
58 if input.Action == "phone-frame" {
59 _, _ = channel.Write(frame)
60 } else {
61 fmt.Fprintf(channel, `{"id":%q}`, id)
62 }
63 return 0, true
64 })
65 s := guest.s
66 secret := randomToken()
67 for _, op := range []string{"open", "frame", "action", "action", "close"} {
68 input := phoneSurfaceInput{ID: id, Width: 390, Height: 640}
69 if op == "action" {
70 input.Type, input.Focus, input.Document = "text", "real-ax-focus", "captured-geometry"
71 input.Text = strings.Repeat("\x01", 8192)
72 mu.Lock()
73 if len(calls) == 3 {
74 input.Text = strings.Repeat("中", 2730) + "ab"
75 }
76 mu.Unlock()
77 }
78 out, status, err := s.phoneSurfaceGuest(t.Context(), phoneDesktop, secret, op, input)
79 if err != nil || status != http.StatusOK || !bytes.Contains(out, []byte(id)) {
80 t.Fatalf("%s: %d %v", op, status, err)
81 }
82 }
83 mu.Lock()
84 defer mu.Unlock()
85 if len(calls) != 5 || len(calls[2].Phone.Text) != 8192 || len(calls[3].Phone.Text) != 8192 {
86 t.Fatal("8KiB phone text was truncated")
87 }
88 for _, call := range calls {
89 if call.PhoneToken != secret || !strings.HasPrefix(call.Action, "phone-") {
90 t.Fatal("phone RPC escaped its lease")
91 }
92 }
93 if validMacOSWindowRequest(macOSWindowRequest{Action: "phone-open"}) {
94 t.Fatal("desktop public endpoint admitted phone RPC")
95 }
96}
97
98func TestMacOSPhoneDesktopRejectsInvalidFramesAndMapsNativeFailures(t *testing.T) {
99 id := uuid.NewString()
100 frame := macPhoneFrame(t, id)
101 for _, code := range []string{"phone_session_ended", "gui_session_changed", "requires_gui_login", "phone_focus_changed", "phone_document_changed", "accessibility_permission", "screen_recording_permission"} {
102 want := http.StatusGone
103 if strings.Contains(code, "changed") && code != "gui_session_changed" {
104 want = http.StatusConflict
105 }
106 if strings.Contains(code, "permission") {
107 want = http.StatusForbidden
108 }
109 _, status, _ := macOSPhoneDesktopReply([]byte(`{"error":"`+code+`"}`), "frame", id)
110 if status != want {
111 t.Fatalf("%s: %d", code, status)
112 }
113 }
114 for _, mutation := range []func(map[string]any){
115 func(v map[string]any) { v["id"] = uuid.NewString() },
116 func(v map[string]any) { v["image"] = "iVBORw0KGgo=" },
117 func(v map[string]any) { v["document"] = "" },
118 func(v map[string]any) { v["content_width"] = 0 },
119 func(v map[string]any) { v["image"] = strings.Repeat("a", 3<<20) },
120 } {
121 var value map[string]any
122 _ = json.Unmarshal(frame, &value)
123 mutation(value)
124 raw, _ := json.Marshal(value)
125 if _, status, _ := macOSPhoneDesktopReply(raw, "frame", id); status != http.StatusBadGateway {
126 t.Fatal("invalid frame accepted")
127 }
128 }
129}
130
131func TestMacOSPhoneDesktopHandlerHonorsRoomGateAndRevocation(t *testing.T) {
132 id := uuid.NewString()
133 frame := macPhoneFrame(t, id)
134 var mu sync.Mutex
135 var secret string
136 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
137 if !strings.Contains(command, "window.sock") {
138 return 0, false
139 }
140 var input macOSWindowRequest
141 if err := json.NewDecoder(channel).Decode(&input); err != nil {
142 return 1, true
143 }
144 mu.Lock()
145 defer mu.Unlock()
146 if input.Action == "phone-open" {
147 secret = input.PhoneToken
148 }
149 if secret == "" || input.PhoneToken != secret {
150 t.Error("host failed to bind private lease")
151 }
152 if input.Action == "phone-frame" {
153 _, _ = channel.Write(frame)
154 } else {
155 fmt.Fprintf(channel, `{"id":%q}`, id)
156 }
157 return 0, true
158 })
159 s := guest.s
160 room, cancel := context.WithCancel(t.Context())
161 defer cancel()
162 s.phones.record = &phoneRecord{}
163 s.phones.roomCtx, s.phones.roomProof = room, "current-room"
164 open := fmt.Sprintf(`{"id":%q,"width":390,"height":640}`, id)
165 if response := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "old-room"); response.Code != 403 {
166 t.Fatalf("old room accepted: %d", response.Code)
167 }
168 if response := windowsPhoneRequest(t, s, "POST", "/api/mobile/desktop/open", open, "current-room"); response.Code != 409 {
169 t.Fatalf("closed gate accepted: %d %s", response.Code, response.Body.String())
170 }
171 cfg, err := loadConfig(s.configPath)
172 if err != nil {
173 t.Fatal(err)
174 }
175 gate, err := cage.NewEgressGate(cfg)
176 if err != nil {
177 t.Fatal(err)
178 }
179 stop, err := cage.StartGateControl(s.configPath, s.instanceDir(), gate)
180 if err != nil {
181 t.Fatal(err)
182 }
183 defer stop()
184 if err := gate.BeginCheck(); err != nil {
185 t.Fatal(err)
186 }
187 state := gate.Status()
188 report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: "phone-fixture", RunID: state.RunID, CheckID: state.CheckID, Configuration: state.Configuration, CreatedAt: time.Now()}
189 for _, check := range []string{"egress_policy", "proxy_transport", "dns_transport", "guest_settings", "browser_settings", "filesystem_boundary", "management_boundary", "fail_closed", "udp_policy", "ipv6_policy", "exit_consistency"} {
190 report.Checks = append(report.Checks, cage.SafetyCheck{ID: check, Title: check, Critical: true, State: cage.CheckPassed, Evidence: "isolated fixture", CheckedAt: report.CreatedAt})
191 }
192 if err := gate.Grant(report); err != nil {
193 t.Fatal(err)
194 }
195 for _, path := range []string{"/api/mobile/desktop/open", "/api/mobile/desktop/" + id + "/frame"} {
196 method, body := "GET", ""
197 if strings.HasSuffix(path, "open") {
198 method, body = "POST", open
199 }
200 response := windowsPhoneRequest(t, s, method, path, body, "current-room")
201 if response.Code != 200 {
202 t.Fatalf("native handler: %d %s", response.Code, response.Body.String())
203 }
204 }
205 s.account.trustedSession = true
206 if response := windowsPhoneRequest(t, s, "GET", "/api/mobile/desktop/"+id+"/frame", "", "current-room"); response.Code != 423 {
207 t.Fatal("desktop-only unlock leaked to phone")
208 }
209 s.account.trustedSession = false
210 cancel()
211 if response := windowsPhoneRequest(t, s, "GET", "/api/mobile/desktop/"+id+"/frame", "", "current-room"); response.Code != 403 {
212 t.Fatal("revoked phone retained frames")
213 }
214}