跳到主要内容

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

浏览文件

server_test.go

257 行 · 7.5 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package portfwdserver
5
6import (
7 "bytes"
8 "context"
9 "io"
10 "net"
11 "testing"
12 "time"
13
14 "gotest.tools/v3/assert"
15
16 "github.com/lima-vm/lima/v2/pkg/guestagent/api"
17)
18
19// recvOnlyTunnelServer implements only Recv of the bidi stream; the other
20// methods are never called by GRPCServerRW.Read.
21type recvOnlyTunnelServer struct {
22 api.GuestService_TunnelServer
23 msgs []*api.TunnelMessage
24}
25
26func (s *recvOnlyTunnelServer) Recv() (*api.TunnelMessage, error) {
27 if len(s.msgs) == 0 {
28 return nil, io.EOF
29 }
30 msg := s.msgs[0]
31 s.msgs = s.msgs[1:]
32 return msg, nil
33}
34
35func TestGRPCServerRWReadShortBuffer(t *testing.T) {
36 payload := bytes.Repeat([]byte("x"), 100)
37 rw := &GRPCServerRW{stream: &recvOnlyTunnelServer{msgs: []*api.TunnelMessage{{Data: payload}}}}
38
39 var got []byte
40 buf := make([]byte, 10)
41 for len(got) < len(payload) {
42 n, err := rw.Read(buf)
43 assert.NilError(t, err)
44 assert.Assert(t, n <= len(buf), "Read returned %d, larger than the %d-byte buffer", n, len(buf))
45 got = append(got, buf[:n]...)
46 }
47 assert.DeepEqual(t, got, payload)
48}
49
50// TestGRPCServerRWCloseNeverBlocks reproduces the teardown sequence of
51// tcpproxy.DialProxy.HandleConn: each copy direction calls CloseRead or
52// CloseWrite, and HandleConn itself calls Close, while Start receives from
53// closeCh only once. None of the calls may block; a blocked Close used to
54// keep HandleConn from closing the dialed guest connection, leaking one FD
55// per forwarded connection (https://github.com/lima-vm/lima/issues/5210).
56func TestGRPCServerRWCloseNeverBlocks(t *testing.T) {
57 rw := &GRPCServerRW{closeCh: make(chan any)}
58 done := make(chan struct{})
59 go func() {
60 _ = rw.CloseWrite()
61 _ = rw.CloseRead()
62 _ = rw.Close()
63 _ = rw.Close() // ctx.Done goroutine in Start may call Close again
64 close(done)
65 }()
66 select {
67 case <-rw.closeCh:
68 case <-time.After(5 * time.Second):
69 assert.Assert(t, false, "closeCh was never signaled")
70 }
71 select {
72 case <-done:
73 case <-time.After(5 * time.Second):
74 assert.Assert(t, false, "Close/CloseRead/CloseWrite blocked")
75 }
76}
77
78// fakeTunnelStream is a minimal bidi stream: Recv returns queued messages
79// and io.EOF once recvCh is closed; Send forwards the payload to sendCh, or
80// discards it when sendCh is nil.
81type fakeTunnelStream struct {
82 api.GuestService_TunnelServer
83 ctx context.Context
84 recvCh chan *api.TunnelMessage
85 sendCh chan []byte
86}
87
88func (s *fakeTunnelStream) Context() context.Context { return s.ctx }
89
90func (s *fakeTunnelStream) Recv() (*api.TunnelMessage, error) {
91 msg, ok := <-s.recvCh
92 if !ok {
93 return nil, io.EOF
94 }
95 return msg, nil
96}
97
98func (s *fakeTunnelStream) Send(msg *api.TunnelMessage) error {
99 if s.sendCh != nil {
100 s.sendCh <- msg.Data
101 }
102 return nil
103}
104
105// TestTunnelServerRelaysHalfClose verifies that a half-close from the host is
106// relayed to the guest service as a FIN without tearing the tunnel down, so a
107// response written after the half-close still reaches the host
108// (https://github.com/lima-vm/lima/issues/5264).
109//
110// A host-side half-close arrives as Recv returning io.EOF while the stream
111// context stays live; only a full close cancels the context as well.
112func TestTunnelServerRelaysHalfClose(t *testing.T) {
113 var lc net.ListenConfig
114 ln, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
115 assert.NilError(t, err)
116 defer ln.Close()
117
118 // The guest service reads the whole request, which completes only once the
119 // half-close reaches it, and replies after the test releases replyCh. The
120 // handshake stands in for a server that takes time to produce a response.
121 reqCh := make(chan []byte, 1)
122 errCh := make(chan error, 1)
123 replyCh := make(chan struct{})
124 go func() {
125 conn, err := ln.Accept()
126 if err != nil {
127 errCh <- err
128 return
129 }
130 defer conn.Close()
131 req, err := io.ReadAll(conn)
132 if err != nil {
133 errCh <- err
134 return
135 }
136 reqCh <- req
137 <-replyCh
138 _, err = conn.Write([]byte("response"))
139 errCh <- err
140 }()
141
142 recvCh := make(chan *api.TunnelMessage, 2)
143 recvCh <- &api.TunnelMessage{Id: "test", Protocol: "tcp", GuestAddr: ln.Addr().String()}
144 recvCh <- &api.TunnelMessage{Id: "test", Data: []byte("request")}
145 sendCh := make(chan []byte, 1)
146 stream := &fakeTunnelStream{ctx: t.Context(), recvCh: recvCh, sendCh: sendCh}
147
148 startDone := make(chan error, 1)
149 go func() {
150 startDone <- NewTunnelServer().Start(stream)
151 }()
152
153 // Half-close: the host has nothing more to send, but is still waiting for
154 // the response.
155 close(recvCh)
156
157 select {
158 case req := <-reqCh:
159 assert.DeepEqual(t, req, []byte("request"))
160 case err := <-errCh:
161 assert.NilError(t, err)
162 case <-time.After(5 * time.Second):
163 assert.Assert(t, false, "guest service never saw the half-close")
164 }
165
166 close(replyCh)
167 assert.NilError(t, <-errCh)
168
169 select {
170 case data := <-sendCh:
171 assert.DeepEqual(t, data, []byte("response"))
172 case <-time.After(5 * time.Second):
173 assert.Assert(t, false, "response was lost; the half-close tore the tunnel down")
174 }
175
176 select {
177 case err := <-startDone:
178 assert.NilError(t, err)
179 case <-time.After(5 * time.Second):
180 assert.Assert(t, false, "Start did not return after the guest service closed")
181 }
182}
183
184// TestTunnelServerClosesGuestConn verifies that the connection dialed to the
185// guest service is fully closed (not just shut down for writing) when the
186// tunnel stream ends (https://github.com/lima-vm/lima/issues/5210).
187func TestTunnelServerClosesGuestConn(t *testing.T) {
188 var lc net.ListenConfig
189 ln, err := lc.Listen(t.Context(), "tcp", "127.0.0.1:0")
190 assert.NilError(t, err)
191 defer ln.Close()
192
193 acceptCh := make(chan net.Conn, 1)
194 go func() {
195 conn, err := ln.Accept()
196 if err == nil {
197 acceptCh <- conn
198 }
199 }()
200
201 ctx, cancel := context.WithCancel(t.Context())
202 defer cancel()
203 recvCh := make(chan *api.TunnelMessage, 2)
204 recvCh <- &api.TunnelMessage{Id: "test", Protocol: "tcp", GuestAddr: ln.Addr().String()}
205 recvCh <- &api.TunnelMessage{Id: "test", Data: []byte("x")}
206 stream := &fakeTunnelStream{ctx: ctx, recvCh: recvCh}
207
208 startDone := make(chan error, 1)
209 go func() {
210 startDone <- NewTunnelServer().Start(stream)
211 }()
212
213 var guestConn net.Conn
214 select {
215 case guestConn = <-acceptCh:
216 case <-time.After(5 * time.Second):
217 assert.Assert(t, false, "tunnel server did not dial the guest address")
218 }
219 defer guestConn.Close()
220
221 // Wait for the tunnel to relay a byte before cancelling. Accept returns as
222 // soon as the kernel completes the handshake, which can happen before
223 // DialContext returns inside Start, and cancelling in that window makes the
224 // dial itself fail instead of exercising the teardown.
225 assert.NilError(t, guestConn.SetReadDeadline(time.Now().Add(5*time.Second)))
226 buf := make([]byte, 1)
227 _, err = io.ReadFull(guestConn, buf)
228 assert.NilError(t, err)
229 assert.NilError(t, guestConn.SetReadDeadline(time.Time{}))
230
231 // Simulate the host closing the tunnel: GrpcClientRW.Close both stops
232 // sending and cancels the stream context. Closing recvCh alone would only
233 // be a half-close, which must keep the tunnel up.
234 close(recvCh)
235 cancel()
236
237 select {
238 case err := <-startDone:
239 assert.NilError(t, err)
240 case <-time.After(5 * time.Second):
241 assert.Assert(t, false, "Start did not return after the stream ended")
242 }
243
244 // If the tunnel server fully closed its side, writes from the guest
245 // service eventually fail (RST). With a leaked FD they succeed forever.
246 deadline := time.After(5 * time.Second)
247 for {
248 if _, err := guestConn.Write([]byte("x")); err != nil {
249 return
250 }
251 select {
252 case <-deadline:
253 assert.Assert(t, false, "guest connection still writable; FD was not closed")
254 case <-time.After(10 * time.Millisecond):
255 }
256 }
257}