This repository has been archived by the owner on Dec 6, 2022. It is now read-only.
forked from kubernetes-sigs/apiserver-network-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_test.go
559 lines (453 loc) · 12.2 KB
/
proxy_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
package tests
import (
"bufio"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"go.uber.org/goleak"
"google.golang.org/grpc"
"sigs.k8s.io/apiserver-network-proxy/konnectivity-client/pkg/client"
clientproto "sigs.k8s.io/apiserver-network-proxy/konnectivity-client/proto/client"
"sigs.k8s.io/apiserver-network-proxy/pkg/agent"
"sigs.k8s.io/apiserver-network-proxy/pkg/server"
agentproto "sigs.k8s.io/apiserver-network-proxy/proto/agent"
)
// test remote server
type testServer struct {
echo []byte
chunks int
wchan chan struct{}
}
func newEchoServer(echo string) *testServer {
return &testServer{
echo: []byte(echo),
chunks: 1,
}
}
func newSizedServer(length, chunks int) *testServer {
return &testServer{
echo: make([]byte, length),
chunks: chunks,
}
}
func (s *testServer) ServeHTTP(w http.ResponseWriter, req *http.Request) {
for i := 0; i < s.chunks; i++ {
// Wait before sending the last chunk if test requires it
if i == (s.chunks-1) && s.wchan != nil {
<-s.wchan
}
w.Write(s.echo)
}
}
func TestBasicProxy_GRPC(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
ctx := context.Background()
server := httptest.NewServer(newEchoServer("hello"))
defer server.Close()
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runGRPCProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
// run test client
tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, proxy.front, grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
c := &http.Client{
Transport: &http.Transport{
DialContext: tunnel.DialContext,
},
}
req, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Error(err)
}
req.Close = true
r, err := c.Do(req)
if err != nil {
t.Error(err)
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
if string(data) != "hello" {
t.Errorf("expect %v; got %v", "hello", string(data))
}
}
func TestProxyHandleDialError_GRPC(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
ctx := context.Background()
invalidServer := httptest.NewServer(newEchoServer("hello"))
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runGRPCProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
// run test client
tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, proxy.front, grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
c := &http.Client{
Transport: &http.Transport{
DialContext: tunnel.DialContext,
},
}
url := invalidServer.URL
invalidServer.Close()
_, err = c.Get(url)
if err == nil || !strings.Contains(err.Error(), "connection refused") {
t.Error("Expected error when destination is unreachable, did not receive error")
}
}
func TestProxyHandle_DoneContext_GRPC(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
hangingServer := newEchoServer("hello")
hangingServer.wchan = make(chan struct{})
server := httptest.NewServer(hangingServer)
defer server.Close()
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runGRPCProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
// run test client
ctx, cancel := context.WithTimeout(context.Background(), -time.Second)
defer cancel()
_, err = client.CreateSingleUseGrpcTunnel(ctx, proxy.front, grpc.WithInsecure())
if err == nil || !strings.Contains(err.Error(), "context deadline exceeded") {
t.Error("Expected error when context is cancelled, did not receive error")
}
}
func TestProxyHandle_SlowContext_GRPC(t *testing.T) {
// TODO: enable goleak validation after https://github.com/kubernetes-sigs/apiserver-network-proxy/issues/340
// defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
slowServer := newEchoServer("hello")
slowServer.wchan = make(chan struct{})
server := httptest.NewServer(slowServer)
defer server.Close()
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runGRPCProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
// run test client
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, proxy.front, grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
go func() {
time.Sleep(3 * time.Second)
close(slowServer.wchan)
}()
c := &http.Client{
Transport: &http.Transport{
DialContext: tunnel.DialContext,
},
}
// TODO: handle case where there is no context on the request.
req, err := http.NewRequestWithContext(ctx, "GET", server.URL, nil)
if err != nil {
t.Error(err)
}
_, err = c.Do(req)
if err == nil || !strings.Contains(err.Error(), "context deadline exceeded") {
t.Error("Expected error when context is cancelled, did not receive error")
}
}
func TestProxy_LargeResponse(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
ctx := context.Background()
length := 1 << 20 // 1M
chunks := 10
server := httptest.NewServer(newSizedServer(length, chunks))
defer server.Close()
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runGRPCProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
// run test client
tunnel, err := client.CreateSingleUseGrpcTunnel(ctx, proxy.front, grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
c := &http.Client{
Transport: &http.Transport{
DialContext: tunnel.DialContext,
},
}
req, err := http.NewRequest("GET", server.URL, nil)
if err != nil {
t.Error(err)
}
req.Close = true
r, err := c.Do(req)
if err != nil {
t.Error(err)
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
if len(data) != length*chunks {
t.Errorf("expect data length %d; got %d", length*chunks, len(data))
}
}
func TestBasicProxy_HTTPCONN(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
server := httptest.NewServer(newEchoServer("hello"))
defer server.Close()
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runHTTPConnProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
conn, err := net.Dial("tcp", proxy.front)
if err != nil {
t.Error(err)
}
serverURL, _ := url.Parse(server.URL)
// Send HTTP-Connect request
_, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1")
if err != nil {
t.Error(err)
}
// Parse the HTTP response for Connect
br := bufio.NewReader(conn)
res, err := http.ReadResponse(br, nil)
if err != nil {
t.Errorf("reading HTTP response from CONNECT: %v", err)
}
if res.StatusCode != 200 {
t.Errorf("expect 200; got %d", res.StatusCode)
}
if br.Buffered() > 0 {
t.Error("unexpected extra buffer")
}
dialer := func(network, addr string) (net.Conn, error) {
return conn, nil
}
c := &http.Client{
Transport: &http.Transport{
Dial: dialer,
},
}
r, err := c.Get(server.URL)
if err != nil {
t.Error(err)
}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
t.Error(err)
}
if string(data) != "hello" {
t.Errorf("expect %v; got %v", "hello", string(data))
}
}
func TestFailedDial_HTTPCONN(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
server := httptest.NewServer(newEchoServer("hello"))
server.Close() // cleanup immediately so connections will fail
stopCh := make(chan struct{})
defer close(stopCh)
proxy, cleanup, err := runHTTPConnProxyServer()
if err != nil {
t.Fatal(err)
}
defer cleanup()
runAgent(proxy.agent, stopCh)
// Wait for agent to register on proxy server
time.Sleep(time.Second)
conn, err := net.Dial("tcp", proxy.front)
if err != nil {
t.Error(err)
}
serverURL, _ := url.Parse(server.URL)
// Send HTTP-Connect request
_, err = fmt.Fprintf(conn, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", serverURL.Host, "127.0.0.1")
if err != nil {
t.Error(err)
}
// Parse the HTTP response for Connect
br := bufio.NewReader(conn)
res, err := http.ReadResponse(br, nil)
if err != nil {
t.Errorf("reading HTTP response from CONNECT: %v", err)
}
if res.StatusCode != 200 {
t.Errorf("expect 200; got %d", res.StatusCode)
}
dialer := func(network, addr string) (net.Conn, error) {
return conn, nil
}
c := &http.Client{
Transport: &http.Transport{
Dial: dialer,
},
}
_, err = c.Get(server.URL)
if err == nil || !strings.Contains(err.Error(), "connection reset by peer") {
t.Error(err)
}
for i := 0; i < 20; i++ {
if proxy.getActiveHTTPConnectConns() == 0 {
return
}
time.Sleep(time.Millisecond * 10)
}
t.Errorf("expected connection to eventually be closed")
}
func localAddr(addr net.Addr) string {
return addr.String()
}
type proxy struct {
server *server.ProxyServer
front string
agent string
getActiveHTTPConnectConns func() int
}
func runGRPCProxyServer() (proxy, func(), error) {
p, _, cleanup, err := runGRPCProxyServerWithServerCount(1)
return p, cleanup, err
}
func runGRPCProxyServerWithServerCount(serverCount int) (proxy, *server.ProxyServer, func(), error) {
var proxy proxy
var err error
var lis, lis2 net.Listener
server := server.NewProxyServer(uuid.New().String(), []server.ProxyStrategy{server.ProxyStrategyDefault}, serverCount, &server.AgentTokenAuthenticationOptions{}, false)
grpcServer := grpc.NewServer()
agentServer := grpc.NewServer()
cleanup := func() {
if lis != nil {
lis.Close()
}
if lis2 != nil {
lis2.Close()
}
agentServer.Stop()
grpcServer.Stop()
}
clientproto.RegisterProxyServiceServer(grpcServer, server)
lis, err = net.Listen("tcp", "")
if err != nil {
return proxy, server, cleanup, err
}
go grpcServer.Serve(lis)
proxy.front = localAddr(lis.Addr())
agentproto.RegisterAgentServiceServer(agentServer, server)
lis2, err = net.Listen("tcp", "")
if err != nil {
return proxy, server, cleanup, err
}
go func() {
agentServer.Serve(lis2)
}()
proxy.agent = localAddr(lis2.Addr())
proxy.server = server
return proxy, server, cleanup, nil
}
func runHTTPConnProxyServer() (proxy, func(), error) {
ctx := context.Background()
var proxy proxy
s := server.NewProxyServer(uuid.New().String(), []server.ProxyStrategy{server.ProxyStrategyDefault}, 0, &server.AgentTokenAuthenticationOptions{}, false)
agentServer := grpc.NewServer()
agentproto.RegisterAgentServiceServer(agentServer, s)
lis, err := net.Listen("tcp", "")
if err != nil {
return proxy, func() {}, err
}
go func() {
agentServer.Serve(lis)
}()
proxy.agent = localAddr(lis.Addr())
// http-connect
active := int32(0)
proxy.getActiveHTTPConnectConns = func() int { return int(atomic.LoadInt32(&active)) }
handler := &server.Tunnel{
Server: s,
}
httpServer := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&active, 1)
defer atomic.AddInt32(&active, -1)
handler.ServeHTTP(w, r)
}),
}
lis2, err := net.Listen("tcp", "")
if err != nil {
return proxy, func() {}, err
}
proxy.front = localAddr(lis2.Addr())
go func() {
err := httpServer.Serve(lis2)
if err != nil {
fmt.Println("http connect server error: ", err)
}
}()
cleanup := func() {
lis.Close()
lis2.Close()
httpServer.Shutdown(ctx)
}
proxy.server = s
return proxy, cleanup, nil
}
func runAgent(addr string, stopCh <-chan struct{}) *agent.ClientSet {
return runAgentWithID(uuid.New().String(), addr, stopCh)
}
func runAgentWithID(agentID, addr string, stopCh <-chan struct{}) *agent.ClientSet {
cc := agent.ClientSetConfig{
Address: addr,
AgentID: agentID,
SyncInterval: 100 * time.Millisecond,
ProbeInterval: 100 * time.Millisecond,
DialOptions: []grpc.DialOption{grpc.WithInsecure()},
}
client := cc.NewAgentClientSet(stopCh)
client.Serve()
return client
}