跳到主要内容

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

浏览文件

control_lifecycle_test.go

264 行 · 8.3 KB历史下载
1package workbench
2
3import (
4 "net"
5 "net/http"
6 "net/http/httptest"
7 "os"
8 "path/filepath"
9 "strconv"
10 "strings"
11 "sync"
12 "sync/atomic"
13 "testing"
14 "time"
15)
16
17func TestAlreadyAdmittedHandoffsShutDownOnlyOnce(t *testing.T) {
18 s := testServer(t)
19 var count atomic.Int32
20 stopped := make(chan struct{}, 16)
21 s.shutdown = func() { count.Add(1); stopped <- struct{}{} }
22 var callers sync.WaitGroup
23 // These requests have already passed the handler's activity admission. A
24 // later request must recheck closing once it acquires the operation lock.
25 for range 16 {
26 callers.Add(1)
27 go func() {
28 defer callers.Done()
29 r := httptest.NewRequest("POST", s.origin+"/api/handoff", strings.NewReader(`{"token":"`+s.token+`"}`))
30 r.Header.Set("Content-Type", "application/json")
31 w := httptest.NewRecorder()
32 s.handoff(w, r)
33 if w.Code != 200 && w.Code != 409 && w.Code != 503 {
34 t.Errorf("unexpected handoff response: %d", w.Code)
35 }
36 }()
37 }
38 callers.Wait()
39 select {
40 case <-stopped:
41 case <-time.After(time.Second):
42 t.Fatal("handoff did not shut down")
43 }
44 // A deterministic late admitted request also covers the scheduling case
45 // where all simultaneous callers above happened to observe a locked op.
46 r := httptest.NewRequest("POST", s.origin+"/api/handoff", strings.NewReader(`{"token":"`+s.token+`"}`))
47 r.Header.Set("Content-Type", "application/json")
48 w := httptest.NewRecorder()
49 s.handoff(w, r)
50 if w.Code != http.StatusServiceUnavailable || count.Load() != 1 {
51 t.Fatalf("repeated handoff restarted shutdown: status=%d calls=%d", w.Code, count.Load())
52 }
53}
54
55func TestHandoffRequiresLauncherSecretAndIdleEnvironment(t *testing.T) {
56 for _, busy := range []string{"none", "job", "terminal", "vm", "operation"} {
57 t.Run(busy, func(t *testing.T) {
58 s := testServer(t)
59 var stopped atomic.Bool
60 s.shutdown = func() { stopped.Store(true) }
61 switch busy {
62 case "job":
63 s.setJobForTest(Job{ID: "active", Running: true})
64 case "terminal":
65 s.terminals.sessions = map[string]*terminalSession{"live": {}}
66 case "vm":
67 path := filepath.Join(s.profile, "state", "lima", "base-building", "cage-running.json")
68 if err := writePrivate(path, map[string]int{"pid": os.Getpid()}); err != nil {
69 t.Fatal(err)
70 }
71 case "operation":
72 s.op.Lock()
73 defer s.op.Unlock()
74 }
75 if w := request(s, "POST", "/api/handoff", s.origin, `{"token":"wrong"}`, true); w.Code != 401 {
76 t.Fatalf("session bypassed launcher secret: %d", w.Code)
77 }
78 if w := request(s, "POST", "/api/handoff", "https://elsewhere.example", `{"token":"`+s.token+`"}`, false); w.Code != 403 {
79 t.Fatalf("cross-origin handoff: %d", w.Code)
80 }
81 w := request(s, "POST", "/api/handoff", s.origin, `{"token":"`+s.token+`"}`, false)
82 if busy != "none" {
83 if w.Code != 409 || stopped.Load() {
84 t.Fatalf("terminated busy controller: %d", w.Code)
85 }
86 return
87 }
88 if w.Code != 200 {
89 t.Fatal(w.Code, w.Body.String())
90 }
91 deadline := time.Now().Add(time.Second)
92 for !stopped.Load() && time.Now().Before(deadline) {
93 time.Sleep(time.Millisecond)
94 }
95 if !stopped.Load() {
96 t.Fatal("idle controller did not shut down")
97 }
98 launchResult := httptest.NewRecorder()
99 s.launch(launchResult, "start", func() error { t.Error("new work started after handoff"); return nil })
100 if launchResult.Code != http.StatusServiceUnavailable {
101 t.Fatalf("new job accepted after handoff: %d", launchResult.Code)
102 }
103 if w := request(s, "POST", "/api/terminals", s.origin, `{}`, true); w.Code != 503 {
104 t.Fatalf("terminal accepted after handoff: %d", w.Code)
105 }
106 })
107 }
108}
109
110func TestDesktopRejectsUnknownAndDifferentBuildsWithoutStoppingThem(t *testing.T) {
111 current, err := currentController()
112 if err != nil {
113 t.Fatal(err)
114 }
115 for _, kind := range []string{"same", "same-version-other-build", "legacy"} {
116 t.Run(kind, func(t *testing.T) {
117 profile := t.TempDir()
118 lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
119 if err != nil {
120 t.Fatal(err)
121 }
122 defer lock.Close()
123 if err := lockController(lock); err != nil {
124 t.Fatal(err)
125 }
126 defer unlockController(lock)
127 identity := current
128 if kind == "same-version-other-build" {
129 identity.Build = "different-build"
130 }
131 if kind == "legacy" {
132 identity = ControllerIdentity{}
133 }
134 var stopCalled bool
135 var origin string
136 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
137 switch r.URL.Path {
138 case "/api/launch":
139 jsonReply(w, launchResponse{URL: origin + "/#ticket", Controller: identity})
140 case "/api/handoff":
141 http.Error(w, "busy", 409)
142 case "/api/stop":
143 stopCalled = true
144 http.Error(w, "unexpected", 500)
145 default:
146 http.NotFound(w, r)
147 }
148 }))
149 defer server.Close()
150 _, portString, _ := net.SplitHostPort(server.Listener.Addr().String())
151 port, _ := strconv.Atoi(portString)
152 origin = "http://localhost:" + portString
153 if err := writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, Token: string(make([]byte, 64)), PID: os.Getpid()}); err != nil {
154 t.Fatal(err)
155 }
156 entry, err := Desktop(filepath.Join(profile, "config.json"), DesktopOptions{})
157 if err != nil {
158 t.Fatal(err)
159 }
160 if kind == "same" {
161 if entry.Status != "ready" || entry.URL == "" {
162 t.Fatalf("same build refused: %+v", entry)
163 }
164 } else if entry.Status != "upgrade_pending" || entry.URL != "" {
165 t.Fatalf("old build silently connected: %+v", entry)
166 }
167 if stopCalled {
168 t.Fatal("startup stopped existing work")
169 }
170 if kind == "legacy" {
171 if _, err := Desktop(filepath.Join(profile, "config.json"), DesktopOptions{CompleteUpdate: true}); err == nil {
172 t.Fatal("unverified legacy PID accepted")
173 }
174 if stopCalled {
175 t.Fatal("signalled or stopped unverified legacy process")
176 }
177 }
178 })
179 }
180}
181
182func TestPrepareUpdateDoesNotAcceptUnresponsiveLockedController(t *testing.T) {
183 profile := t.TempDir()
184 f, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_CREATE|os.O_RDWR, 0600)
185 if err != nil {
186 t.Fatal(err)
187 }
188 defer f.Close()
189 if err = lockController(f); err != nil {
190 t.Fatal(err)
191 }
192 defer unlockController(f)
193 if _, err := PrepareUpdate(filepath.Join(profile, "config.json"), false); err == nil {
194 t.Fatal("locked offline service accepted as safe to replace")
195 }
196}
197
198func TestPrepareUpdateWaitsForRoutineProbeAndPreservesActiveWork(t *testing.T) {
199 for _, activeJob := range []bool{false, true} {
200 t.Run(strconv.FormatBool(activeJob), func(t *testing.T) {
201 s := testServer(t)
202 var err error
203 s.identity, err = currentController()
204 if err != nil {
205 t.Fatal(err)
206 }
207 lock, err := openControllerLock(s.profile, os.O_CREATE|os.O_RDWR)
208 if err != nil {
209 t.Fatal(err)
210 }
211 defer lock.Close()
212 if err := lockController(lock); err != nil {
213 t.Fatal(err)
214 }
215 defer unlockController(lock)
216 var stopped atomic.Bool
217 shutdownDone := make(chan struct{})
218 s.shutdown = func() {
219 stopped.Store(true)
220 _ = unlockController(lock)
221 close(shutdownDone)
222 }
223 server := httptest.NewServer(s.handler())
224 defer server.Close()
225 _, portString, _ := net.SplitHostPort(server.Listener.Addr().String())
226 port, _ := strconv.Atoi(portString)
227 s.origin = "http://localhost:" + portString
228 if err := writePrivate(filepath.Join(s.profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: s.identity}); err != nil {
229 t.Fatal(err)
230 }
231 if activeJob {
232 s.setJobForTest(Job{ID: "active", Running: true})
233 }
234 // The first handoff reaches a real occupied operation lock. A
235 // routine probe releases it without creating a user job or VM.
236 s.op.Lock()
237 released := make(chan struct{})
238 go func() {
239 time.Sleep(100 * time.Millisecond)
240 s.op.Unlock()
241 close(released)
242 }()
243 result, err := PrepareUpdate(s.configPath, false)
244 <-released
245 if result.Status == "prepared" {
246 select {
247 case <-shutdownDone:
248 case <-time.After(time.Second):
249 t.Fatal("prepared update did not finish shutting down")
250 }
251 }
252 if err != nil {
253 t.Fatal(err)
254 }
255 if activeJob {
256 if result.Status != "stop_required" || stopped.Load() {
257 t.Fatalf("active work was not preserved: %+v stopped=%v", result, stopped.Load())
258 }
259 } else if result.Status != "prepared" || !stopped.Load() {
260 t.Fatalf("routine probe prevented idle update: %+v stopped=%v", result, stopped.Load())
261 }
262 })
263 }
264}