跳到主要内容

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

浏览文件

native_maintenance_test.go

232 行 · 8.1 KB历史下载
1package workbench
2
3import (
4 "archive/tar"
5 "bytes"
6 "crypto/sha256"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net/http"
11 "net/http/httptest"
12 "os"
13 "path/filepath"
14 "runtime"
15 "strings"
16 "sync"
17 "sync/atomic"
18 "testing"
19
20 "github.com/sylvinus/agent-vm/internal/guestos"
21 "golang.org/x/crypto/ssh"
22)
23
24func macMaintenanceKit(t *testing.T) string {
25 t.Helper()
26 kit := filepath.Join(t.TempDir(), "guest-os")
27 for _, name := range []string{"Cage Guest Window.app/Contents/MacOS/CageGuestWindow", "Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard", "project/cage-sshfs", "project/cage-macos-terminal", "native-browser/macos-native-browser.mjs", "native-browser/macos-browser-service.mjs", "register-macos-browser.sh", "native-browser/macos-phone-browser.mjs", "macos-cli.py", "cli_channel.py"} {
28 filename := filepath.Join(kit, filepath.FromSlash(name))
29 if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
30 t.Fatal(err)
31 }
32 if err := os.WriteFile(filename, []byte("current"), 0600); err != nil {
33 t.Fatal(err)
34 }
35 }
36 return kit
37}
38
39func nativeMaintenanceRequest(s *Server, method, path, body string) *httptest.ResponseRecorder {
40 r := httptest.NewRequest(method, s.origin+path, strings.NewReader(body))
41 r.Header.Set("Origin", s.origin)
42 r.Header.Set("Content-Type", "application/json")
43 r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
44 r.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)})
45 w := httptest.NewRecorder()
46 s.handler().ServeHTTP(w, r)
47 return w
48}
49
50func TestNativeVersionsUsesBoundTransportAndActualManifest(t *testing.T) {
51 var mu sync.Mutex
52 snapshot := nativeComponentSnapshot{}
53 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
54 if !strings.Contains(command, "cage-components.json") {
55 return 0, false
56 }
57 if !strings.Contains(command, "cage-cli/bin/python3") || !strings.Contains(command, "hashlib.file_digest") {
58 t.Error("version read omitted the bundled Python and actual file verification")
59 return 1, true
60 }
61 mu.Lock()
62 defer mu.Unlock()
63 if err := json.NewEncoder(channel).Encode(snapshot); err != nil {
64 return 1, true
65 }
66 return 0, true
67 })
68 s := guest.s
69 kit := macMaintenanceKit(t)
70 s.exe = filepath.Join(filepath.Dir(kit), "cage")
71 required, err := guestos.RequiredNativeComponents(kit, guestos.MacOS)
72 if err != nil {
73 t.Fatal(err)
74 }
75 check := func(status string, installed bool) {
76 t.Helper()
77 response := nativeMaintenanceRequest(s, "GET", "/api/environment/versions", "")
78 var result struct {
79 Components componentVersions `json:"components"`
80 Installed bool `json:"installed"`
81 Tools map[string]toolVersion
82 Maintenance struct{ Native bool }
83 }
84 if response.Code != 200 || json.Unmarshal(response.Body.Bytes(), &result) != nil {
85 t.Fatal(response.Code, response.Body.String())
86 }
87 if result.Components.Status != status || result.Installed != installed || !result.Maintenance.Native {
88 t.Fatal(response.Body.String())
89 }
90 if status == "current" && result.Tools["claude"].Current != "2.1.311 (Claude Code)" {
91 t.Fatal("tool version was inferred from required version")
92 }
93 }
94 check("update_required", false)
95 mu.Lock()
96 snapshot.Manifest = &required.GuestManifest
97 snapshot.Installed = true
98 snapshot.Tools = map[string]string{"claude": "2.1.311 (Claude Code)"}
99 mu.Unlock()
100 check("current", true)
101 mu.Lock()
102 snapshot.Installed = false
103 snapshot.Missing = []string{"/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard"}
104 mu.Unlock()
105 check("update_required", false)
106 if err = os.Remove(filepath.Join(kit, "macos-cli.py")); err != nil {
107 t.Fatal(err)
108 }
109 check("unknown", false)
110}
111
112func TestNativeMaintenanceTransfersToExistingMacIdentity(t *testing.T) {
113 if runtime.GOOS != "darwin" {
114 t.Skip("macOS maintenance executes the host OpenSSH and BSD tar")
115 }
116 var calls atomic.Int32
117 var fail atomic.Bool
118 var mu sync.Mutex
119 files := map[string][]byte{}
120 guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) {
121 calls.Add(1)
122 switch {
123 case strings.Contains(command, "mktemp -d /private/var/tmp/cage-components."):
124 if !strings.Contains(command, "cage") {
125 t.Error("missing provisioning identity")
126 }
127 fmt.Fprintln(channel, "/private/var/tmp/cage-components.ABCDEFGH")
128 case strings.Contains(command, "/usr/bin/tar -xf -"):
129 archive := tar.NewReader(channel)
130 for {
131 header, err := archive.Next()
132 if err == io.EOF {
133 break
134 }
135 if err != nil {
136 t.Error(err)
137 return 1, true
138 }
139 if header.Typeflag == tar.TypeReg {
140 contents, err := io.ReadAll(archive)
141 if err != nil {
142 t.Error(err)
143 return 1, true
144 }
145 mu.Lock()
146 files[strings.TrimPrefix(header.Name, "./")] = contents
147 mu.Unlock()
148 }
149 }
150 io.Copy(io.Discard, channel)
151 case strings.Contains(command, "maintain-macos-workbench.sh"):
152 if !strings.Contains(command, "cageuser components") || !strings.Contains(command, "/Users/cage/password") {
153 t.Errorf("maintenance did not retain old provisioning/user identities: %s", command)
154 }
155 if fail.Load() {
156 return 1, true
157 }
158 case strings.Contains(command, "/usr/sbin/chown -R root:wheel /private/var/tmp/cage-components.ABCDEFGH"),
159 strings.Contains(command, "/bin/rm -rf /private/var/tmp/cage-components.ABCDEFGH"):
160 default:
161 t.Errorf("unexpected operation: %s", command)
162 return 1, true
163 }
164 return 0, true
165 })
166 s := guest.s
167 identifier := []byte("existing-mac-identity")
168 if err := os.WriteFile(filepath.Join(s.instanceDir(), "vz-identifier"), identifier, 0600); err != nil {
169 t.Fatal(err)
170 }
171 binding := guestos.MacOSProfile{Version: 1, Instance: "mac", User: "cageuser", MachineID: fmt.Sprintf("%x", sha256.Sum256(identifier))}
172 if err := writePrivate(filepath.Join(s.profile, "macos-guest.json"), binding); err != nil {
173 t.Fatal(err)
174 }
175 kit := macMaintenanceKit(t)
176 manifest, err := guestos.RequiredNativeComponents(kit, guestos.MacOS)
177 if err != nil {
178 t.Fatal(err)
179 }
180 manifestFile := filepath.Join(t.TempDir(), "manifest.json")
181 if err = guestos.WriteNativeComponentManifest(manifestFile, manifest); err != nil {
182 t.Fatal(err)
183 }
184 var log bytes.Buffer
185 for _, shouldFail := range []bool{true, false, false} {
186 fail.Store(shouldFail)
187 err = guestos.MaintainMacOSComponents(t.Context(), s.profile, kit, manifestFile, false, &log, &log)
188 if (err != nil) != shouldFail {
189 t.Fatal(err, log.String())
190 }
191 }
192 mu.Lock()
193 var transferred guestos.NativeComponentManifest
194 err = json.Unmarshal(files["native-components.json"], &transferred)
195 phone := string(files["native-browser/macos-phone-browser.mjs"])
196 mu.Unlock()
197 if err != nil || transferred.Revision != manifest.Revision || phone != "current" {
198 t.Fatal("new capability or manifest missing from native transfer", err)
199 }
200 before := calls.Load()
201 if err = os.WriteFile(filepath.Join(kit, "macos-cli.py"), []byte("changed"), 0600); err != nil {
202 t.Fatal(err)
203 }
204 if guestos.MaintainMacOSComponents(t.Context(), s.profile, kit, manifestFile, false, &log, &log) == nil || calls.Load() != before {
205 t.Fatal("changed source was transferred after manifest selection")
206 }
207}
208
209func TestNativeMaintenanceRejectsLiveTerminalsBeforeJob(t *testing.T) {
210 for _, system := range []string{guestos.MacOS, guestos.Windows11} {
211 t.Run(system, func(t *testing.T) {
212 s := testServer(t)
213 if system == guestos.MacOS {
214 s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "cage"}
215 } else {
216 s.windowsGuest = &guestos.WindowsProfile{}
217 }
218 s.terminals.sessions = map[string]*terminalSession{"active": {}}
219 for _, route := range []string{"/api/environment/update", "/api/environment/tools"} {
220 response := nativeMaintenanceRequest(s, "POST", route, "{}")
221 if response.Code != 409 || !strings.Contains(response.Body.String(), "结束正在运行的终端") || s.jobs.snapshot().Running {
222 t.Fatal(response.Code, response.Body.String())
223 }
224 }
225 s.terminals.sessions = nil
226 response := nativeMaintenanceRequest(s, "POST", "/api/environment/update", "{}")
227 if response.Code != 409 || !strings.Contains(response.Body.String(), "启动并登录客机") {
228 t.Fatal(response.Code, response.Body.String())
229 }
230 })
231 }
232}