Debian Codegraph @

pkg/server/server_test.go

raw symbols SCIP
1 /*
2 Copyright 2019 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package server
18
19 import (
20 "context"
21 "fmt"
22 "io"
23 "reflect"
24 "sync"
25 "testing"
26 "time"
27
28 "github.com/google/uuid"
29 "go.uber.org/mock/gomock"
30 "google.golang.org/grpc/metadata"
31
32 promtest "github.com/prometheus/client_golang/prometheus/testutil"
33 authv1 "k8s.io/api/authentication/v1"
34 "k8s.io/apimachinery/pkg/runtime"
35 "k8s.io/apimachinery/pkg/util/wait"
36 k8sfake "k8s.io/client-go/kubernetes/fake"
37 fakeauthenticationv1 "k8s.io/client-go/kubernetes/typed/authentication/v1/fake"
38 k8stesting "k8s.io/client-go/testing"
39
40 client "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client"
41 "sigs.k8s.io/apiserver-network-proxy/pkg/server/metrics"
42 metricstest "sigs.k8s.io/apiserver-network-proxy/pkg/testing/metrics"
43 agentmock "sigs.k8s.io/apiserver-network-proxy/proto/agent/mocks"
44 "sigs.k8s.io/apiserver-network-proxy/proto/header"
45 )
46
47 const xfrChannelSize = 10
48
49 func TestAgentTokenAuthenticationErrorsToken(t *testing.T) {
50 stub := gomock.NewController(t)
51 defer stub.Finish()
52
53 ns := "test_ns"
54 sa := "test_sa"
55
56 testCases := []struct {
57 desc string
58 mdKey string
59 tokens []string
60 wantNamespace string
61 wantServiceAccount string
62 authenticated bool
63 authError string
64 tokenReviewError error
65 wantError bool
66 }{
67 {
68 desc: "no context",
69 wantError: true,
70 },
71 {
72 desc: "non valid metadata key",
73 mdKey: "someKey",
74 tokens: []string{"token1"},
75 wantError: true,
76 },
77 {
78 desc: "non valid token prefix",
79 mdKey: header.AuthenticationTokenContextKey,
80 tokens: []string{"token1"},
81 wantError: true,
82 },
83 {
84 desc: "multiple valid tokens",
85 mdKey: header.AuthenticationTokenContextKey,
86 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1", header.AuthenticationTokenContextSchemePrefix + "token2"},
87 wantError: true,
88 },
89 {
90 desc: "not authenticated",
91 authenticated: false,
92 mdKey: header.AuthenticationTokenContextKey,
93 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"},
94 wantNamespace: ns,
95 wantServiceAccount: sa,
96 wantError: true,
97 },
98 {
99 desc: "tokenReview error",
100 authenticated: false,
101 mdKey: header.AuthenticationTokenContextKey,
102 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"},
103 tokenReviewError: fmt.Errorf("some error"),
104 wantNamespace: ns,
105 wantServiceAccount: sa,
106 wantError: true,
107 },
108 {
109 desc: "non valid namespace",
110 authenticated: true,
111 mdKey: header.AuthenticationTokenContextKey,
112 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"},
113 wantNamespace: "_" + ns,
114 wantServiceAccount: sa,
115 wantError: true,
116 },
117 {
118 desc: "non valid service account",
119 authenticated: true,
120 mdKey: header.AuthenticationTokenContextKey,
121 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"},
122 wantNamespace: ns,
123 wantServiceAccount: "_" + sa,
124 wantError: true,
125 },
126 {
127 desc: "authorization succeed",
128 authenticated: true,
129 mdKey: header.AuthenticationTokenContextKey,
130 tokens: []string{header.AuthenticationTokenContextSchemePrefix + "token1"},
131 wantNamespace: ns,
132 wantServiceAccount: sa,
133 },
134 }
135
136 for _, tc := range testCases {
137 t.Run(tc.desc, func(t *testing.T) {
138 kcs := k8sfake.NewSimpleClientset()
139
140 kcs.AuthenticationV1().(*fakeauthenticationv1.FakeAuthenticationV1).Fake.PrependReactor("create", "tokenreviews", func(_ k8stesting.Action) (handled bool, ret runtime.Object, err error) {
141 tr := &authv1.TokenReview{
142 Status: authv1.TokenReviewStatus{
143 Authenticated: tc.authenticated,
144 Error: tc.authError,
145 User: authv1.UserInfo{
146 Username: fmt.Sprintf("system:serviceaccount:%v:%v", ns, sa),
147 },
148 },
149 }
150 return true, tr, tc.tokenReviewError
151 })
152
153 var md metadata.MD
154 for _, token := range tc.tokens {
155 md = metadata.Join(md, metadata.Pairs(tc.mdKey, token))
156 }
157
158 md = metadata.Join(md, metadata.Pairs(header.AgentID, ""))
159
160 ctx := context.Background()
161 defer ctx.Done()
162 ctx = metadata.NewIncomingContext(ctx, md)
163 conn := agentmock.NewMockAgentService_ConnectServer(stub)
164 conn.EXPECT().Context().AnyTimes().Return(ctx)
165
166 // close agent's connection if no error is expected
167 if !tc.wantError {
168 conn.EXPECT().SendHeader(gomock.Any()).Return(nil)
169 conn.EXPECT().Recv().Return(nil, io.EOF)
170 }
171
172 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{
173 Enabled: true,
174 KubernetesClient: kcs,
175 AgentNamespace: tc.wantNamespace,
176 AgentServiceAccount: tc.wantServiceAccount,
177 }, xfrChannelSize)
178
179 err := p.Connect(conn)
180 if tc.wantError {
181 if err == nil {
182 t.Errorf("test case expected for error")
183 }
184 } else {
185 if err != nil {
186 t.Errorf("did not expected for error but got :%v", err)
187 }
188 }
189 })
190 }
191 }
192
193 func TestRemovePendingDialForStream(t *testing.T) {
194 streamUID := "target-uuid"
195 pending1 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: streamUID}}
196 pending2 := &ProxyClientConnection{}
197 pending3 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: streamUID}}
198 pending4 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: "different-uid"}}
199 pending5 := &ProxyClientConnection{frontend: &GrpcFrontend{streamUID: ""}}
200 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
201 p.PendingDial.Add(1, pending1)
202 p.PendingDial.Add(2, pending2)
203 p.PendingDial.Add(3, pending3)
204 p.PendingDial.Add(4, pending4)
205 p.PendingDial.Add(5, pending5)
206 p.PendingDial.removeForStream(streamUID)
207 expectedPending := map[int64]*ProxyClientConnection{
208 int64(2): pending2,
209 int64(4): pending4,
210 int64(5): pending5,
211 }
212 if e, a := expectedPending, p.PendingDial.pendingDial; !reflect.DeepEqual(e, a) {
213 t.Errorf("expected %v, got %v", e, a)
214 }
215 p.PendingDial.removeForStream("")
216 if e, a := expectedPending, p.PendingDial.pendingDial; !reflect.DeepEqual(e, a) {
217 t.Errorf("expected %v, got %v", e, a)
218 }
219 }
220
221 func TestAddRemoveFrontends(t *testing.T) {
222 agent1ConnID1 := new(ProxyClientConnection)
223 agent1ConnID2 := new(ProxyClientConnection)
224 agent2ConnID1 := new(ProxyClientConnection)
225 agent2ConnID2 := new(ProxyClientConnection)
226 agent3ConnID1 := new(ProxyClientConnection)
227
228 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
229 p.addEstablished("agent1", int64(1), agent1ConnID1)
230 p.removeEstablished("agent1", int64(1))
231 expectedFrontends := make(map[string]map[int64]*ProxyClientConnection)
232 if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) {
233 t.Errorf("expected %v, got %v", e, a)
234 }
235
236 p = NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
237 p.addEstablished("agent1", int64(1), agent1ConnID1)
238 p.addEstablished("agent1", int64(2), agent1ConnID2)
239 p.addEstablished("agent2", int64(1), agent2ConnID1)
240 p.addEstablished("agent2", int64(2), agent2ConnID2)
241 p.addEstablished("agent3", int64(1), agent3ConnID1)
242 p.removeEstablished("agent2", int64(1))
243 p.removeEstablished("agent2", int64(2))
244 p.removeEstablished("agent1", int64(1))
245 expectedFrontends = map[string]map[int64]*ProxyClientConnection{
246 "agent1": {
247 int64(2): agent1ConnID2,
248 },
249 "agent3": {
250 int64(1): agent3ConnID1,
251 },
252 }
253 if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) {
254 t.Errorf("expected %v, got %v", e, a)
255 }
256 }
257
258 func TestAddRemoveBackends_DefaultStrategy(t *testing.T) {
259 ctrl := gomock.NewController(t)
260 defer ctrl.Finish()
261
262 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{}))
263 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{}))
264 backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{}))
265
266 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
267
268 p.addBackend(backend1)
269
270 if got, _ := p.getBackend("127.0.0.1"); got != backend1 {
271 t.Errorf("expected %v, got %v", backend1, got)
272 }
273
274 p.addBackend(backend2)
275 p.addBackend(backend3)
276 p.removeBackend(backend1)
277 p.removeBackend(backend2)
278
279 if got, _ := p.getBackend("127.0.0.1"); got != backend3 {
280 t.Errorf("expected %v, got %v", backend3, got)
281 }
282
283 p.removeBackend(backend3)
284
285 if got, _ := p.getBackend("127.0.0.1"); got != nil {
286 t.Errorf("expected nil, got %v", got)
287 }
288 }
289
290 func TestAddRemoveBackends_DefaultRouteStrategy(t *testing.T) {
291 ctrl := gomock.NewController(t)
292 defer ctrl.Finish()
293
294 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{}))
295 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=false"}))
296 backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"default-route=true"}))
297
298 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefaultRoute}, 1, nil, xfrChannelSize)
299
300 p.addBackend(backend1)
301
302 if got, _ := p.getBackend("127.0.0.1"); got != nil {
303 t.Errorf("expected nil, got %v", got)
304 }
305
306 p.addBackend(backend2)
307
308 if got, _ := p.getBackend("127.0.0.1"); got != nil {
309 t.Errorf("expected nil, got %v", got)
310 }
311
312 p.addBackend(backend3)
313
314 if got, _ := p.getBackend("127.0.0.1"); got != backend3 {
315 t.Errorf("expected %v, got %v", backend3, got)
316 }
317
318 p.removeBackend(backend1)
319 p.removeBackend(backend2)
320
321 if got, _ := p.getBackend("127.0.0.1"); got != backend3 {
322 t.Errorf("expected %v, got %v", backend3, got)
323 }
324
325 p.removeBackend(backend3)
326
327 if got, _ := p.getBackend("127.0.0.1"); got != nil {
328 t.Errorf("expected nil, got %v", got)
329 }
330 }
331
332 func TestAddRemoveBackends_DestHostStrategy(t *testing.T) {
333 ctrl := gomock.NewController(t)
334 defer ctrl.Finish()
335
336 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"}))
337 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=true"}))
338 backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"}))
339
340 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDestHost}, 1, nil, xfrChannelSize)
341
342 p.addBackend(backend1)
343 p.addBackend(backend2)
344 p.addBackend(backend3)
345
346 if got, _ := p.getBackend("127.0.0.1"); got != nil {
347 t.Errorf("expected nil, got %v", got)
348 }
349 if got, _ := p.getBackend("localhost"); got != backend1 {
350 t.Errorf("expected %v, got %v", backend1, got)
351 }
352 if got, _ := p.getBackend("node1.mydomain.com"); got != backend1 {
353 t.Errorf("expected %v, got %v", backend1, got)
354 }
355 if got, _ := p.getBackend("1.2.3.4"); got != backend1 {
356 t.Errorf("expected %v, got %v", backend1, got)
357 }
358 if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend1 {
359 t.Errorf("expected %v, got %v", backend1, got)
360 }
361 if got, _ := p.getBackend("node2.mydomain.com"); got != backend3 {
362 t.Errorf("expected %v, got %v", backend3, got)
363 }
364 if got, _ := p.getBackend("5.6.7.8"); got != backend3 {
365 t.Errorf("expected %v, got %v", backend3, got)
366 }
367 if got, _ := p.getBackend("::"); got != backend3 {
368 t.Errorf("expected %v, got %v", backend3, got)
369 }
370
371 p.removeBackend(backend1)
372 p.removeBackend(backend2)
373 p.removeBackend(backend3)
374
375 if got, _ := p.getBackend("127.0.0.1"); got != nil {
376 t.Errorf("expected nil, got %v", got)
377 }
378 }
379
380 func TestAddRemoveBackends_DestHostSanitizeRequest(t *testing.T) {
381 ctrl := gomock.NewController(t)
382 defer ctrl.Finish()
383
384 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"}))
385 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"}))
386
387 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDestHost}, 1, nil, xfrChannelSize)
388
389 p.addBackend(backend1)
390 p.addBackend(backend2)
391
392 if got, _ := p.getBackend("127.0.0.1:443"); got != nil {
393 t.Errorf("expected nil, got %v", got)
394 }
395 if got, _ := p.getBackend("node1.mydomain.com:443"); got != backend1 {
396 t.Errorf("expected %v, got %v", backend1, got)
397 }
398 if got, _ := p.getBackend("node2.mydomain.com:443"); got != backend2 {
399 t.Errorf("expected %v, got %v", backend2, got)
400 }
401 }
402
403 func TestAddRemoveBackends_DestHostWithDefault(t *testing.T) {
404 ctrl := gomock.NewController(t)
405 defer ctrl.Finish()
406
407 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"}))
408 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"default-route=false"}))
409 backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"}))
410
411 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDestHost, ProxyStrategyDefault}, 1, nil, xfrChannelSize)
412
413 p.addBackend(backend1)
414 p.addBackend(backend2)
415 p.addBackend(backend3)
416
417 if got, _ := p.getBackend("127.0.0.1"); got == nil {
418 t.Errorf("expected random fallback, got nil")
419 }
420 if got, _ := p.getBackend("localhost"); got != backend1 {
421 t.Errorf("expected %v, got %v", backend1, got)
422 }
423 if got, _ := p.getBackend("node1.mydomain.com"); got != backend1 {
424 t.Errorf("expected %v, got %v", backend1, got)
425 }
426 if got, _ := p.getBackend("1.2.3.4"); got != backend1 {
427 t.Errorf("expected %v, got %v", backend1, got)
428 }
429 if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend1 {
430 t.Errorf("expected %v, got %v", backend1, got)
431 }
432 if got, _ := p.getBackend("node2.mydomain.com"); got != backend3 {
433 t.Errorf("expected %v, got %v", backend3, got)
434 }
435 if got, _ := p.getBackend("5.6.7.8"); got != backend3 {
436 t.Errorf("expected %v, got %v", backend3, got)
437 }
438 if got, _ := p.getBackend("::"); got != backend3 {
439 t.Errorf("expected %v, got %v", backend3, got)
440 }
441
442 p.removeBackend(backend1)
443 p.removeBackend(backend2)
444
445 if got, _ := p.getBackend("127.0.0.1"); got != backend3 {
446 t.Errorf("expected %v, got %v", backend3, got)
447 }
448
449 p.removeBackend(backend3)
450
451 if got, _ := p.getBackend("127.0.0.1"); got != nil {
452 t.Errorf("expected nil, got %v", got)
453 }
454 }
455
456 func TestAddRemoveBackends_DestHostWithDuplicateIdents(t *testing.T) {
457 ctrl := gomock.NewController(t)
458 defer ctrl.Finish()
459
460 backend1, _ := NewBackend(mockAgentConn(ctrl, "agent1", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"}))
461 backend2, _ := NewBackend(mockAgentConn(ctrl, "agent2", []string{"host=localhost&host=node1.mydomain.com&ipv4=1.2.3.4&ipv6=9878::7675:1292:9183:7562"}))
462 backend3, _ := NewBackend(mockAgentConn(ctrl, "agent3", []string{"host=localhost&host=node2.mydomain.com&ipv4=5.6.7.8&ipv6=::"}))
463
464 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDestHost, ProxyStrategyDefault}, 1, nil, xfrChannelSize)
465
466 p.addBackend(backend1)
467 p.addBackend(backend2)
468 p.addBackend(backend3)
469
470 if got, _ := p.getBackend("127.0.0.1"); got == nil {
471 t.Errorf("expected random fallback, got nil")
472 }
473 if got, _ := p.getBackend("localhost"); got == nil {
474 t.Errorf("expected any backend, got nil")
475 }
476
477 p.removeBackend(backend1)
478 p.removeBackend(backend3)
479
480 if got, _ := p.getBackend("127.0.0.1"); got != backend2 {
481 t.Errorf("expected %v, got %v", backend2, got)
482 }
483 if got, _ := p.getBackend("localhost"); got != backend2 {
484 t.Errorf("expected %v, got %v", backend2, got)
485 }
486 if got, _ := p.getBackend("node1.mydomain.com"); got != backend2 {
487 t.Errorf("expected %v, got %v", backend2, got)
488 }
489 if got, _ := p.getBackend("1.2.3.4"); got != backend2 {
490 t.Errorf("expected %v, got %v", backend2, got)
491 }
492 if got, _ := p.getBackend("9878::7675:1292:9183:7562"); got != backend2 {
493 t.Errorf("expected %v, got %v", backend2, got)
494 }
495 if got, _ := p.getBackend("node2.mydomain.com"); got != backend2 {
496 t.Errorf("expected %v, got %v", backend2, got)
497 }
498 if got, _ := p.getBackend("5.6.7.8"); got != backend2 {
499 t.Errorf("expected %v, got %v", backend2, got)
500 }
501 if got, _ := p.getBackend("::"); got != backend2 {
502 t.Errorf("expected %v, got %v", backend2, got)
503 }
504
505 p.removeBackend(backend2)
506
507 if got, _ := p.getBackend("127.0.0.1"); got != nil {
508 t.Errorf("expected nil, got %v", got)
509 }
510 }
511
512 func TestEstablishedConnsMetric(t *testing.T) {
513 metrics.Metrics.Reset()
514
515 agent1ConnID1 := new(ProxyClientConnection)
516 agent1ConnID2 := new(ProxyClientConnection)
517 agent2ConnID1 := new(ProxyClientConnection)
518 agent2ConnID2 := new(ProxyClientConnection)
519 agent3ConnID1 := new(ProxyClientConnection)
520
521 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
522 p.addEstablished("agent1", int64(1), agent1ConnID1)
523 assertEstablishedConnsMetric(t, 1)
524 p.addEstablished("agent1", int64(2), agent1ConnID2)
525 assertEstablishedConnsMetric(t, 2)
526 p.addEstablished("agent2", int64(1), agent2ConnID1)
527 assertEstablishedConnsMetric(t, 3)
528 p.addEstablished("agent2", int64(2), agent2ConnID2)
529 assertEstablishedConnsMetric(t, 4)
530 p.addEstablished("agent3", int64(1), agent3ConnID1)
531 assertEstablishedConnsMetric(t, 5)
532 p.removeEstablished("agent2", int64(1))
533 assertEstablishedConnsMetric(t, 4)
534 p.removeEstablished("agent2", int64(2))
535 assertEstablishedConnsMetric(t, 3)
536 p.removeEstablished("agent1", int64(1))
537 assertEstablishedConnsMetric(t, 2)
538 p.removeEstablished("agent1", int64(2))
539 assertEstablishedConnsMetric(t, 1)
540 p.removeEstablished("agent3", int64(1))
541 assertEstablishedConnsMetric(t, 0)
542 }
543
544 func TestRemoveEstablishedForBackendConn(t *testing.T) {
545 backend1 := &Backend{}
546 backend2 := &Backend{}
547 backend3 := &Backend{}
548 agent1ConnID1 := &ProxyClientConnection{backend: backend1}
549 agent1ConnID2 := &ProxyClientConnection{backend: backend1}
550 agent2ConnID1 := &ProxyClientConnection{backend: backend2}
551 agent2ConnID2 := &ProxyClientConnection{backend: backend2}
552 agent3ConnID1 := &ProxyClientConnection{backend: backend3}
553 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
554 p.addEstablished("agent1", int64(1), agent1ConnID1)
555 p.addEstablished("agent1", int64(2), agent1ConnID2)
556 p.addEstablished("agent2", int64(1), agent2ConnID1)
557 p.addEstablished("agent2", int64(2), agent2ConnID2)
558 p.addEstablished("agent3", int64(1), agent3ConnID1)
559 p.removeEstablishedForBackendConn("agent2", backend2)
560 expectedFrontends := map[string]map[int64]*ProxyClientConnection{
561 "agent1": {
562 int64(1): agent1ConnID1,
563 int64(2): agent1ConnID2,
564 },
565 "agent3": {
566 int64(1): agent3ConnID1,
567 },
568 }
569 if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) {
570 t.Errorf("expected %v, got %v", e, a)
571 }
572 }
573
574 func TestRemoveEstablishedForStream(t *testing.T) {
575 streamUID := "target-uuid"
576 backend1 := &Backend{}
577 backend2 := &Backend{}
578 backend3 := &Backend{}
579 agent1ConnID1 := &ProxyClientConnection{backend: backend1, frontend: &GrpcFrontend{streamUID: streamUID}}
580 agent1ConnID2 := &ProxyClientConnection{backend: backend1}
581 agent2ConnID1 := &ProxyClientConnection{backend: backend2, frontend: &GrpcFrontend{streamUID: streamUID}}
582 agent2ConnID2 := &ProxyClientConnection{backend: backend2}
583 agent3ConnID1 := &ProxyClientConnection{backend: backend3, frontend: &GrpcFrontend{streamUID: streamUID}}
584 p := NewProxyServer("", []ProxyStrategy{ProxyStrategyDefault}, 1, nil, xfrChannelSize)
585 p.addEstablished("agent1", int64(1), agent1ConnID1)
586 p.addEstablished("agent1", int64(2), agent1ConnID2)
587 p.addEstablished("agent2", int64(1), agent2ConnID1)
588 p.addEstablished("agent2", int64(2), agent2ConnID2)
589 p.addEstablished("agent3", int64(1), agent3ConnID1)
590 p.removeEstablishedForStream(streamUID)
591 expectedFrontends := map[string]map[int64]*ProxyClientConnection{
592 "agent1": {
593 int64(2): agent1ConnID2,
594 },
595 "agent2": {
596 int64(2): agent2ConnID2,
597 },
598 }
599 if e, a := expectedFrontends, p.established; !reflect.DeepEqual(e, a) {
600 t.Errorf("expected %v, got %v", e, a)
601 }
602 }
603
604 func prepareFrontendConn(ctrl *gomock.Controller) *agentmock.MockAgentService_ConnectServer {
605 // prepare the connection to fontend of proxy-server
606 // TODO: replace with a mock ProxyService_ProxyServer
607 frontendConn := agentmock.NewMockAgentService_ConnectServer(ctrl)
608 frontendConnMD := metadata.MD{
609 ":authority": []string{"127.0.0.1:8090"},
610 "content-type": []string{"application/grpc"},
611 "user-agent": []string{"grpc-go/1.42.0"},
612 }
613 frontendConnCtx := metadata.NewIncomingContext(context.Background(), frontendConnMD)
614 frontendConn.EXPECT().Context().Return(frontendConnCtx).AnyTimes()
615 return frontendConn
616 }
617
618 func prepareAgentConnMD(t testing.TB, ctrl *gomock.Controller, proxyServer *ProxyServer) (*agentmock.MockAgentService_ConnectServer, *Backend) {
619 t.Helper()
620 // prepare the the connection to agent of proxy-server
621 agentConn := agentmock.NewMockAgentService_ConnectServer(ctrl)
622 agentConnMD := metadata.MD{
623 ":authority": []string{"127.0.0.1:8091"},
624 "agentid": []string{uuid.New().String()},
625 "agentidentifiers": []string{},
626 "content-type": []string{"application/grpc"},
627 "user-agent": []string{"grpc-go/1.42.0"},
628 }
629 agentConnCtx := metadata.NewIncomingContext(context.Background(), agentConnMD)
630 agentConn.EXPECT().Context().Return(agentConnCtx).AnyTimes()
631 backend, err := NewBackend(agentConn)
632 if err != nil {
633 t.Fatalf("Unexpected NewBackend error: %v", err)
634 }
635 proxyServer.addBackend(backend)
636 return agentConn, backend
637 }
638
639 func baseServerProxyTestWithoutBackend(t *testing.T, validate func(*agentmock.MockAgentService_ConnectServer)) {
640 ctrl := gomock.NewController(t)
641 defer ctrl.Finish()
642
643 frontendConn := prepareFrontendConn(ctrl)
644 proxyServer := NewProxyServer(uuid.New().String(), []ProxyStrategy{ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize)
645
646 validate(frontendConn)
647
648 proxyServer.Proxy(frontendConn)
649 }
650
651 func baseServerProxyTestWithBackend(t *testing.T, validate func(*agentmock.MockAgentService_ConnectServer, *agentmock.MockAgentService_ConnectServer)) {
652 ctrl := gomock.NewController(t)
653 defer ctrl.Finish()
654
655 frontendConn := prepareFrontendConn(ctrl)
656
657 // prepare proxy server
658 proxyServer := NewProxyServer(uuid.New().String(), []ProxyStrategy{ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize)
659
660 agentConn, _ := prepareAgentConnMD(t, ctrl, proxyServer)
661
662 validate(frontendConn, agentConn)
663
664 proxyServer.Proxy(frontendConn)
665 }
666
667 func TestServerProxyNoBackend(t *testing.T) {
668 validate := func(frontendConn *agentmock.MockAgentService_ConnectServer) {
669 // receive DIAL_REQ from frontend and proxy to backend
670 dialReq := &client.Packet{
671 Type: client.PacketType_DIAL_REQ,
672 Payload: &client.Packet_DialRequest{
673 DialRequest: &client.DialRequest{
674 Protocol: "tcp",
675 Address: "127.0.0.1:8080",
676 Random: 111,
677 },
678 },
679 }
680
681 dialResp := &client.Packet{
682 Type: client.PacketType_DIAL_RSP,
683 Payload: &client.Packet_DialResponse{
684 DialResponse: &client.DialResponse{
685 Random: 111,
686 Error: (&ErrNotFound{}).Error(),
687 }},
688 }
689
690 gomock.InOrder(
691 frontendConn.EXPECT().Recv().Return(dialReq, nil).Times(1),
692 frontendConn.EXPECT().Recv().Return(nil, io.EOF).Times(1),
693 // NOTE(mainred): `Send` should come before `Recv` io.EOF, but we cannot add wait between
694 // two Recvs, thus `Recv`` comes before `Send`
695 frontendConn.EXPECT().Send(dialResp).Return(nil).Times(1),
696 )
697
698 }
699 baseServerProxyTestWithoutBackend(t, validate)
700
701 if err := metricstest.DefaultTester.ExpectServerDialFailure(metrics.DialFailureNoAgent, 1); err != nil {
702 t.Error(err)
703 }
704 }
705
706 func TestServerProxyNormalClose(t *testing.T) {
707 validate := func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) {
708 const dialID = 111
709 const connectID = 123456
710 // receive DIAL_REQ from frontend and proxy to backend
711 dialReq := dialReqPkt(dialID)
712 data := dataPkt(connectID, []byte("hello world"))
713 closeReq := closeReqPkt(connectID)
714
715 gomock.InOrder(
716 frontendConn.EXPECT().Recv().Return(dialReq, nil).Times(1),
717 frontendConn.EXPECT().Recv().Return(data, nil).Times(1),
718 frontendConn.EXPECT().Recv().Return(closeReq, nil).Times(1),
719 frontendConn.EXPECT().Recv().Return(nil, io.EOF).Times(1),
720 )
721 gomock.InOrder(
722 agentConn.EXPECT().Send(dialReq).Return(nil).Times(1),
723 agentConn.EXPECT().Send(data).Return(nil).Times(1),
724 agentConn.EXPECT().Send(closeReq).Return(nil).Times(1),
725 agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1),
726 )
727 }
728 baseServerProxyTestWithBackend(t, validate)
729 }
730
731 func TestServerProxyRecvChanFull(t *testing.T) {
732 validate := func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) {
733 const dialID = 111
734 const connectID = 1
735 // receive DIAL_REQ from frontend and proxy to backend
736 dialReq := dialReqPkt(dialID)
737 data := dataPkt(connectID, []byte("hello world"))
738
739 const defaultTimeout = 5 * time.Minute
740 deadline := time.Now().Add(defaultTimeout)
741 if testDeadline, ok := t.Deadline(); ok && testDeadline.Before(deadline) {
742 deadline = testDeadline.Add(-1 * time.Second)
743 }
744
745 waitForMetricVal := func(expected float64) {
746 err := wait.Poll(10*time.Millisecond, time.Until(deadline), func() (bool, error) {
747 val := promtest.ToFloat64(metrics.Metrics.FullRecvChannel(metrics.Proxy))
748 return val == expected, nil
749 })
750 if err != nil {
751 t.Fatalf("Failed to observe expected metric: %v", err)
752 }
753 }
754
755 expectMetricVal := func(expected float64) {
756 val := promtest.ToFloat64(metrics.Metrics.FullRecvChannel(metrics.Proxy))
757 if val != expected {
758 t.Errorf("Unexpected metric value: %v (expected %v)", val, expected)
759 }
760 }
761
762 // WaitGroups for coordinating test stages.
763 recvWG := sync.WaitGroup{}
764 recvWG.Add(1)
765 sendWG := sync.WaitGroup{}
766 sendWG.Add(1)
767
768 gomock.InOrder(
769 frontendConn.EXPECT().Recv().Return(dialReq, nil),
770 // First packet goes through to agentConn.Send
771 frontendConn.EXPECT().Recv().Return(data, nil),
772 // Next xfrChannelSize packets fill the channel.
773 frontendConn.EXPECT().Recv().DoAndReturn(func() (*client.Packet, error) {
774 // Wait for initial packet send before filling the channel.
775 recvWG.Wait()
776 return data, nil
777 }),
778 frontendConn.EXPECT().Recv().Return(data, nil).Times(xfrChannelSize-1),
779 // Last packet should trigger channel full condition.
780 frontendConn.EXPECT().Recv().DoAndReturn(func() (*client.Packet, error) {
781 // Verify that the full channel condition hasn't triggered yet.
782 expectMetricVal(0)
783 return data, nil
784 }),
785
786 frontendConn.EXPECT().Recv().Return(closeReqPkt(1), nil),
787 // Ensure that the go-routines don't deadlock if more packets are received before closing the connection.
788 // This is a bit contrived, but exercises a possible failure scenario.
789 frontendConn.EXPECT().Recv().Return(data, nil).Times(xfrChannelSize+1),
790 frontendConn.EXPECT().Recv().Return(nil, io.EOF),
791 )
792 gomock.InOrder(
793 agentConn.EXPECT().Send(dialReq).Return(nil),
794 agentConn.EXPECT().Send(data).DoAndReturn(func(_ *client.Packet) error {
795 // Channel should not be full at this point.
796 expectMetricVal(0)
797 recvWG.Done() // Proceed to fill the channel.
798
799 // Block the send from completing until the full channel condition is detected.
800 waitForMetricVal(1)
801 return nil
802 }),
803 agentConn.EXPECT().Send(data).Return(nil).Times(xfrChannelSize+1), // Expect the remaining packets to be sent.
804 agentConn.EXPECT().Send(closeReqPkt(1)).Return(nil),
805 agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1),
806 )
807 }
808 baseServerProxyTestWithBackend(t, validate)
809 }
810
811 func TestServerProxyNoDial(t *testing.T) {
812 baseServerProxyTestWithBackend(t, func(frontendConn, _ *agentmock.MockAgentService_ConnectServer) {
813 const connectID = 123456
814 data := &client.Packet{
815 Type: client.PacketType_DATA,
816 Payload: &client.Packet_Data{
817 Data: &client.Data{
818 ConnectID: connectID,
819 },
820 },
821 }
822
823 gomock.InOrder(
824 frontendConn.EXPECT().Recv().Return(data, nil),
825 frontendConn.EXPECT().Recv().Return(nil, io.EOF),
826 )
827 frontendConn.EXPECT().Send(closeRspPkt(connectID, "backend not initialized")).Return(nil)
828 })
829 }
830
831 func TestServerProxyConnectionMismatch(t *testing.T) {
832 baseServerProxyTestWithBackend(t, func(frontendConn, agentConn *agentmock.MockAgentService_ConnectServer) {
833 const dialID = 111
834 const firstConnectID = 123456
835 const secondConnectID = 654321
836 dialReq := dialReqPkt(dialID)
837 data := dataPkt(firstConnectID, []byte("hello"))
838 mismatchedData := dataPkt(secondConnectID, []byte("world"))
839
840 gomock.InOrder(
841 frontendConn.EXPECT().Recv().Return(dialReq, nil),
842 frontendConn.EXPECT().Recv().Return(data, nil),
843 frontendConn.EXPECT().Recv().Return(mismatchedData, nil),
844 frontendConn.EXPECT().Recv().Return(nil, io.EOF),
845 )
846 gomock.InOrder(
847 agentConn.EXPECT().Send(dialReq).Return(nil),
848 agentConn.EXPECT().Send(data).Return(nil),
849 )
850 agentConn.EXPECT().Send(closeReqPkt(secondConnectID)).Return(nil)
851 agentConn.EXPECT().Send(closeReqPkt(firstConnectID)).Return(nil)
852 frontendConn.EXPECT().Send(closeRspPkt(secondConnectID, "mismatched connection IDs")).Return(nil)
853 frontendConn.EXPECT().Send(closeRspPkt(firstConnectID, "mismatched connection IDs")).Return(nil)
854 agentConn.EXPECT().Send(dialClosePkt(dialID)).Return(nil).Times(1)
855 })
856 }
857
858 func TestReadyBackendsMetric(t *testing.T) {
859 ctrl := gomock.NewController(t)
860 defer ctrl.Finish()
861
862 metrics.Metrics.Reset()
863
864 p := NewProxyServer(uuid.New().String(), []ProxyStrategy{ProxyStrategyDefault}, 1, &AgentTokenAuthenticationOptions{}, xfrChannelSize)
865 assertReadyBackendsMetric(t, 0)
866
867 _, backend := prepareAgentConnMD(t, ctrl, p)
868 assertReadyBackendsMetric(t, 1)
869
870 p.removeBackend(backend)
871 assertReadyBackendsMetric(t, 0)
872 }
873
874 func dialReqPkt(dialID int64) *client.Packet {
875 return &client.Packet{
876 Type: client.PacketType_DIAL_REQ,
877 Payload: &client.Packet_DialRequest{
878 DialRequest: &client.DialRequest{
879 Protocol: "tcp",
880 Address: "127.0.0.1:8080",
881 Random: dialID,
882 },
883 },
884 }
885 }
886
887 func dataPkt(connectID int64, data []byte) *client.Packet {
888 return &client.Packet{
889 Type: client.PacketType_DATA,
890 Payload: &client.Packet_Data{
891 Data: &client.Data{
892 ConnectID: connectID,
893 Data: data,
894 },
895 },
896 }
897 }
898
899 func closeReqPkt(connectID int64) *client.Packet {
900 return &client.Packet{
901 Type: client.PacketType_CLOSE_REQ,
902 Payload: &client.Packet_CloseRequest{
903 CloseRequest: &client.CloseRequest{
904 ConnectID: connectID,
905 }},
906 }
907 }
908
909 func closeRspPkt(connectID int64, errMsg string) *client.Packet {
910 return &client.Packet{
911 Type: client.PacketType_CLOSE_RSP,
912 Payload: &client.Packet_CloseResponse{
913 CloseResponse: &client.CloseResponse{
914 ConnectID: connectID,
915 Error: errMsg,
916 },
917 },
918 }
919 }
920
921 func assertEstablishedConnsMetric(t testing.TB, expect int) {
922 t.Helper()
923 if err := metricstest.DefaultTester.ExpectServerEstablishedConns(expect); err != nil {
924 t.Errorf("Expected %d %s metric: %v", expect, "established_connections", err)
925 }
926 }
927
928 func assertReadyBackendsMetric(t testing.TB, expect int) {
929 t.Helper()
930 if err := metricstest.DefaultTester.ExpectServerReadyBackends(expect); err != nil {
931 t.Errorf("Expected %d %s metric: %v", expect, "ready_backend_connections", err)
932 }
933 }
934
935 func dialClosePkt(dialID int64) *client.Packet {
936 return &client.Packet{
937 Type: client.PacketType_DIAL_CLS,
938 Payload: &client.Packet_CloseDial{
939 CloseDial: &client.CloseDial{
940 Random: dialID,
941 },
942 },
943 }
944 }