跳到主要内容

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

浏览文件

connector_test.go

588 行 · 17.8 KB历史下载
1package remotehost
2
3import (
4 "context"
5 "crypto/ecdsa"
6 "crypto/ed25519"
7 "crypto/elliptic"
8 "crypto/rand"
9 "crypto/rsa"
10 "crypto/x509"
11 "encoding/json"
12 "encoding/pem"
13 "errors"
14 "fmt"
15 "io"
16 "net"
17 "net/http"
18 "net/http/httptest"
19 "net/http/httputil"
20 "net/url"
21 "os"
22 "os/exec"
23 "path/filepath"
24 "runtime"
25 "strconv"
26 "strings"
27 "sync"
28 "sync/atomic"
29 "testing"
30 "time"
31
32 "github.com/gorilla/websocket"
33 "golang.org/x/crypto/ssh"
34)
35
36type sshFixture struct {
37 profile HostProfile
38 manifest ServerManifest
39 commands chan string
40 connections sync.Map
41 listener net.Listener
42 forwardCount atomic.Int64
43}
44
45func newFixture(t *testing.T, handler http.Handler, extraHostKeys ...ssh.Signer) *sshFixture {
46 t.Helper()
47 httpServer := httptest.NewServer(handler)
48 t.Cleanup(httpServer.Close)
49 _, hostPrivate, _ := ed25519.GenerateKey(rand.Reader)
50 hostSigner, _ := ssh.NewSignerFromKey(hostPrivate)
51 _, clientPrivate, _ := ed25519.GenerateKey(rand.Reader)
52 clientSigner, _ := ssh.NewSignerFromKey(clientPrivate)
53 keyBytes, _ := x509.MarshalPKCS8PrivateKey(clientPrivate)
54 keyPath := filepath.Join(t.TempDir(), "identity")
55 if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}), 0600); err != nil {
56 t.Fatal(err)
57 }
58 listener, err := net.Listen("tcp4", "127.0.0.1:0")
59 if err != nil {
60 t.Fatal(err)
61 }
62 f := &sshFixture{listener: listener, commands: make(chan string, 8), manifest: ServerManifest{APIProtocol: 1, InstanceID: strings.Repeat("a", 64), Version: "test", Platform: "linux", Runtime: "container", Origin: httpServer.URL, Ticket: strings.Repeat("t", 64), Capabilities: map[string]bool{"terminal": true}}}
63 f.profile = HostProfile{ID: newID(), Name: "fixture", Host: "127.0.0.1", Port: listener.Addr().(*net.TCPAddr).Port, User: "cage", Auth: AuthConfig{Kind: "key_file", IdentityFile: keyPath}, HostKey: &HostKey{Algorithm: hostSigner.PublicKey().Type(), Fingerprint: ssh.FingerprintSHA256(hostSigner.PublicKey())}}
64 config := &ssh.ServerConfig{PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
65 if string(key.Marshal()) != string(clientSigner.PublicKey().Marshal()) {
66 return nil, errors.New("wrong key")
67 }
68 return nil, nil
69 }}
70 config.AddHostKey(hostSigner)
71 for _, key := range extraHostKeys {
72 config.AddHostKey(key)
73 }
74 go func() {
75 for {
76 conn, err := listener.Accept()
77 if err != nil {
78 return
79 }
80 f.connections.Store(conn, true)
81 go func() {
82 defer f.connections.Delete(conn)
83 defer conn.Close()
84 server, channels, requests, err := ssh.NewServerConn(conn, config)
85 if err != nil {
86 return
87 }
88 defer server.Close()
89 go ssh.DiscardRequests(requests)
90 for channel := range channels {
91 go f.channel(channel)
92 }
93 }()
94 }
95 }()
96 t.Cleanup(func() {
97 listener.Close()
98 f.connections.Range(func(key, value any) bool { key.(net.Conn).Close(); return true })
99 })
100 return f
101}
102
103func (f *sshFixture) channel(in ssh.NewChannel) {
104 switch in.ChannelType() {
105 case "session":
106 channel, requests, err := in.Accept()
107 if err != nil {
108 return
109 }
110 defer channel.Close()
111 for request := range requests {
112 if request.Type != "exec" {
113 request.Reply(false, nil)
114 continue
115 }
116 var command struct{ Command string }
117 ssh.Unmarshal(request.Payload, &command)
118 f.commands <- command.Command
119 request.Reply(true, nil)
120 json.NewEncoder(channel).Encode(f.manifest)
121 channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Code uint32 }{0}))
122 return
123 }
124 case "direct-tcpip":
125 var forward struct {
126 Host string
127 Port uint32
128 Origin string
129 OriginPort uint32
130 }
131 if ssh.Unmarshal(in.ExtraData(), &forward) != nil {
132 in.Reject(ssh.Prohibited, "invalid")
133 return
134 }
135 u, _ := url.Parse(f.manifest.Origin)
136 port, _ := strconv.Atoi(u.Port())
137 if forward.Host != "127.0.0.1" || int(forward.Port) != port {
138 in.Reject(ssh.Prohibited, "wrong destination")
139 return
140 }
141 peer, err := net.Dial("tcp", net.JoinHostPort(forward.Host, strconv.Itoa(int(forward.Port))))
142 if err != nil {
143 in.Reject(ssh.ConnectionFailed, "dial")
144 return
145 }
146 defer peer.Close()
147 channel, requests, err := in.Accept()
148 if err != nil {
149 return
150 }
151 defer channel.Close()
152 f.forwardCount.Add(1)
153 go ssh.DiscardRequests(requests)
154 done := make(chan struct{})
155 go func() { io.Copy(peer, channel); peer.Close(); close(done) }()
156 io.Copy(channel, peer)
157 channel.Close()
158 <-done
159 default:
160 in.Reject(ssh.UnknownChannelType, "unsupported")
161 }
162}
163
164func fixtureHandler(t *testing.T, next http.Handler) http.Handler {
165 t.Helper()
166 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
167 if r.Header.Get("Origin") != "http://"+r.Host {
168 http.Error(w, "origin", 403)
169 return
170 }
171 if r.URL.Path == "/api/session" {
172 var body struct{ Token string }
173 json.NewDecoder(r.Body).Decode(&body)
174 if body.Token != strings.Repeat("t", 64) {
175 http.Error(w, "ticket", 401)
176 return
177 }
178 http.SetCookie(w, &http.Cookie{Name: "remote_session", Value: "private-cookie", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode})
179 io.WriteString(w, `{"ok":true}`)
180 return
181 }
182 cookie, err := r.Cookie("remote_session")
183 if err != nil || cookie.Value != "private-cookie" || r.Header.Get("Authorization") != "" || strings.Contains(r.Header.Get("Cookie"), "local-secret") {
184 http.Error(w, "auth", 401)
185 return
186 }
187 next.ServeHTTP(w, r)
188 })
189}
190
191func connectFixture(t *testing.T, f *sshFixture) *Session {
192 t.Helper()
193 s, err := connect(context.Background(), f.profile, ConnectSecrets{}, func(string) {})
194 if err != nil {
195 t.Fatal(err)
196 }
197 t.Cleanup(func() { s.Close() })
198 return s
199}
200
201func TestSSHSessionHTTPWebSocketSSEAndCancellation(t *testing.T) {
202 sseEnded := make(chan struct{})
203 f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
204 switch r.URL.Path {
205 case "/check":
206 io.WriteString(w, "authenticated")
207 case "/stream":
208 w.Header().Set("Content-Type", "text/event-stream")
209 io.WriteString(w, "data: ready\n\n")
210 w.(http.Flusher).Flush()
211 <-r.Context().Done()
212 close(sseEnded)
213 case "/ws":
214 connection, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "http://"+r.Host }}).Upgrade(w, r, nil)
215 if err != nil {
216 return
217 }
218 defer connection.Close()
219 kind, data, err := connection.ReadMessage()
220 if err == nil {
221 connection.WriteMessage(kind, data)
222 }
223 default:
224 http.NotFound(w, r)
225 }
226 })))
227 s := connectFixture(t, f)
228 if command := <-f.commands; command != "exec 'cage' server-entry --json" {
229 t.Fatalf("command = %q", command)
230 }
231 req, _ := http.NewRequest("GET", s.Origin+"/check", nil)
232 req.Header.Set("Cookie", "local=local-secret")
233 req.Header.Set("Authorization", "Bearer local-secret")
234 response, err := s.Client.Do(req)
235 if err != nil {
236 t.Fatal(err)
237 }
238 body, _ := io.ReadAll(response.Body)
239 response.Body.Close()
240 if string(body) != "authenticated" {
241 t.Fatalf("HTTP = %d %q", response.StatusCode, body)
242 }
243 u, _ := url.Parse(s.Origin)
244 proxy := httputil.NewSingleHostReverseProxy(u)
245 proxy.Transport = s.Transport
246 gateway := httptest.NewServer(proxy)
247 defer gateway.Close()
248 ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(gateway.URL, "http")+"/ws", nil)
249 if err != nil {
250 t.Fatal(err)
251 }
252 defer ws.Close()
253 if err = ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
254 t.Fatal(err)
255 }
256 _, message, err := ws.ReadMessage()
257 if err != nil || string(message) != "hello" {
258 t.Fatalf("websocket: %q %v", message, err)
259 }
260 stream, err := s.Client.Get(s.Origin + "/stream")
261 if err != nil {
262 t.Fatal(err)
263 }
264 first := make([]byte, len("data: ready\n\n"))
265 if _, err = io.ReadFull(stream.Body, first); err != nil {
266 t.Fatal(err)
267 }
268 s.Close()
269 stream.Body.Close()
270 select {
271 case <-sseEnded:
272 case <-time.After(3 * time.Second):
273 t.Fatal("SSE remained open after disconnect")
274 }
275 if _, err = s.Client.Get(s.Origin + "/check"); err == nil {
276 t.Fatal("closed session accepted request")
277 }
278}
279
280func TestHostKeyRequiresExplicitMatchingPin(t *testing.T) {
281 f := newFixture(t, fixtureHandler(t, http.NotFoundHandler()))
282 for _, code := range []string{"host_key_unknown", "host_key_changed"} {
283 p := f.profile
284 if code == "host_key_unknown" {
285 p.HostKey = nil
286 } else {
287 p.HostKey = &HostKey{Algorithm: p.HostKey.Algorithm, Fingerprint: "SHA256:" + strings.Repeat("A", 43)}
288 }
289 _, err := connect(context.Background(), p, ConnectSecrets{}, func(string) {})
290 var structured *Error
291 if !errors.As(err, &structured) || structured.Code != code || structured.HostKey == nil || structured.HostKey.Fingerprint != f.profile.HostKey.Fingerprint {
292 t.Fatalf("%s: %#v", code, err)
293 }
294 }
295 if f.forwardCount.Load() != 0 {
296 t.Fatal("untrusted host reached HTTP service")
297 }
298}
299
300func TestPinnedHostKeySelectsMatchingAlgorithmOnMultiKeyServer(t *testing.T) {
301 ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
302 if err != nil {
303 t.Fatal(err)
304 }
305 ecdsaSigner, err := ssh.NewSignerFromKey(ecdsaKey)
306 if err != nil {
307 t.Fatal(err)
308 }
309 rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
310 if err != nil {
311 t.Fatal(err)
312 }
313 rsaSigner, err := ssh.NewSignerFromKey(rsaKey)
314 if err != nil {
315 t.Fatal(err)
316 }
317 f := newFixture(t, fixtureHandler(t, http.NotFoundHandler()), ecdsaSigner, rsaSigner)
318 // The stored ED25519 key must win even if the client's default preference
319 // would negotiate the server's ECDSA key first.
320 connectFixture(t, f).Close()
321 // RSA's public key type differs from its SHA-2 signature algorithm names.
322 f.profile.HostKey = &HostKey{Algorithm: ssh.KeyAlgoRSA, Fingerprint: ssh.FingerprintSHA256(rsaSigner.PublicKey())}
323 connectFixture(t, f).Close()
324}
325
326func TestOriginRedirectAndMutationReplayRefused(t *testing.T) {
327 var mutations atomic.Int64
328 f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
329 if r.URL.Path == "/redirect" {
330 http.Redirect(w, r, "http://public.example/private", 302)
331 return
332 }
333 if r.URL.Path == "/mutation" {
334 mutations.Add(1)
335 conn, _, _ := w.(http.Hijacker).Hijack()
336 conn.Close()
337 return
338 }
339 io.WriteString(w, "ok")
340 })))
341 s := connectFixture(t, f)
342 if _, err := s.Client.Get("http://public.example/check"); err == nil {
343 t.Fatal("arbitrary destination accepted")
344 }
345 if _, err := s.Client.Get(s.Origin + "/redirect"); err == nil {
346 t.Fatal("redirect accepted")
347 }
348 req, _ := http.NewRequest("POST", s.Origin+"/mutation", strings.NewReader("operation"))
349 req.Header.Set("Idempotency-Key", "do-not-replay")
350 if _, err := s.Client.Do(req); err == nil {
351 t.Fatal("missing mutation response accepted")
352 }
353 if mutations.Load() != 1 {
354 t.Fatalf("mutation count = %d", mutations.Load())
355 }
356}
357
358func TestServerEntryCommandQuotesPaths(t *testing.T) {
359 if runtime.GOOS == "windows" {
360 t.Skip("POSIX server command is executed by the remote Linux shell")
361 }
362 dir := t.TempDir()
363 executable := filepath.Join(dir, "cage ' literal")
364 if err := os.WriteFile(executable, []byte("#!/bin/sh\nprintf '%s\\n%s\\n%s\\n' \"$CLAUDE_CAGE_CONFIG\" \"$1\" \"$2\"\n"), 0700); err != nil {
365 t.Fatal(err)
366 }
367 p := HostProfile{Name: "test", Host: "localhost", User: "user", Auth: AuthConfig{Kind: "agent"}, Executable: executable, ConfigPath: filepath.Join(dir, "a'$(touch injected).json")}
368 command, err := ServerEntryCommand(p)
369 if err != nil {
370 t.Fatal(err)
371 }
372 cmd := exec.Command("sh", "-c", command)
373 cmd.Dir = dir
374 output, err := cmd.Output()
375 if err != nil {
376 t.Fatal(err)
377 }
378 if string(output) != p.ConfigPath+"\nserver-entry\n--json\n" {
379 t.Fatalf("command output = %q", output)
380 }
381 if _, err = os.Stat(filepath.Join(dir, "injected")); !os.IsNotExist(err) {
382 t.Fatal("shell substitution executed")
383 }
384}
385
386func TestManifestRejectsRemoteTargets(t *testing.T) {
387 manifest := ServerManifest{APIProtocol: 1, InstanceID: strings.Repeat("a", 64), Platform: "linux", Runtime: "container", Origin: "http://localhost:17800", Ticket: strings.Repeat("t", 64)}
388 for _, origin := range []string{"https://localhost:17800", "http://example.com:80", "http://127.0.0.1:17800/path", "http://user@localhost:17800", "http://localhost:17800?x=1", "http://localhost:17800#x", "http://localhost"} {
389 manifest.Origin = origin
390 if ValidateManifest(manifest) == nil {
391 t.Errorf("accepted %s", origin)
392 }
393 }
394 manifest.Origin = "http://localhost:17800"
395 if err := ValidateManifest(manifest); err != nil {
396 t.Fatal(err)
397 }
398 manifest.APIProtocol = 2
399 if err := ValidateManifest(manifest); err == nil {
400 t.Fatal("accepted unknown protocol")
401 }
402 manifest.APIProtocol = APIProtocol
403 manifest.InstanceID = newID()
404 if err := ValidateManifest(manifest); err == nil {
405 t.Fatal("accepted an instance identity that cannot be used by file and account consumers")
406 }
407}
408
409func waitState(t *testing.T, m *Manager, want string) ConnectionState {
410 t.Helper()
411 deadline := time.Now().Add(5 * time.Second)
412 for time.Now().Before(deadline) {
413 state := m.Snapshot()
414 if state.State == want {
415 return state
416 }
417 if state.State == "failed" && want != "failed" {
418 t.Fatalf("connection failed: %+v", state)
419 }
420 time.Sleep(time.Millisecond * 5)
421 }
422 t.Fatalf("state never became %s: %+v", want, m.Snapshot())
423 return ConnectionState{}
424}
425
426func TestManagerGenerationAndDisconnectDoNotStopServer(t *testing.T) {
427 var stopCalls atomic.Int64
428 f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
429 if strings.Contains(r.URL.Path, "stop") || strings.Contains(r.URL.Path, "suspend") {
430 stopCalls.Add(1)
431 }
432 io.WriteString(w, "ok")
433 })))
434 store := NewStore(t.TempDir())
435 p := f.profile
436 p.ID = ""
437 p, err := store.Upsert(p)
438 if err != nil {
439 t.Fatal(err)
440 }
441 m := NewManager(store)
442 defer m.Close()
443 first, err := m.Connect(p.ID, ConnectSecrets{})
444 if err != nil {
445 t.Fatal(err)
446 }
447 waitState(t, m, "connected")
448 old, err := m.Acquire(first.ConnectionID)
449 if err != nil {
450 t.Fatal(err)
451 }
452 if err = m.Disconnect(first.ConnectionID); err != nil {
453 t.Fatal(err)
454 }
455 select {
456 case <-old.Context.Done():
457 case <-time.After(time.Second):
458 t.Fatal("connection not cancelled")
459 }
460 second, err := m.Connect(p.ID, ConnectSecrets{})
461 if err != nil {
462 t.Fatal(err)
463 }
464 state := waitState(t, m, "connected")
465 if second.ConnectionID == first.ConnectionID || state.InstanceID != f.manifest.InstanceID {
466 t.Fatal("incorrect identity lifecycle")
467 }
468 if _, err = m.Acquire(first.ConnectionID); err == nil {
469 t.Fatal("obsolete connection acquired")
470 }
471 if err = m.Disconnect(first.ConnectionID); err == nil {
472 t.Fatal("old generation disconnected new connection")
473 }
474 if _, err = m.Acquire(second.ConnectionID); err != nil {
475 t.Fatal(err)
476 }
477 if stopCalls.Load() != 0 {
478 t.Fatal("disconnect stopped remote environment")
479 }
480 encoded, _ := json.Marshal(state)
481 if strings.Contains(string(encoded), strings.Repeat("t", 64)) || strings.Contains(string(encoded), "private-cookie") {
482 t.Fatal("connection secrets leaked into state")
483 }
484 f.connections.Range(func(key, value any) bool { key.(net.Conn).Close(); return true })
485 waitState(t, m, "failed")
486}
487
488func TestExpiredHTTPServerSessionInvalidatesLiveSSHConnectionWithoutReplay(t *testing.T) {
489 var expired atomic.Bool
490 var requests atomic.Int64
491 f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
492 requests.Add(1)
493 if expired.Load() {
494 http.Error(w, "expired server cookie", http.StatusUnauthorized)
495 return
496 }
497 io.WriteString(w, "ok")
498 })))
499 store := NewStore(t.TempDir())
500 p := f.profile
501 p.ID = ""
502 p, err := store.Upsert(p)
503 if err != nil {
504 t.Fatal(err)
505 }
506 manager := NewManager(store)
507 defer manager.Close()
508 state, err := manager.Connect(p.ID, ConnectSecrets{})
509 if err != nil {
510 t.Fatal(err)
511 }
512 waitState(t, manager, "connected")
513 session, err := manager.Acquire(state.ConnectionID)
514 if err != nil {
515 t.Fatal(err)
516 }
517 response, err := session.Client.Get(session.Origin + "/ready")
518 if err != nil {
519 t.Fatal(err)
520 }
521 response.Body.Close()
522 if session.Context.Err() != nil {
523 t.Fatal("SSH session was already closed before server expiry")
524 }
525 expired.Store(true)
526 before := requests.Load()
527 request, _ := http.NewRequest("POST", session.Origin+"/mutation", strings.NewReader(`{"operation":"start"}`))
528 _, err = session.Client.Do(request)
529 var structured *Error
530 if !errors.As(err, &structured) || structured.Code != "remote_session_expired" {
531 t.Fatalf("session expiry = %v", err)
532 }
533 failed := waitState(t, manager, "failed")
534 if failed.Message != "远程连接已中断,请重新连接并核对云端任务" {
535 t.Fatalf("misleading recovery message: %s", failed.Message)
536 }
537 if requests.Load() != before+1 {
538 t.Fatal("request was replayed after server session expiry")
539 }
540 if _, err := manager.Acquire(state.ConnectionID); err == nil {
541 t.Fatal("expired session remained available")
542 }
543}
544
545func TestStorePreservesIndependentUpdatesAndRejectsUnsafeFiles(t *testing.T) {
546 dir := t.TempDir()
547 var group sync.WaitGroup
548 errs := make(chan error, 12)
549 for i := 0; i < 12; i++ {
550 group.Add(1)
551 go func(i int) {
552 defer group.Done()
553 _, err := NewStore(dir).Upsert(HostProfile{Name: fmt.Sprint(i), Host: "localhost", User: "cage", Auth: AuthConfig{Kind: "agent"}})
554 errs <- err
555 }(i)
556 }
557 group.Wait()
558 close(errs)
559 for err := range errs {
560 if err != nil {
561 t.Fatal(err)
562 }
563 }
564 profiles, err := NewStore(dir).List()
565 if err != nil || len(profiles) != 12 {
566 t.Fatalf("profiles=%d err=%v", len(profiles), err)
567 }
568 if err = NewStore(dir).Delete(profiles[0].ID); err != nil {
569 t.Fatal(err)
570 }
571 if _, err = NewStore(dir).Get(profiles[0].ID); err == nil {
572 t.Fatal("deleted host retained")
573 }
574 if runtime.GOOS != "windows" {
575 if err = os.Chmod(filepath.Join(dir, "remote-hosts.json"), 0644); err != nil {
576 t.Fatal(err)
577 }
578 if _, err = NewStore(dir).List(); err == nil {
579 t.Fatal("world-readable configuration accepted")
580 }
581 }
582 other := t.TempDir()
583 if err = os.Symlink(filepath.Join(dir, "remote-hosts.json"), filepath.Join(other, "remote-hosts.json")); err == nil {
584 if _, err = NewStore(other).List(); err == nil {
585 t.Fatal("symlink config accepted")
586 }
587 }
588}