跳到主要内容

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

浏览文件

agent_transport_test.go

312 行 · 12.3 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "io"
8 "net/http"
9 "net/http/httptest"
10 "os"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15)
16
17func TestAgentRoutesComeFromTheActualListener(t *testing.T) {
18 s := agentTestController(t)
19 response, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/agent/routes", nil, "", "")
20 if err != nil {
21 t.Fatal(err)
22 }
23 var routes []string
24 _ = json.Unmarshal(response.Data, &routes)
25 for _, pattern := range []string{"POST /api/agent/native", "POST /api/browser/extensions/upload", "POST /api/account/{action}", "GET /api/proxy"} {
26 found := false
27 for _, route := range routes {
28 found = found || route == pattern
29 }
30 if !found {
31 t.Fatal("missing registered UI route", pattern)
32 }
33 }
34}
35
36func TestAgentRawInputAndBinaryOutputUseProductionHandler(t *testing.T) {
37 s := agentTestController(t)
38 s.ready = true
39 var received string
40 s.browserControl = browserClientForTest(t, s, browserTransport(func(r *http.Request) (*http.Response, error) {
41 body := make([]byte, 4)
42 _, _ = r.Body.Read(body)
43 received = string(body)
44 return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"application/json"}}, Body: io.NopCloser(strings.NewReader(`{"upload":"accepted"}`))}, nil
45 }))
46 // Existing UI upload boundary validates and forwards the binary archive.
47 upload, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "POST", "/api/browser/extensions/upload", strings.NewReader("ZIP!"), "application/octet-stream", "")
48 if err != nil || !strings.Contains(string(upload.Data), "accepted") {
49 t.Fatal(upload, err)
50 }
51 if received != "ZIP!" {
52 t.Fatal("raw upload never reached production receiver", err, received)
53 }
54 path := filepath.Join(t.TempDir(), "bundle.zip")
55 result, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/diagnostics/export", nil, "", path)
56 if err != nil || result.Path != path {
57 t.Fatal(result, err)
58 }
59 before, err := os.ReadFile(path)
60 if err != nil || len(before) < 2 || string(before[:2]) != "PK" {
61 t.Fatal("not a real diagnostic ZIP", err)
62 }
63 _, err = AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/diagnostics/export", nil, "", path)
64 if err == nil {
65 t.Fatal("existing output replaced")
66 }
67 after, _ := os.ReadFile(path)
68 if string(after) != string(before) {
69 t.Fatal("original output changed")
70 }
71}
72
73func TestAgentNativeQueueClaimsOnceAndKeepsReceipts(t *testing.T) {
74 s := agentTestController(t)
75 s.account.lock() // Native account unlock must be reachable from the lock screen.
76 if w := request(s, "POST", "/api/agent/native", s.origin, `{"connection_id":"local","request":{"action":"accountDevice"}}`, true); w.Code != 403 {
77 t.Fatal("submission lacked launcher proof", w.Code)
78 }
79 data, err := AgentCall(context.Background(), s.configPath, "native.submit", json.RawMessage(`{"connection_id":"local","request":{"action":"accountDevice","operation":"status"}}`))
80 if err != nil {
81 t.Fatal(err)
82 }
83 var item agentNativeItem
84 _ = json.Unmarshal(data, &item)
85 if item.Status != "pending" {
86 t.Fatal(string(data))
87 }
88 if w := request(s, "GET", "/api/agent/native?consumer=window", "", "", true); w.Code != 403 {
89 t.Fatal("ordinary session could claim native request", w.Code)
90 }
91 ticket := s.issueTicket()
92 registered := request(s, "POST", "/api/agent/native/window", s.origin, `{"ticket":"`+ticket+`"}`, true)
93 var grant struct {
94 Proof string `json:"window_proof"`
95 }
96 _ = json.Unmarshal(registered.Body.Bytes(), &grant)
97 if registered.Code != 200 || len(grant.Proof) != 64 {
98 t.Fatal("native ticket was not exchanged", registered.Code)
99 }
100 if replay := request(s, "POST", "/api/agent/native/window", s.origin, `{"ticket":"`+ticket+`"}`, true); replay.Code != 403 {
101 t.Fatal("native ticket replay accepted")
102 }
103 claim := func(connection string) *httptest.ResponseRecorder {
104 r := httptest.NewRequest("GET", s.origin+"/api/agent/native?consumer=window", nil)
105 r.Header.Set(connectionHeader, connection)
106 r.Header.Set("X-Cage-Agent-Window", grant.Proof)
107 r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
108 w := httptest.NewRecorder()
109 s.handler().ServeHTTP(w, r)
110 return w
111 }
112 if w := claim("old-generation"); strings.Contains(w.Body.String(), item.ID) {
113 t.Fatal("wrong window claimed action")
114 }
115 if w := claim("local"); !strings.Contains(w.Body.String(), item.ID) {
116 t.Fatal("correct window cannot claim", w.Code, w.Body.String())
117 }
118 if w := claim("local"); strings.Contains(w.Body.String(), item.ID) {
119 t.Fatal("native operation replayed")
120 }
121 complete := "/api/agent/native/" + item.ID + "/complete"
122 for _, body := range []string{`{"result":{"supported":false}}`, `{"result":{"supported":true}}`} {
123 if denied := request(s, "POST", complete, s.origin, body, true); denied.Code != 403 {
124 t.Fatal("ordinary session forged native completion")
125 }
126 r := httptest.NewRequest("POST", s.origin+complete, strings.NewReader(body))
127 r.Header.Set("Origin", s.origin)
128 r.Header.Set("Content-Type", "application/json")
129 r.Header.Set("X-Cage-Agent-Window", grant.Proof)
130 r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session})
131 w := httptest.NewRecorder()
132 s.handler().ServeHTTP(w, r)
133 if w.Code != 200 {
134 t.Fatal(w.Code, w.Body.String())
135 }
136 }
137 result, err := AgentRequest(context.Background(), s.configPath, AgentTarget{}, "GET", "/api/agent/native/"+item.ID, nil, "", "")
138 if err != nil {
139 t.Fatal(err)
140 }
141 if !strings.Contains(string(result.Data), `"supported":false`) {
142 t.Fatal("repeated completion changed original result", string(result.Data))
143 }
144 if w := request(s, "GET", "/api/agent/native/"+item.ID, "", "", true); w.Code != 403 {
145 t.Fatal("untrusted view read native secret")
146 }
147}
148
149func TestAgentDesktopConfigurationUsesExplicitSelection(t *testing.T) {
150 full := filepath.Join(t.TempDir(), "config.json")
151 s := agentTestController(t)
152 // Reuse this production listener under the actual desktop-entry location.
153 s.desktopEntry = true
154 endpoint := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { jsonReply(w, map[string]bool{"ok": true}) }))
155 t.Cleanup(endpoint.Close)
156 s.remote = newDesktopGateway(s.profile, &gatewayLocalFixture{endpoint: endpoint, status: DesktopLocalStatus{Known: true}})
157 t.Cleanup(s.remote.close)
158 path := desktopConfigPath(full)
159 if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
160 t.Fatal(err)
161 }
162 record, err := os.ReadFile(filepath.Join(s.profile, "control.json"))
163 if err != nil {
164 t.Fatal(err)
165 }
166 if err := writePrivate(filepath.Join(filepath.Dir(path), "control.json"), json.RawMessage(record)); err != nil {
167 t.Fatal(err)
168 }
169 lock, err := openControllerLock(filepath.Dir(path), os.O_CREATE|os.O_RDWR)
170 if err != nil {
171 t.Fatal(err)
172 }
173 if err := lockController(lock); err != nil {
174 t.Fatal(err)
175 }
176 defer func() { unlockController(lock); lock.Close() }()
177 s.configPath = path
178 target := AgentTarget{Scope: "desktop"}
179 result, err := AgentRequest(context.Background(), full, target, "GET", "/api/client/context", nil, "", "")
180 if err != nil {
181 t.Fatal(err)
182 }
183 var current ClientContext
184 _ = json.Unmarshal(result.Data, &current)
185 if !current.DesktopGateway || current.ConnectionID == "" {
186 t.Fatal(string(result.Data))
187 }
188 body := `{"name":"test host","host":"127.0.0.1","port":22,"user":"qa","auth":{"kind":"agent"}}`
189 result, err = AgentRequest(context.Background(), full, target, "POST", "/api/client/hosts", strings.NewReader(body), "application/json", "")
190 if err != nil {
191 t.Fatal(err)
192 }
193 if result.HTTPStatus != 200 || !strings.Contains(string(result.Data), "test host") {
194 t.Fatal(string(result.Data))
195 }
196 _, err = AgentRequest(context.Background(), full, target, "POST", "/api/stop", strings.NewReader(`{}`), "application/json", "")
197 var ae *AgentError
198 if !errors.As(err, &ae) || ae.Code != "invalid_input" {
199 t.Fatal("implicit target accepted", err)
200 }
201 _, err = AgentRequest(context.Background(), full, AgentTarget{Scope: "selected", Connection: "old"}, "POST", "/api/stop", strings.NewReader(`{}`), "application/json", "")
202 if !errors.As(err, &ae) || ae.Code != "state_conflict" {
203 t.Fatal("stale target accepted", err)
204 }
205 // A real candidate creation returns 202. The HTTP adapter must preserve it.
206 result, err = AgentRequest(context.Background(), full, target, "POST", "/api/client/candidate", strings.NewReader(`{"mode":"local","connection_id":"`+current.ConnectionID+`"}`), "application/json", "")
207 if err != nil || result.HTTPStatus != 202 {
208 t.Fatalf("candidate 202 rejected: %+v %v", result, err)
209 }
210}
211
212func TestAgentSocketUsesTheSameTerminalAndAccountLock(t *testing.T) {
213 s := agentTestController(t)
214 t.Cleanup(s.terminals.close)
215 session, err := s.terminals.start(terminalChildCommand("echo"), "/project", "shell")
216 if err != nil {
217 t.Fatal(err)
218 }
219 input, writer := io.Pipe()
220 output, reader := io.Pipe()
221 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
222 defer cancel()
223 done := make(chan error, 1)
224 go func() {
225 err := AgentSocket(ctx, s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", input, reader)
226 reader.Close()
227 done <- err
228 }()
229 type frame struct {
230 Status string `json:"status"`
231 Type string `json:"type"`
232 Data json.RawMessage `json:"data"`
233 }
234 decoder := json.NewDecoder(output)
235 var connected frame
236 if err := decoder.Decode(&connected); err != nil || connected.Status != "connected" {
237 t.Fatal(connected, err)
238 }
239 payload, _ := json.Marshal(map[string]any{"type": "input", "data": terminalInputLine("agent-socket-parity")})
240 if err := json.NewEncoder(writer).Encode(map[string]any{"type": "text", "data": string(payload)}); err != nil {
241 t.Fatal(err)
242 }
243 var captured strings.Builder
244 for !strings.Contains(captured.String(), "child:agent-socket-parity") {
245 var item frame
246 if err := decoder.Decode(&item); err != nil {
247 t.Fatal(err, captured.String())
248 }
249 if item.Type == "binary" {
250 var data []byte
251 _ = json.Unmarshal(item.Data, &data)
252 captured.Write(data)
253 }
254 }
255 cancel()
256 writer.Close()
257 output.Close()
258 if err := <-done; err != nil {
259 t.Fatal(err)
260 }
261 s.account.lock()
262 if err := AgentSocket(context.Background(), s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", io.NopCloser(strings.NewReader("")), io.Discard); err == nil {
263 t.Fatal("locked account retained terminal access")
264 }
265}
266
267func TestAgentHostGitUsesSameExplicitConsentAndPreservesConfig(t *testing.T) {
268 path := isolatedGitConfig(t)
269 s := agentTestController(t)
270 if _, err := AgentCall(context.Background(), s.configPath, "host.git.enable", json.RawMessage(`{}`)); err == nil {
271 t.Fatal("missing explicit consent accepted")
272 }
273 _, err := AgentCall(context.Background(), s.configPath, "host.git.enable", json.RawMessage(`{"confirm":true}`))
274 if err != nil {
275 t.Fatal(err)
276 }
277 body, err := os.ReadFile(path)
278 if err != nil || !strings.Contains(string(body), "bareRepository = explicit") || !strings.Contains(string(body), "name = Cage Test") {
279 t.Fatal("real Git config not preserved", err, string(body))
280 }
281 ui := request(s, "GET", "/api/host/git", "", "", true)
282 if !strings.Contains(ui.Body.String(), `"ready":true`) {
283 t.Fatal(ui.Body.String())
284 }
285}
286
287func TestAgentDoesNotExportNativeDeviceWrappingCredentials(t *testing.T) {
288 for _, path := range []string{"/api/agent/native/window", "/api/account/device-enroll", "/api/account/device-unlock", "/api/account/device-revoke", "/api/launch", "/api/session", "/api/desktop-local/trusted-login"} {
289 _, err := AgentRequest(context.Background(), filepath.Join(t.TempDir(), "config.json"), AgentTarget{}, "POST", path, strings.NewReader(`{}`), "application/json", "")
290 var ae *AgentError
291 if !errors.As(err, &ae) || ae.Code != "native_transport_required" {
292 t.Fatal(path, err)
293 }
294 }
295}
296
297func TestAgentSocketRejectsMalformedInputWithoutWaitingForRemote(t *testing.T) {
298 s := agentTestController(t)
299 t.Cleanup(s.terminals.close)
300 session, err := s.terminals.start(terminalChildCommand("echo"), "/project", "shell")
301 if err != nil {
302 t.Fatal(err)
303 }
304 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
305 defer cancel()
306 started := time.Now()
307 err = AgentSocket(ctx, s.configPath, AgentTarget{}, "/api/terminals/"+session.id+"/stream", io.NopCloser(strings.NewReader("malformed JSON")), io.Discard)
308 var ae *AgentError
309 if !errors.As(err, &ae) || ae.Code != "invalid_input" || time.Since(started) > time.Second {
310 t.Fatal("malformed input hung or was reported as success", err)
311 }
312}