跳到主要内容

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

浏览文件

control_recovery_test.go

236 行 · 7.4 KB历史下载
1package workbench
2
3import (
4 "context"
5 "errors"
6 "net"
7 "net/http"
8 "net/http/httptest"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strconv"
13 "strings"
14 "testing"
15 "time"
16)
17
18// Reusing a dead controller's port must not turn an old token into a
19// permanently unopenable profile, including when its PID has been reused.
20func TestDesktopRecoversStaleRecordOnReusedPort(t *testing.T) {
21 for _, held := range []bool{false, true} {
22 t.Run(strconv.FormatBool(held), func(t *testing.T) {
23 profile := t.TempDir()
24 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
25 http.Error(w, "old token", http.StatusUnauthorized)
26 }))
27 defer server.Close()
28 _, portText, _ := net.SplitHostPort(server.Listener.Addr().String())
29 port, _ := strconv.Atoi(portText)
30 if err := writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, PID: os.Getpid(), Token: strings.Repeat("a", 64)}); err != nil {
31 t.Fatal(err)
32 }
33 lock, err := os.OpenFile(filepath.Join(profile, "control.lock"), os.O_CREATE|os.O_RDWR, 0600)
34 if err != nil {
35 t.Fatal(err)
36 }
37 defer lock.Close()
38 if held {
39 if err := lockController(lock); err != nil {
40 t.Fatal(err)
41 }
42 defer unlockController(lock)
43 }
44 started := errors.New("replacement started")
45 _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error { return started })
46 if held && (err == nil || errors.Is(err, started)) {
47 t.Fatalf("replaced a locked unauthenticated controller: %v", err)
48 }
49 if !held && !errors.Is(err, started) {
50 t.Fatalf("stale record prevented restart: %v", err)
51 }
52 if !held {
53 exe, _ := os.Executable()
54 st, err := NewDesktopLocalController(filepath.Join(profile, "config.json"), exe).Status(context.Background())
55 if err != nil || !st.Known || st.ServiceRunning {
56 t.Fatalf("stale port/PID reported as a live controller: %+v %v", st, err)
57 }
58 }
59 })
60 }
61}
62
63func TestControllerRestartAfterGracefulAndForcedExit(t *testing.T) {
64 for _, forced := range []bool{false, true} {
65 t.Run(strconv.FormatBool(forced), func(t *testing.T) {
66 profile := t.TempDir()
67 config := filepath.Join(profile, "config.json")
68 keep := filepath.Join(profile, "personal-data-sentinel")
69 if err := os.WriteFile(keep, []byte("preserve projects and account data"), 0600); err != nil {
70 t.Fatal(err)
71 }
72 exe, err := os.Executable()
73 if err != nil {
74 t.Fatal(err)
75 }
76 start := func() *exec.Cmd {
77 cmd := exec.Command(exe, "-test.run=^TestServeShutdownHandoff$", "-test.timeout=30s")
78 cmd.Env = append(os.Environ(), "CAGE_TEST_SHUTDOWN_CONFIG="+config)
79 if err := cmd.Start(); err != nil {
80 t.Fatal(err)
81 }
82 t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
83 return cmd
84 }
85 waitReady := func() *controllerClient {
86 deadline := time.Now().Add(10 * time.Second)
87 for time.Now().Before(deadline) {
88 c, err := connectController(profile)
89 if err == nil {
90 return c
91 }
92 time.Sleep(25 * time.Millisecond)
93 }
94 t.Fatal("controller never became ready")
95 return nil
96 }
97 stop := func(c *controllerClient) {
98 deadline := time.Now().Add(3 * time.Second)
99 for {
100 status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil)
101 if err != nil {
102 t.Fatal(err)
103 }
104 if status == http.StatusOK {
105 break
106 }
107 if status != http.StatusConflict || time.Now().After(deadline) {
108 t.Fatalf("idle handoff returned HTTP %d", status)
109 }
110 time.Sleep(25 * time.Millisecond)
111 }
112 if err := c.waitForExit(); err != nil {
113 t.Fatal(err)
114 }
115 }
116 cmd := start()
117 c := waitReady()
118 old := c.record
119 if forced {
120 if err := cmd.Process.Kill(); err != nil {
121 t.Fatal(err)
122 }
123 _ = cmd.Wait()
124 if _, err := os.Stat(filepath.Join(profile, "control.json")); err != nil {
125 t.Fatalf("forced exit did not leave the expected stale record: %v", err)
126 }
127 } else {
128 stop(c)
129 if err := cmd.Wait(); err != nil {
130 t.Fatal(err)
131 }
132 if _, err := os.Stat(filepath.Join(profile, "control.json")); !os.IsNotExist(err) {
133 t.Fatalf("normal exit left a connection record: %v", err)
134 }
135 }
136 c.close()
137 if !controllerLockFree(profile) {
138 t.Fatal("exited process left the OS lock held")
139 }
140 // Occupy the old port with a different service while reopening Cage.
141 listener, err := net.Listen("tcp4", net.JoinHostPort("127.0.0.1", strconv.Itoa(old.Port)))
142 if err != nil {
143 t.Fatal(err)
144 }
145 foreign := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "different service", 401) }))
146 foreign.Listener.Close()
147 foreign.Listener = listener
148 foreign.Start()
149 defer foreign.Close()
150 _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error { cmd = start(); return nil })
151 if err != nil {
152 t.Fatalf("reopen failed: %v", err)
153 }
154 c = waitReady()
155 defer c.close()
156 if c.record.PID == old.PID || c.record.Token == old.Token {
157 t.Fatal("reopen reused a dead controller's identity")
158 }
159 stop(c)
160 if err := cmd.Wait(); err != nil {
161 t.Fatal(err)
162 }
163 if _, err := os.Stat(filepath.Join(profile, "control.json")); !os.IsNotExist(err) {
164 t.Fatalf("reopened controller left a record: %v", err)
165 }
166 if b, err := os.ReadFile(keep); err != nil || string(b) != "preserve projects and account data" {
167 t.Fatalf("personal data changed: %v", err)
168 }
169 })
170 }
171}
172
173func TestDesktopRecoveryRejectsNonRegularLock(t *testing.T) {
174 profile := t.TempDir()
175 if err := os.Mkdir(filepath.Join(profile, "control.lock"), 0700); err != nil {
176 t.Fatal(err)
177 }
178 if err := os.WriteFile(filepath.Join(profile, "control.json"), []byte("invalid"), 0600); err != nil {
179 t.Fatal(err)
180 }
181 _, err := desktopLaunch(profile, false, DesktopOptions{}, func() error {
182 t.Fatal("started with an unusable lock")
183 return nil
184 })
185 if err == nil {
186 t.Fatal("unusable lock accepted")
187 }
188}
189
190func TestDesktopWaitsForRetiringController(t *testing.T) {
191 profile := t.TempDir()
192 lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
193 if err != nil {
194 t.Fatal(err)
195 }
196 defer lock.Close()
197 if err := lockController(lock); err != nil {
198 t.Fatal(err)
199 }
200 released := make(chan struct{})
201 go func() { time.Sleep(100 * time.Millisecond); _ = unlockController(lock); close(released) }()
202 defer func() { <-released }()
203 started := errors.New("new controller started")
204 _, err = desktopLaunch(profile, false, DesktopOptions{}, func() error {
205 if !controllerLockFree(profile) {
206 t.Error("started before the retiring controller released its lock")
207 }
208 return started
209 })
210 if !errors.Is(err, started) {
211 t.Fatalf("did not resume after shutdown: %v", err)
212 }
213}
214
215func TestPrepareUpdateWaitsForRetiringController(t *testing.T) {
216 profile := t.TempDir()
217 lock, err := openControllerLock(profile, os.O_CREATE|os.O_RDWR)
218 if err != nil {
219 t.Fatal(err)
220 }
221 defer lock.Close()
222 if err := lockController(lock); err != nil {
223 t.Fatal(err)
224 }
225 // Shutdown has removed control.json but has not released the profile yet.
226 released := make(chan struct{})
227 go func() { time.Sleep(100 * time.Millisecond); _ = unlockController(lock); close(released) }()
228 defer func() { <-released }()
229 result, err := PrepareUpdate(filepath.Join(profile, "config.json"), false)
230 if err != nil || result.Status != "prepared" {
231 t.Fatalf("retiring controller prevented update: %+v %v", result, err)
232 }
233 if !controllerLockFree(profile) {
234 t.Fatal("update accepted before the controller released its lock")
235 }
236}