跳到主要内容

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

浏览文件

server_test.go

335 行 · 8.6 KB历史下载
1package sftp
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "io"
8 "os"
9 "path"
10 "runtime"
11 "sync"
12 "syscall"
13 "testing"
14
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17)
18
19func clientServerPair(t *testing.T) (*Client, *Server) {
20 cr, sw := io.Pipe()
21 sr, cw := io.Pipe()
22 var options []ServerOption
23 if *testAllocator {
24 options = append(options, WithAllocator())
25 }
26 server, err := NewServer(struct {
27 io.Reader
28 io.WriteCloser
29 }{sr, sw}, options...)
30 if err != nil {
31 t.Fatal(err)
32 }
33 go server.Serve()
34 client, err := NewClientPipe(cr, cw)
35 if err != nil {
36 t.Fatalf("%+v\n", err)
37 }
38 return client, server
39}
40
41type sshFxpTestBadExtendedPacket struct {
42 ID uint32
43 Extension string
44 Data string
45}
46
47func (p sshFxpTestBadExtendedPacket) id() uint32 { return p.ID }
48
49func (p sshFxpTestBadExtendedPacket) MarshalBinary() ([]byte, error) {
50 l := 4 + 1 + 4 + // uint32(length) + byte(type) + uint32(id)
51 4 + len(p.Extension) +
52 4 + len(p.Data)
53
54 b := make([]byte, 4, l)
55 b = append(b, sshFxpExtended)
56 b = marshalUint32(b, p.ID)
57 b = marshalString(b, p.Extension)
58 b = marshalString(b, p.Data)
59
60 return b, nil
61}
62
63func checkServerAllocator(t *testing.T, server *Server) {
64 if server.pktMgr.alloc == nil {
65 return
66 }
67 checkAllocatorBeforeServerClose(t, server.pktMgr.alloc)
68 server.Close()
69 checkAllocatorAfterServerClose(t, server.pktMgr.alloc)
70}
71
72// test that errors are sent back when we request an invalid extended packet operation
73// this validates the following rfc draft is followed https://tools.ietf.org/html/draft-ietf-secsh-filexfer-extensions-00
74func TestInvalidExtendedPacket(t *testing.T) {
75 client, server := clientServerPair(t)
76 defer client.Close()
77 defer server.Close()
78
79 badPacket := sshFxpTestBadExtendedPacket{client.nextID(), "thisDoesn'tExist", "foobar"}
80 typ, data, err := client.clientConn.sendPacket(context.Background(), nil, badPacket)
81 if err != nil {
82 t.Fatalf("unexpected error from sendPacket: %s", err)
83 }
84 if typ != sshFxpStatus {
85 t.Fatalf("received non-FPX_STATUS packet: %v", typ)
86 }
87
88 err = unmarshalStatus(badPacket.id(), data)
89 statusErr, ok := err.(*StatusError)
90 if !ok {
91 t.Fatal("failed to convert error from unmarshalStatus to *StatusError")
92 }
93 if statusErr.Code != sshFxOPUnsupported {
94 t.Errorf("statusErr.Code => %d, wanted %d", statusErr.Code, sshFxOPUnsupported)
95 }
96 checkServerAllocator(t, server)
97}
98
99// test that server handles concurrent requests correctly
100func TestConcurrentRequests(t *testing.T) {
101 skipIfWindows(t)
102 var filename string
103 switch runtime.GOOS {
104 case "plan9":
105 filename = "/lib/ndb/local"
106 case "zos":
107 filename = "/etc/.shrc"
108 default:
109 filename = "/etc/passwd"
110 }
111 client, server := clientServerPair(t)
112 defer client.Close()
113 defer server.Close()
114
115 concurrency := 2
116 var wg sync.WaitGroup
117 wg.Add(concurrency)
118
119 for i := 0; i < concurrency; i++ {
120 go func() {
121 defer wg.Done()
122
123 for j := 0; j < 1024; j++ {
124 f, err := client.Open(filename)
125 if err != nil {
126 t.Errorf("failed to open file: %v", err)
127 continue
128 }
129 if err := f.Close(); err != nil {
130 t.Errorf("failed t close file: %v", err)
131 }
132 }
133 }()
134 }
135 wg.Wait()
136 checkServerAllocator(t, server)
137}
138
139// Test error conversion
140func TestStatusFromError(t *testing.T) {
141 type test struct {
142 err error
143 pkt *sshFxpStatusPacket
144 }
145 tpkt := func(id, code uint32) *sshFxpStatusPacket {
146 return &sshFxpStatusPacket{
147 ID: id,
148 StatusError: StatusError{Code: code},
149 }
150 }
151 testCases := []test{
152 {syscall.ENOENT, tpkt(1, sshFxNoSuchFile)},
153 {&os.PathError{Err: syscall.ENOENT},
154 tpkt(2, sshFxNoSuchFile)},
155 {&os.PathError{Err: errors.New("foo")}, tpkt(3, sshFxFailure)},
156 {ErrSSHFxEOF, tpkt(4, sshFxEOF)},
157 {ErrSSHFxOpUnsupported, tpkt(5, sshFxOPUnsupported)},
158 {io.EOF, tpkt(6, sshFxEOF)},
159 {os.ErrNotExist, tpkt(7, sshFxNoSuchFile)},
160 }
161 for _, tc := range testCases {
162 tc.pkt.StatusError.msg = tc.err.Error()
163 assert.Equal(t, tc.pkt, statusFromError(tc.pkt.ID, tc.err))
164 }
165}
166
167// This was written to test a race b/w open immediately followed by a stat.
168// Previous to this the Open would trigger the use of a worker pool, then the
169// stat packet would come in an hit the pool and return faster than the open
170// (returning a file-not-found error).
171// The below by itself wouldn't trigger the race however, I needed to add a
172// small sleep in the openpacket code to trigger the issue. I wanted to add a
173// way to inject that in the code but right now there is no good place for it.
174// I'm thinking after I convert the server into a request-server backend I
175// might be able to do something with the runWorker method passed into the
176// packet manager. But with the 2 implementations fo the server it just doesn't
177// fit well right now.
178func TestOpenStatRace(t *testing.T) {
179 client, server := clientServerPair(t)
180 defer client.Close()
181 defer server.Close()
182
183 // openpacket finishes to fast to trigger race in tests
184 // need to add a small sleep on server to openpackets somehow
185 tmppath := path.Join(os.TempDir(), "stat_race")
186 pflags := toPflags(os.O_RDWR | os.O_CREATE | os.O_TRUNC)
187 ch := make(chan result, 3)
188 id1 := client.nextID()
189 id2 := client.nextID()
190 client.dispatchRequest(ch, &sshFxpOpenPacket{
191 ID: id1,
192 Path: tmppath,
193 Pflags: pflags,
194 })
195 client.dispatchRequest(ch, &sshFxpLstatPacket{
196 ID: id2,
197 Path: tmppath,
198 })
199 testreply := func(id uint32) {
200 r := <-ch
201 require.NoError(t, r.err)
202 switch r.typ {
203 case sshFxpAttrs, sshFxpHandle: // ignore
204 case sshFxpStatus:
205 err := normaliseError(unmarshalStatus(id, r.data))
206 assert.NoError(t, err, "race hit, stat before open")
207 default:
208 t.Fatal("unexpected type:", r.typ)
209 }
210 }
211 testreply(id1)
212 testreply(id2)
213 os.Remove(tmppath)
214 checkServerAllocator(t, server)
215}
216
217func TestOpenWithPermissions(t *testing.T) {
218 ctx, cancel := context.WithCancel(context.Background())
219 defer cancel()
220
221 skipIfWindows(t)
222
223 client, server := clientServerPair(t)
224 defer client.Close()
225 defer server.Close()
226
227 tmppath := path.Join(os.TempDir(), "open_permissions")
228 defer os.Remove(tmppath)
229
230 pflags := toPflags(os.O_RDWR | os.O_CREATE | os.O_TRUNC)
231
232 id1 := client.nextID()
233 id2 := client.nextID()
234
235 typ, data, err := client.sendPacket(ctx, nil, &sshFxpOpenPacket{
236 ID: id1,
237 Path: tmppath,
238 Pflags: pflags,
239 Flags: sshFileXferAttrPermissions,
240 Attrs: &FileStat{
241 Mode: 0o745,
242 },
243 })
244 if err != nil {
245 t.Fatal("unexpected error:", err)
246 }
247 switch typ {
248 case sshFxpHandle:
249 // do nothing, we can just leave the handle open.
250 case sshFxpStatus:
251 t.Fatal("unexpected status:", normaliseError(unmarshalStatus(id1, data)))
252 default:
253 t.Fatal("unpexpected packet type:", unimplementedPacketErr(typ))
254 }
255
256 stat, err := os.Stat(tmppath)
257 if err != nil {
258 t.Fatal("unexpected error:", err)
259 }
260
261 if stat.Mode()&os.ModePerm != 0o745 {
262 t.Errorf("stat.Mode() = %v was expecting 0o745", stat.Mode())
263 }
264
265 // Existing files should not have their permissions changed.
266 typ, data, err = client.sendPacket(ctx, nil, &sshFxpOpenPacket{
267 ID: id2,
268 Path: tmppath,
269 Pflags: pflags,
270 Flags: sshFileXferAttrPermissions,
271 Attrs: &FileStat{
272 Mode: 0o755,
273 },
274 })
275 if err != nil {
276 t.Fatal("unexpected error:", err)
277 }
278 switch typ {
279 case sshFxpHandle:
280 // do nothing, we can just leave the handle open.
281 case sshFxpStatus:
282 t.Fatal("unexpected status:", normaliseError(unmarshalStatus(id2, data)))
283 default:
284 t.Fatal("unpexpected packet type:", unimplementedPacketErr(typ))
285 }
286
287 if stat.Mode()&os.ModePerm != 0o745 {
288 t.Errorf("stat.Mode() = %v, was expecting unchanged 0o745", stat.Mode())
289 }
290
291 checkServerAllocator(t, server)
292}
293
294// Ensure that proper error codes are returned for non existent files, such
295// that they are mapped back to a 'not exists' error on the client side.
296func TestStatNonExistent(t *testing.T) {
297 client, server := clientServerPair(t)
298 defer client.Close()
299 defer server.Close()
300
301 for _, file := range []string{"/doesnotexist", "/doesnotexist/a/b"} {
302 _, err := client.Stat(file)
303 if !os.IsNotExist(err) {
304 t.Errorf("expected 'does not exist' err for file %q. got: %v", file, err)
305 }
306 }
307}
308
309func TestServerWithBrokenClient(t *testing.T) {
310 validInit := sp(&sshFxInitPacket{Version: 3})
311 brokenOpen := sp(&sshFxpOpenPacket{Path: "foo"})
312 brokenOpen = brokenOpen[:len(brokenOpen)-2]
313
314 for _, clientInput := range [][]byte{
315 // Packet length zero (never valid). This used to crash the server.
316 {0, 0, 0, 0},
317 append(validInit, 0, 0, 0, 0),
318
319 // Client hangs up mid-packet.
320 append(validInit, brokenOpen...),
321 } {
322 srv, err := NewServer(struct {
323 io.Reader
324 io.WriteCloser
325 }{
326 bytes.NewReader(clientInput),
327 &sink{},
328 })
329 require.NoError(t, err)
330
331 err = srv.Serve()
332 assert.Error(t, err)
333 srv.Close()
334 }
335}