跳到主要内容

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

浏览文件

account_test.go

247 行 · 7.3 KB历史下载
1package workbench
2
3import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "image"
8 "image/color"
9 "image/png"
10 "net/http"
11 "net/http/httptest"
12 "os"
13 "path/filepath"
14 "strings"
15 "testing"
16 "time"
17
18 "github.com/gorilla/websocket"
19)
20
21func newTestAccount(t *testing.T) *localAccount {
22 t.Helper()
23 a, err := loadLocalAccount(t.TempDir())
24 if err != nil {
25 t.Fatal(err)
26 }
27 if err = a.create("林间工作室", "initial-test-password", ""); err != nil {
28 t.Fatal(err)
29 }
30 t.Cleanup(a.lock)
31 return a
32}
33
34func TestLocalAccountEncryptionPasswordChangeAndReload(t *testing.T) {
35 a := newTestAccount(t)
36 key, _ := a.desktopKey()
37 defer clear(key)
38 data, err := os.ReadFile(a.path)
39 if err != nil || bytes.Contains(data, []byte("initial-test-password")) || bytes.Contains(data, key) {
40 t.Fatal("plaintext credentials persisted", err)
41 }
42 if err = a.changePassword("initial-test-password", "replacement-test-password"); err != nil {
43 t.Fatal(err)
44 }
45 a.lock()
46 reloaded, err := loadLocalAccount(filepath.Dir(a.path))
47 if err != nil {
48 t.Fatal(err)
49 }
50 defer reloaded.lock()
51 if reloaded.view().Unlocked {
52 t.Fatal("reloaded account must be locked")
53 }
54 if err = reloaded.unlock("initial-test-password"); err == nil {
55 t.Fatal("old password accepted")
56 }
57 reloaded.nextAttempt = time.Time{}
58 if err = reloaded.unlock("replacement-test-password"); err != nil {
59 t.Fatal(err)
60 }
61 after, _ := reloaded.desktopKey()
62 defer clear(after)
63 if !bytes.Equal(after, key) {
64 t.Fatal("password change rotated the guest key and lost existing login access")
65 }
66 if err = reloaded.create("other", "new-password", ""); err == nil {
67 t.Fatal("second account replaced the existing account")
68 }
69}
70
71func TestLocalAccountFailedSavePreservesExistingPassword(t *testing.T) {
72 a := newTestAccount(t)
73 path := a.path
74 a.path = t.TempDir()
75 if err := a.changePassword("initial-test-password", "replacement-test-password"); err == nil {
76 t.Fatal("save unexpectedly succeeded")
77 }
78 a.path = path
79 a.lock()
80 if err := a.unlock("initial-test-password"); err != nil {
81 t.Fatal("failed save changed the active password", err)
82 }
83}
84
85func TestLocalAccountProfileAndAvatarPersistWithoutRekey(t *testing.T) {
86 a := newTestAccount(t)
87 before, _ := a.desktopKey()
88 defer clear(before)
89 img := image.NewRGBA(image.Rect(0, 0, 200, 100))
90 img.Set(100, 50, color.RGBA{R: 240, G: 100, B: 40, A: 255})
91 var b bytes.Buffer
92 _ = png.Encode(&b, img)
93 avatar := "data:image/png;base64," + base64.StdEncoding.EncodeToString(b.Bytes())
94 if err := a.updateProfile(" 山雀 ", avatar); err != nil {
95 t.Fatal(err)
96 }
97 data, _ := base64.StdEncoding.DecodeString(strings.SplitN(a.view().Avatar, ",", 2)[1])
98 cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
99 if err != nil || cfg.Width != 128 || cfg.Height != 128 {
100 t.Fatal("avatar was not normalized", cfg, err)
101 }
102 loaded, err := loadLocalAccount(filepath.Dir(a.path))
103 if err != nil {
104 t.Fatal(err)
105 }
106 if loaded.view().Username != "山雀" || loaded.view().Avatar != a.view().Avatar {
107 t.Fatal("profile did not persist")
108 }
109 after, _ := a.desktopKey()
110 defer clear(after)
111 if !bytes.Equal(before, after) {
112 t.Fatal("profile edit changed credential key")
113 }
114 if err := a.updateProfile("山雀", "data:image/svg+xml;base64,PHN2Zy8+"); err == nil {
115 t.Fatal("active content accepted as avatar")
116 }
117}
118
119func TestLocalAccountCorruptionCannotBecomeFirstRun(t *testing.T) {
120 a := newTestAccount(t)
121 if err := os.WriteFile(a.path, []byte(`{"version":1}`), 0600); err != nil {
122 t.Fatal(err)
123 }
124 if _, err := loadLocalAccount(filepath.Dir(a.path)); err == nil {
125 t.Fatal("corrupt account silently became setup/unlocked")
126 }
127}
128
129func TestAccountLockBlocksRoutesAndCancelsAccess(t *testing.T) {
130 s := testServer(t)
131 ctx, ok := s.account.access()
132 if !ok {
133 t.Fatal("fixture locked")
134 }
135 w := request(s, "POST", "/api/account/lock", s.origin, "{}", true)
136 if w.Code != 200 {
137 t.Fatal(w.Code, w.Body.String())
138 }
139 select {
140 case <-ctx.Done():
141 default:
142 t.Fatal("active requests not cancelled")
143 }
144 for _, path := range []string{"/api/settings", "/api/terminals", "/api/vnc-credentials", "/api/claude-desktop/vnc-credentials", "/api/audio"} {
145 if w = request(s, "GET", path, "", "", true); w.Code != 423 {
146 t.Fatal(path, w.Code)
147 }
148 }
149 if w = request(s, "GET", "/api/account", "", "", true); w.Code != 200 {
150 t.Fatal("lock screen cannot read public profile")
151 }
152 if w = request(s, "GET", "/api/account", "", "", false); w.Code != 401 {
153 t.Fatal("account bypassed host session")
154 }
155}
156
157func TestLockDisconnectsTerminalViewerWithoutEndingSession(t *testing.T) {
158 s := testServer(t)
159 term := &terminalSession{id: "keep", title: "ongoing work", history: []byte("still running"), clients: map[chan []byte]bool{}}
160 s.terminals.sessions = map[string]*terminalSession{term.id: term}
161 server := httptest.NewServer(s.handler())
162 defer server.Close()
163 s.origin = server.URL
164 headers := http.Header{"Origin": {server.URL}, "Cookie": {s.cookieName() + "=" + s.session}}
165 ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/api/terminals/keep/stream", headers)
166 if err != nil {
167 t.Fatal(err)
168 }
169 defer ws.Close()
170 var marker struct {
171 Type string `json:"type"`
172 }
173 if err := ws.ReadJSON(&marker); err != nil || marker.Type != "history" {
174 t.Fatalf("history marker: %+v, %v", marker, err)
175 }
176 _, data, err := ws.ReadMessage()
177 if err != nil || string(data) != "still running" {
178 t.Fatal("viewer did not attach", err)
179 }
180 s.account.lock()
181 _ = ws.SetReadDeadline(time.Now().Add(time.Second))
182 if _, _, err = ws.ReadMessage(); err == nil {
183 t.Fatal("locked viewer retained its connection")
184 }
185 term.mu.Lock()
186 defer term.mu.Unlock()
187 if term.closed || string(term.history) != "still running" {
188 t.Fatal("locking destroyed the background terminal")
189 }
190}
191
192func TestLoginRequiresValidPasswordBeforeProtectedAPIs(t *testing.T) {
193 s := testServer(t)
194 a := newTestAccount(t)
195 a.lock()
196 s.account = a
197 w := request(s, "POST", "/api/account/unlock", s.origin, `{"password":"wrong-password"}`, true)
198 if w.Code != 400 {
199 t.Fatal(w.Code)
200 }
201 if w = request(s, "GET", "/api/settings", "", "", true); w.Code != 423 {
202 t.Fatal("wrong password granted access")
203 }
204 a.nextAttempt = time.Time{}
205 w = request(s, "POST", "/api/account/unlock", s.origin, `{"password":"initial-test-password"}`, true)
206 if w.Code != 200 {
207 t.Fatal(w.Code, w.Body.String())
208 }
209 if w = request(s, "GET", "/api/settings", "", "", true); w.Code != 200 {
210 t.Fatal(w.Code)
211 }
212 ctx, ok := a.access()
213 if !ok || ctx.Err() != nil {
214 t.Fatal("unlock did not establish fresh access context")
215 }
216}
217
218func TestLogoutJoinsActiveStopAndLocksOnlyOnSuccess(t *testing.T) {
219 for _, failed := range []bool{false, true} {
220 t.Run(map[bool]string{false: "success", true: "failure"}[failed], func(t *testing.T) {
221 s := testServer(t)
222 started, finish := make(chan struct{}), make(chan struct{})
223 s.launch(httptest.NewRecorder(), "stop", func() error {
224 close(started)
225 <-finish
226 if failed {
227 return errors.New("stop failed")
228 }
229 return nil
230 })
231 <-started
232 w := request(s, "POST", "/api/account/logout", s.origin, "{}", true)
233 if w.Code != 200 {
234 t.Fatal(w.Code, w.Body.String())
235 }
236 if !s.account.view().Unlocked {
237 t.Fatal("logout locked before stop completed")
238 }
239 close(finish)
240 s.op.Lock()
241 defer s.op.Unlock()
242 if s.account.view().Unlocked != failed {
243 t.Fatal("logout did not follow the active stop result")
244 }
245 })
246 }
247}