跳到主要内容

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

浏览文件

native_download_test.go

506 行 · 17.2 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "encoding/base64"
8 "encoding/json"
9 "net/http"
10 "net/http/cookiejar"
11 "net/http/httptest"
12 "net/url"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "strconv"
17 "strings"
18 "sync"
19 "testing"
20 "time"
21
22 "github.com/google/uuid"
23 "github.com/sylvinus/agent-vm/internal/guestos"
24 "github.com/sylvinus/agent-vm/internal/remotehost"
25)
26
27// The child provides the native controller protocol over a real pipe. Every
28// download source is a test-owned file selected by its catalog ID.
29func TestNativeDownloadRelay(t *testing.T) {
30 directory := os.Getenv("CAGE_NATIVE_DOWNLOAD_FIXTURE")
31 if directory == "" {
32 return
33 }
34 scanner := bufio.NewScanner(os.Stdin)
35 sources := make(map[string][]byte)
36 for scanner.Scan() {
37 var request struct {
38 Path string
39 Input struct {
40 ID, Transfer string
41 Sequence int
42 After int
43 }
44 }
45 if json.Unmarshal(scanner.Bytes(), &request) != nil {
46 os.Exit(2)
47 }
48 raw, err := os.ReadFile(filepath.Join(directory, "catalog.json"))
49 if err != nil {
50 os.Exit(3)
51 }
52 var state struct{ Downloads []browserDownloadInfo }
53 if json.Unmarshal(raw, &state) != nil {
54 os.Exit(4)
55 }
56 var result any = map[string]any{"ok": true}
57 switch request.Path {
58 case "/tabs":
59 result = map[string]any{"active": "tab", "tabs": []any{}, "downloads": state.Downloads}
60 case "/events":
61 result = map[string]any{"sequence": 1}
62 if request.Input.After != 1 {
63 result = map[string]any{"sequence": 1, "state": map[string]any{"active": "tab", "tabs": []any{}, "downloads": state.Downloads}}
64 }
65 case "/file-open":
66 var selected *browserDownloadInfo
67 for i := range state.Downloads {
68 if state.Downloads[i].ID == request.Input.ID {
69 selected = &state.Downloads[i]
70 }
71 }
72 if selected == nil {
73 os.Exit(5)
74 }
75 source, err := os.ReadFile(filepath.Join(directory, selected.ID))
76 if err != nil {
77 os.Exit(6)
78 }
79 transfer := strings.ReplaceAll(selected.ID, "-", "")
80 sources[transfer] = source
81 result = map[string]any{"transfer": transfer, "size": len(source), "name": selected.Name}
82 case "/file-read":
83 _ = os.WriteFile(filepath.Join(directory, "reading"), nil, 0600)
84 for {
85 if _, err := os.Stat(filepath.Join(directory, "block")); os.IsNotExist(err) {
86 break
87 }
88 time.Sleep(10 * time.Millisecond)
89 }
90 if _, err := os.Stat(filepath.Join(directory, "fail")); err == nil {
91 os.Exit(7)
92 }
93 source := sources[request.Input.Transfer]
94 start := request.Input.Sequence * (64 << 10)
95 end := min(start+(64<<10), len(source))
96 if start > len(source) {
97 os.Exit(8)
98 }
99 result = map[string]any{"data": base64.StdEncoding.EncodeToString(source[start:end]), "sequence": request.Input.Sequence + 1, "eof": end == len(source)}
100 }
101 if json.NewEncoder(os.Stdout).Encode(result) != nil {
102 os.Exit(9)
103 }
104 }
105 os.Exit(0)
106}
107
108func nativeDownloadFixture(t *testing.T, system string, records []browserDownloadInfo, payload []byte) (*Server, string, string) {
109 t.Helper()
110 s := testServer(t)
111 if system == "macos" {
112 s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
113 } else {
114 s.windowsGuest = &guestos.WindowsProfile{}
115 }
116 workspace, err := filepath.EvalSymlinks(t.TempDir())
117 if err != nil {
118 t.Fatal(err)
119 }
120 if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil {
121 t.Fatal(err)
122 }
123 directory := t.TempDir()
124 catalog, _ := json.Marshal(map[string]any{"downloads": records})
125 if err = os.WriteFile(filepath.Join(directory, "catalog.json"), catalog, 0600); err != nil {
126 t.Fatal(err)
127 }
128 for _, record := range records {
129 if err = os.WriteFile(filepath.Join(directory, record.ID), payload, 0600); err != nil {
130 t.Fatal(err)
131 }
132 }
133 client := newWindowsBrowserClient(context.Background(), "unused-native-download-fixture")
134 client.start = func(ctx context.Context) (*exec.Cmd, error) {
135 cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestNativeDownloadRelay$")
136 cmd.Env = append(os.Environ(), "CAGE_NATIVE_DOWNLOAD_FIXTURE="+directory)
137 return cmd, nil
138 }
139 s.windowsBrowserControl = client
140 s.ready = true
141 t.Cleanup(func() { s.beginClose(); client.close(); s.activities.Wait() })
142 return s, workspace, directory
143}
144
145func TestNativeDownloadsPublishHostCopiesAndPreserveSavedLocations(t *testing.T) {
146 for _, system := range []string{"macos", "windows-11"} {
147 t.Run(system, func(t *testing.T) {
148 ids := []string{uuid.NewString(), uuid.NewString()}
149 records := []browserDownloadInfo{
150 {ID: ids[0], Name: "参考.bin", State: "saved", Path: "Downloads/参考.bin"},
151 {ID: ids[1], Name: "参考.bin", State: "saved", Path: "/untrusted/guest/path"},
152 }
153 payload := bytes.Repeat([]byte{0, 1, 127, 255}, 40001)
154 s, workspace, _ := nativeDownloadFixture(t, system, records, payload)
155 if err := os.Mkdir(filepath.Join(workspace, "Downloads"), 0700); err != nil {
156 t.Fatal(err)
157 }
158 existing := filepath.Join(workspace, "Downloads", "参考.bin")
159 if err := os.WriteFile(existing, []byte("existing"), 0600); err != nil {
160 t.Fatal(err)
161 }
162 snapshot, _ := json.Marshal(map[string]any{"tabs": []any{}, "downloads": records})
163 if _, err := s.browserStateForHost(snapshot); err != nil {
164 t.Fatal(err)
165 }
166 var workers sync.WaitGroup
167 paths := make(chan string, 8)
168 for n := 0; n < 8; n++ {
169 id := ids[n%len(ids)]
170 workers.Add(1)
171 go func() {
172 defer workers.Done()
173 item, err := s.downloadInfo(t.Context(), id)
174 if err != nil {
175 t.Error(err)
176 return
177 }
178 paths <- item.Path
179 }()
180 }
181 workers.Wait()
182 close(paths)
183 distinct := map[string]bool{}
184 for path := range paths {
185 distinct[path] = true
186 got, err := os.ReadFile(path)
187 if err != nil || !bytes.Equal(got, payload) {
188 t.Errorf("host copy differs: %v", err)
189 }
190 }
191 if len(distinct) != 2 {
192 t.Fatalf("duplicate requests created %d copies", len(distinct))
193 }
194 original, _ := os.ReadFile(existing)
195 if string(original) != "existing" {
196 t.Fatal("existing same-name file overwritten")
197 }
198 mapped, err := s.browserStateForHost(snapshot)
199 if err != nil {
200 t.Fatal(err)
201 }
202 var state struct{ Downloads []browserDownloadInfo }
203 if json.Unmarshal(mapped, &state) != nil {
204 t.Fatal("invalid host state")
205 }
206 for _, record := range state.Downloads {
207 if record.State != "saved" || !filepath.IsAbs(record.Path) || !strings.HasPrefix(record.Path, workspace+string(filepath.Separator)) {
208 t.Fatalf("not a completed host location: %#v", record)
209 }
210 }
211 chosen := filepath.Join(workspace, "chosen.bin")
212 if err := saveDownloadedStream(chosen, bytes.NewReader(payload), int64(len(payload))); err != nil {
213 t.Fatal(err)
214 }
215 if err := rememberDownload(s.profile, SavedDownload{ID: ids[0], Name: "chosen.bin", Path: chosen}, false); err != nil {
216 t.Fatal(err)
217 }
218 if _, err := s.browserStateForHost(snapshot); err != nil {
219 t.Fatal(err)
220 }
221 s.ready = false
222 response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/browser/files/downloads/"+ids[0]+"/content", nil)
223 if response.Code != 200 || !bytes.Equal(response.Body.Bytes(), payload) {
224 t.Fatalf("offline saved copy unavailable: %d", response.Code)
225 }
226 saved, err := readSavedDownload(s.profile, ids[0])
227 if err != nil || saved.Path != chosen {
228 t.Fatal("explicit saved location replaced")
229 }
230 })
231 }
232}
233
234func TestNativeDownloadFailureRetryAndCancellation(t *testing.T) {
235 for _, mode := range []string{"failed-read", "account-lock", "symlink"} {
236 t.Run(mode, func(t *testing.T) {
237 id := uuid.NewString()
238 item := browserDownloadInfo{ID: id, Name: "retry.txt", State: "saved", Path: "Downloads/retry.txt"}
239 payload := bytes.Repeat([]byte("test payload"), 10000)
240 s, workspace, directory := nativeDownloadFixture(t, "macos", []browserDownloadInfo{item}, payload)
241 switch mode {
242 case "failed-read":
243 if err := os.WriteFile(filepath.Join(directory, "fail"), nil, 0600); err != nil {
244 t.Fatal(err)
245 }
246 case "account-lock":
247 if err := os.WriteFile(filepath.Join(directory, "block"), nil, 0600); err != nil {
248 t.Fatal(err)
249 }
250 case "symlink":
251 if err := os.Symlink(t.TempDir(), filepath.Join(workspace, "Downloads")); err != nil {
252 t.Skip(err)
253 }
254 }
255 transfer, err := s.startNativeDownload(item)
256 if err != nil {
257 t.Fatal(err)
258 }
259 if mode == "account-lock" {
260 deadline := time.Now().Add(5 * time.Second)
261 for {
262 if _, err := os.Stat(filepath.Join(directory, "reading")); err == nil {
263 break
264 }
265 if time.Now().After(deadline) {
266 t.Fatal("reader did not start")
267 }
268 time.Sleep(10 * time.Millisecond)
269 }
270 s.account.lock()
271 }
272 select {
273 case <-transfer.done:
274 case <-time.After(5 * time.Second):
275 t.Fatal("failed transfer was not retired")
276 }
277 if transfer.err == nil {
278 t.Fatal("failed transfer published success")
279 }
280 if _, err := readSavedDownload(s.profile, id); err == nil {
281 t.Fatal("failed download has saved receipt")
282 }
283 files, _ := filepath.Glob(filepath.Join(workspace, "Downloads", "*"))
284 if len(files) != 0 {
285 t.Fatal("failed download left a host file", files)
286 }
287 if mode == "symlink" {
288 return
289 }
290 _ = os.Remove(filepath.Join(directory, "fail"))
291 _ = os.Remove(filepath.Join(directory, "block"))
292 if mode == "account-lock" {
293 s.account.setKey(make([]byte, 32))
294 }
295 response := windowsBrowserRequestForTest(s, "POST", "/api/browser/download-retry", []byte(`{"id":"`+id+`"}`))
296 if response.Code != 200 {
297 t.Fatalf("retry refused: %d %s", response.Code, response.Body.String())
298 }
299 saved, err := s.downloadInfo(t.Context(), id)
300 if err != nil {
301 t.Fatal(err)
302 }
303 got, _ := os.ReadFile(saved.Path)
304 if !bytes.Equal(got, payload) {
305 t.Fatal("retry did not complete host copy")
306 }
307 })
308 }
309}
310
311func TestNativeBrowserFileSaveUsesProductionHostBridge(t *testing.T) {
312 item := browserDownloadInfo{ID: uuid.NewString(), Name: "download.bin", State: "saved", Path: "Downloads/download.bin"}
313 payload := bytes.Repeat([]byte{0, 255, 42}, 50000)
314 s, workspace, _ := nativeDownloadFixture(t, "windows-11", []browserDownloadInfo{item}, payload)
315 workload := httptest.NewServer(s.handler())
316 defer workload.Close()
317 endpoint, _ := url.Parse(workload.URL)
318 s.origin = "http://localhost:" + endpoint.Port()
319 workloadURL, _ := url.Parse(s.origin)
320 jar, _ := cookiejar.New(nil)
321 jar.SetCookies(workloadURL, []*http.Cookie{
322 {Name: s.cookieName(), Value: s.session, Path: "/"},
323 {Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token), Path: "/"},
324 })
325 session, err := remotehost.LocalSession(t.Context(), s.origin, remotehost.PublicManifest{InstanceID: strings.Repeat("a", 64)}, jar)
326 if err != nil {
327 t.Fatal(err)
328 }
329 gateway := testServer(t)
330 gateway.profile = filepath.Join(s.profile, "desktop-entry")
331 gateway.configPath = filepath.Join(gateway.profile, "config.json")
332 if err = os.MkdirAll(gateway.profile, 0700); err != nil {
333 t.Fatal(err)
334 }
335 gateway.remote = newDesktopGateway(gateway.profile, nil)
336 generation := gateway.remote.desktop.generation
337 ctx, cancel := context.WithCancel(t.Context())
338 gateway.remote.desktop.active = &desktopTarget{id: generation, mode: "local", ctx: ctx, cancel: cancel, session: session}
339 t.Cleanup(gateway.remote.close)
340 lock, err := openControllerLock(gateway.profile, os.O_CREATE|os.O_RDWR)
341 if err != nil {
342 t.Fatal(err)
343 }
344 defer lock.Close()
345 if err = lockController(lock); err != nil {
346 t.Fatal(err)
347 }
348 defer unlockController(lock)
349 server := httptest.NewServer(gateway.handler())
350 defer server.Close()
351 endpoint, _ = url.Parse(server.URL)
352 port, _ := strconv.Atoi(endpoint.Port())
353 gateway.origin = "http://localhost:" + endpoint.Port()
354 if err = writePrivate(filepath.Join(gateway.profile, "control.json"), controlFile{Port: port, Token: gateway.token, PID: os.Getpid()}); err != nil {
355 t.Fatal(err)
356 }
357 destination := filepath.Join(workspace, "chosen.bin")
358 result, err := BrowserFileForConnection(gateway.configPath, generation, "save", item.ID, destination)
359 if err != nil || result.Path != destination {
360 t.Fatalf("native bridge save: %#v %v", result, err)
361 }
362 for _, path := range []string{destination, filepath.Join(workspace, "Downloads", item.Name)} {
363 got, err := os.ReadFile(path)
364 if err != nil || !bytes.Equal(got, payload) {
365 t.Errorf("save bytes mismatch: %v", err)
366 }
367 }
368 receipt, err := readSavedDownload(s.profile, item.ID)
369 if err != nil || receipt.Path != destination {
370 t.Fatal("native Save As did not replace the saved location")
371 }
372 if _, err = BrowserFileForConnection(gateway.configPath, "old-connection", "save", item.ID, filepath.Join(workspace, "refused.bin")); err == nil {
373 t.Fatal("old connection saved a download")
374 }
375}
376
377// Runs the production native browser controller with actual Chromium. The
378// browser download then crosses the production HTTP and chunked file paths.
379func TestNativeDownloadActualChromiumToHost(t *testing.T) {
380 if os.Getenv("CAGE_BROWSER_TEST_PLAYWRIGHT") == "" || os.Getenv("CAGE_BROWSER_TEST_CHROMIUM") == "" {
381 t.Skip("set the test Playwright and Chromium paths")
382 }
383 root, err := filepath.Abs("../..")
384 if err != nil {
385 t.Fatal(err)
386 }
387 s, workspace, _ := nativeDownloadFixture(t, "macos", nil, nil)
388 browserDirectory := filepath.Join(t.TempDir(), "native-browser")
389 t.Cleanup(func() {
390 client := s.windowsBrowserControl
391 client.mu.Lock()
392 defer client.mu.Unlock()
393 if client.cmd != nil {
394 // Give the test controller its stdin EOF so Playwright closes Chrome
395 // before testing removes the browser's isolated profile directory.
396 _ = client.input.Close()
397 _ = client.cmd.Wait()
398 client.cmd, client.input, client.output = nil, nil, nil
399 }
400 })
401 s.windowsBrowserControl.start = func(ctx context.Context) (*exec.Cmd, error) {
402 return exec.CommandContext(ctx, "node", filepath.Join(root, "scripts/guest-os/tests/native-download-host-fixture.mjs"), root, browserDirectory), nil
403 }
404 var item browserDownloadInfo
405 deadline := time.Now().Add(30 * time.Second)
406 for time.Now().Before(deadline) {
407 response := windowsBrowserRequestForTest(s, "GET", "/api/browser/tabs", nil)
408 if response.Code != 200 {
409 t.Fatalf("native tabs failed: %d %s", response.Code, response.Body.String())
410 }
411 var state struct{ Downloads []browserDownloadInfo }
412 if err = json.Unmarshal(response.Body.Bytes(), &state); err != nil {
413 t.Fatal(err)
414 }
415 if len(state.Downloads) > 0 {
416 item = state.Downloads[0]
417 if item.State == "failed" {
418 t.Fatal(item.Error)
419 }
420 if item.State == "saved" {
421 break
422 }
423 }
424 time.Sleep(20 * time.Millisecond)
425 }
426 if item.State != "saved" || item.Path != filepath.Join(workspace, "Downloads", "native-download.bin") {
427 t.Fatalf("not saved on the host: %#v", item)
428 }
429 payload := make([]byte, 131089)
430 for index := range payload {
431 payload[index] = byte(index % 251)
432 }
433 actual, err := os.ReadFile(item.Path)
434 if err != nil || !bytes.Equal(actual, payload) {
435 t.Fatalf("downloaded host bytes differ: %v", err)
436 }
437 response := windowsBrowserRequestForTest(s, "GET", "/api/browser/files/downloads/"+item.ID+"/content", nil)
438 if response.Code != 200 || !bytes.Equal(response.Body.Bytes(), payload) {
439 t.Fatal("native HTTP content differs", response.Code)
440 }
441 t.Log("actual Chromium click downloaded 131089 bytes; native transfer published a verified host file and the production HTTP content returned identical bytes")
442}
443
444func TestNativeDownloadCompletionUpdatesIdleBrowserEvents(t *testing.T) {
445 item := browserDownloadInfo{ID: uuid.NewString(), Name: "event.bin", State: "saved", Path: "Downloads/event.bin"}
446 s, _, directory := nativeDownloadFixture(t, "macos", []browserDownloadInfo{item}, []byte("event payload"))
447 block := filepath.Join(directory, "block")
448 if err := os.WriteFile(block, nil, 0600); err != nil {
449 t.Fatal(err)
450 }
451 server := httptest.NewServer(s.handler())
452 defer server.Close()
453 endpoint, _ := url.Parse(server.URL)
454 s.origin = "http://localhost:" + endpoint.Port()
455 request, err := http.NewRequestWithContext(t.Context(), "GET", s.origin+"/api/browser/events", nil)
456 if err != nil {
457 t.Fatal(err)
458 }
459 request.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
460 request.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
461 client := &http.Client{Timeout: 5 * time.Second}
462 response, err := client.Do(request)
463 if err != nil {
464 t.Fatal(err)
465 }
466 defer response.Body.Close()
467 if response.StatusCode != 200 {
468 t.Fatal(response.StatusCode)
469 }
470 scanner := bufio.NewScanner(response.Body)
471 next := func() browserDownloadInfo {
472 t.Helper()
473 for scanner.Scan() {
474 data, ok := strings.CutPrefix(scanner.Text(), "data: ")
475 if !ok {
476 continue
477 }
478 var state struct{ Downloads []browserDownloadInfo }
479 if json.Unmarshal([]byte(data), &state) != nil || len(state.Downloads) != 1 {
480 t.Fatal("invalid event snapshot")
481 }
482 return state.Downloads[0]
483 }
484 t.Fatalf("browser event ended before download state: %v", scanner.Err())
485 return browserDownloadInfo{}
486 }
487 initial := next()
488 if initial.State != "saving" || initial.Path != "" {
489 t.Fatalf("incomplete copy published a host path: %#v", initial)
490 }
491 if err = os.Remove(block); err != nil {
492 t.Fatal(err)
493 }
494 for result := next(); ; result = next() {
495 if result.State == "saved" {
496 got, err := os.ReadFile(result.Path)
497 if err != nil || string(got) != "event payload" {
498 t.Fatal("saved event preceded the host file")
499 }
500 break
501 }
502 if result.State == "failed" {
503 t.Fatal(result.Error)
504 }
505 }
506}