Skip to content
File

Blob: tun/server/server_test.go

go342 lines
1package server
2 
3import (
4 "bytes"
5 "context"
6 "fmt"
7 "testing"
8 "time"
9 
10 "go.miragespace.co/specter/spec/chord"
11 mocks "go.miragespace.co/specter/spec/mocks"
12 "go.miragespace.co/specter/spec/protocol"
13 "go.miragespace.co/specter/spec/rpc"
14 "go.miragespace.co/specter/spec/transport"
15 "go.miragespace.co/specter/spec/tun"
16 "go.miragespace.co/specter/util/bufconn"
17 
18 "github.com/stretchr/testify/mock"
19 "github.com/stretchr/testify/require"
20 "go.uber.org/zap"
21 "go.uber.org/zap/zaptest"
22)
23 
24const (
25 testRootDomain = "hello.com"
26 testAcmeZone = "acme.example.com"
27)
28 
29func assertBytes(got []byte, exp ...[]byte) bool {
30 for _, b := range exp {
31 r := bytes.Compare(got, b)
32 if r == 0 {
33 return true
34 }
35 }
36 return false
37}
38 
39type configOption func(*Config)
40 
41func withResolver(r tun.DNSResolver) configOption {
42 return func(c *Config) {
43 c.Resolver = r
44 }
45}
46 
47func getFixture(t *testing.T, as *require.Assertions, options ...configOption) (*zap.Logger, *mocks.VNode, *mocks.Transport, *mocks.Transport, *Server) {
48 logger := zaptest.NewLogger(t, zaptest.WrapOptions(zap.AddCaller()))
49 
50 n := new(mocks.VNode)
51 cht := new(mocks.Transport)
52 clt := new(mocks.Transport)
53 
54 as.True(true) // placeholder
55 
56 cfg := Config{
57 ParentContext: context.Background(),
58 Logger: logger,
59 Chord: chord.WrapRetryKV(n, time.Millisecond*100, 3),
60 TunnelTransport: clt,
61 ChordTransport: cht,
62 Apex: testRootDomain,
63 Acme: testAcmeZone,
64 }
65 
66 for _, opt := range options {
67 opt(&cfg)
68 }
69 
70 s := New(cfg)
71 t.Cleanup(s.hostWAFCache.Close)
72 
73 return logger, n, clt, cht, s
74}
75 
76func getExpected(link *protocol.Link) [][]byte {
77 return [][]byte{
78 []byte(tun.RoutingKey(link.GetHostname(), 1)),
79 []byte(tun.RoutingKey(link.GetHostname(), 2)),
80 []byte(tun.RoutingKey(link.GetHostname(), 3)),
81 }
82}
83 
84func getIdentities() (*protocol.Node, *protocol.Node, *protocol.Node) {
85 cl := &protocol.Node{
86 Address: "client:123",
87 Id: chord.Random(),
88 Rendezvous: true,
89 }
90 ch := &protocol.Node{
91 Address: "chord:123",
92 Id: chord.Random(),
93 }
94 tn := &protocol.Node{
95 Address: "tunnel:123",
96 Id: chord.Random(),
97 }
98 return cl, ch, tn
99}
100 
101func TestContinueLookupOnError(t *testing.T) {
102 as := require.New(t)
103 
104 _, node, _, _, serv := getFixture(t, as)
105 
106 link := &protocol.Link{
107 Alpn: protocol.Link_HTTP,
108 Hostname: "test",
109 }
110 expected := getExpected(link)
111 
112 node.On("Get", mock.Anything, mock.MatchedBy(func(k []byte) bool {
113 return assertBytes(k, expected...)
114 })).Return(nil, fmt.Errorf("panic"))
115 
116 c, err := serv.DialClient(context.Background(), link)
117 as.ErrorIs(err, tun.ErrLookupFailed)
118 as.Nil(c)
119 
120 node.AssertExpectations(t)
121}
122 
123func TestLookupSuccessDirect(t *testing.T) {
124 as := require.New(t)
125 
126 _, node, clientT, _, serv := getFixture(t, as)
127 
128 link := &protocol.Link{
129 Alpn: protocol.Link_HTTP,
130 Hostname: "test",
131 }
132 
133 cli, cht, tn := getIdentities()
134 bundle := &protocol.TunnelRoute{
135 ClientDestination: cli,
136 ChordDestination: cht,
137 TunnelDestination: tn,
138 Hostname: link.GetHostname(),
139 }
140 bundleBuf, err := bundle.MarshalVT()
141 as.NoError(err)
142 
143 expected := getExpected(link)
144 
145 // 1. first query the chord network
146 node.On("Get", mock.Anything, mock.MatchedBy(func(k []byte) bool {
147 return assertBytes(k, expected...)
148 })).Return(bundleBuf, nil)
149 
150 // 2. then it should compare the content in bundle
151 clientT.On("Identity").Return(tn)
152 
153 // 3. once we figure out that it is connected to us,
154 // attempt to dial
155 c1, c2 := bufconn.BufferedPipe(8192)
156 go func() {
157 l := &protocol.Link{}
158 err := rpc.BoundedReceive(c2, l, 1024)
159 as.NoError(err)
160 as.Equal(link.GetAlpn(), l.GetAlpn())
161 as.Equal(link.GetHostname(), l.GetHostname())
162 }()
163 clientT.On("DialStream", mock.Anything, mock.MatchedBy(func(n *protocol.Node) bool {
164 return n.GetId() == cli.GetId()
165 }), protocol.Stream_DIRECT).Return(c1, nil)
166 
167 _, err = serv.DialClient(context.Background(), link)
168 as.NoError(err)
169 
170 node.AssertExpectations(t)
171 clientT.AssertExpectations(t)
172}
173 
174func TestLookupSuccessRemote(t *testing.T) {
175 as := require.New(t)
176 
177 _, node, clientT, chordT, serv := getFixture(t, as)
178 
179 link := &protocol.Link{
180 Alpn: protocol.Link_HTTP,
181 Hostname: "test",
182 }
183 
184 cli, cht, tn := getIdentities()
185 bundle := &protocol.TunnelRoute{
186 ClientDestination: cli,
187 ChordDestination: cht,
188 TunnelDestination: tn,
189 Hostname: link.GetHostname(),
190 }
191 bundleBuf, err := bundle.MarshalVT()
192 as.NoError(err)
193 
194 expected := getExpected(link)
195 
196 // 1. first query the chord network
197 node.On("Get", mock.Anything, mock.MatchedBy(func(k []byte) bool {
198 return assertBytes(k, expected...)
199 })).Return(bundleBuf, nil)
200 
201 // 2. then it should compare the content in bundle
202 clientT.On("Identity").Return(nil)
203 
204 // 3. once we figure out that it is NOT connected to us,
205 // attempt to dial via chord
206 c1, c2 := bufconn.BufferedPipe(8192)
207 go func() {
208 // the remote node should receive the bundle
209 bundle := &protocol.TunnelRoute{}
210 err := rpc.BoundedReceive(c2, bundle, 2048)
211 as.NoError(err)
212 
213 // remote node need to send feedback
214 tun.SendStatusProto(c2, nil)
215 
216 // then receive the link information
217 l := &protocol.Link{}
218 err = rpc.BoundedReceive(c2, l, 1024)
219 as.NoError(err)
220 as.Equal(link.GetAlpn(), l.GetAlpn())
221 as.Equal(link.GetHostname(), l.GetHostname())
222 }()
223 chordT.On("DialStream", mock.Anything, mock.MatchedBy(func(n *protocol.Node) bool {
224 return n.GetId() == cht.GetId()
225 }), protocol.Stream_PROXY).Return(c1, nil)
226 
227 _, err = serv.DialClient(context.Background(), link)
228 as.NoError(err)
229 
230 node.AssertExpectations(t)
231 clientT.AssertExpectations(t)
232 chordT.AssertExpectations(t)
233}
234 
235func TestHandleRemoteConnection(t *testing.T) {
236 as := require.New(t)
237 
238 logger, node, clientT, chordT, serv := getFixture(t, as)
239 cli, cht, tn := getIdentities()
240 bundle := &protocol.TunnelRoute{
241 ClientDestination: cli,
242 ChordDestination: cht,
243 TunnelDestination: tn,
244 Hostname: "test",
245 }
246 
247 ctx := t.Context()
248 
249 syncA := make(chan struct{})
250 syncB := make(chan struct{})
251 
252 chordChan := make(chan *transport.StreamDelegate)
253 chordT.On("AcceptStream").Return(chordChan)
254 chordT.On("Identity").Return(cht)
255 
256 clientChan := make(chan *transport.StreamDelegate)
257 clientT.On("AcceptStream").Return(clientChan)
258 clientT.On("Identity").Return(tn)
259 
260 // on start up (Accept), identities should get published
261 node.On("Put", mock.Anything, mock.MatchedBy(func(k []byte) bool {
262 exp := [][]byte{
263 []byte(tun.DestinationByChordKey(cht)),
264 []byte(tun.DestinationByTunnelKey(tn)),
265 }
266 return assertBytes(k, exp...)
267 }), mock.MatchedBy(func(v []byte) bool {
268 pair := &protocol.TunnelDestination{
269 Chord: cht,
270 Tunnel: tn,
271 }
272 buf, err := pair.MarshalVT()
273 if err != nil {
274 return false
275 }
276 return assertBytes(v, buf)
277 })).Return(nil)
278 
279 streamRouter := transport.NewStreamRouter(logger, chordT, clientT)
280 go streamRouter.Accept(ctx)
281 
282 serv.AttachRouter(ctx, streamRouter)
283 
284 // since the "client" is connected to us, we should expect a DialDirect
285 // to the client
286 c1, c2 := bufconn.BufferedPipe(8192)
287 c3, c4 := bufconn.BufferedPipe(8192)
288 clientT.On("DialStream", mock.Anything, mock.MatchedBy(func(n *protocol.Node) bool {
289 return n.GetId() == cli.GetId()
290 }), protocol.Stream_DIRECT).Return(c3, nil)
291 
292 buf := []byte{1, 2, 3}
293 
294 go func() {
295 // the remote should be sending the bundle over
296 err := rpc.Send(c2, bundle)
297 as.NoError(err)
298 
299 // getConn should check the status
300 x := &protocol.TunnelStatus{}
301 err = rpc.BoundedReceive(c2, x, 1024)
302 as.NoError(err)
303 as.Equal(protocol.TunnelStatusCode_STATUS_OK, x.GetStatus())
304 
305 // now the remote gateway is sending data to us
306 _, err = c2.Write(buf)
307 as.NoError(err)
308 
309 close(syncA)
310 }()
311 
312 go func() {
313 <-syncA
314 
315 // we should receive data from the remote side
316 b := make([]byte, len(buf))
317 _, err := c4.Read(b)
318 as.NoError(err)
319 as.EqualValues(buf, b)
320 
321 close(syncB)
322 }()
323 
324 serv.MustRegister(ctx)
325 
326 chordChan <- &transport.StreamDelegate{
327 Conn: c1,
328 Identity: &protocol.Node{Id: chord.Random()},
329 Kind: protocol.Stream_PROXY,
330 }
331 
332 select {
333 case <-syncB:
334 case <-time.After(time.Second * 5):
335 as.FailNow("timeout")
336 }
337 
338 clientT.AssertExpectations(t)
339 chordT.AssertExpectations(t)
340 node.AssertExpectations(t)
341}