forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_test.go
1210 lines (1146 loc) · 34 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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"math/rand"
"net"
"os"
"regexp"
"runtime"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"golang.org/x/time/rate"
"github.com/contentsquare/chproxy/cache"
"net/http"
"net/http/httptest"
"net/url"
"github.com/contentsquare/chproxy/config"
"github.com/stretchr/testify/assert"
)
var nbHeavyRequestsInflight int64 = 0
var nbRequestsInflight int64 = 0
var totalNbOfRequests uint64 = 0
var shouldStop uint64 = 0
const max_concurrent_goroutines = 256
const heavyRequestDuration = time.Millisecond * 512
const defaultUsername = "default"
const (
okResponse = "1"
badGatewayResponse = "]: cannot reach 127.0.0.1:"
)
const testCacheDir = "./test-cache-data"
var goodCfg = &config.Config{
Server: config.Server{
Metrics: config.Metrics{
Namespace: "proxy_test"},
},
Clusters: []config.Cluster{
{
Name: "cluster",
Scheme: "http",
Replicas: []config.Replica{
{
Nodes: []string{"localhost:8123"},
},
},
ClusterUsers: []config.ClusterUser{
{
Name: "web",
},
},
},
},
Users: []config.User{
{
Name: defaultUsername,
ToCluster: "cluster",
ToUser: "web",
},
},
ParamGroups: []config.ParamGroup{
{Name: "param_test", Params: []config.Param{{Key: "param_key", Value: "param_value"}}},
},
}
var goodCfgWithCache = &config.Config{
Clusters: []config.Cluster{
{
Name: "cluster",
Scheme: "http",
Replicas: []config.Replica{
{
Nodes: []string{"localhost:8123"},
},
},
ClusterUsers: []config.ClusterUser{
{
Name: "web",
},
},
},
},
Users: []config.User{
{
Name: defaultUsername,
ToCluster: "cluster",
ToUser: "web",
Cache: "file_system_cache",
},
},
ParamGroups: []config.ParamGroup{
{Name: "param_test", Params: []config.Param{{Key: "param_key", Value: "param_value"}}},
},
Caches: []config.Cache{
{
Name: "file_system_cache",
Mode: "file_system",
FileSystem: config.FileSystemCacheConfig{
Dir: testCacheDir,
MaxSize: config.ByteSize(1024 * 1024),
},
Expire: config.Duration(1000 * 60 * 60),
},
},
}
func newConfiguredProxy(cfg *config.Config) (*reverseProxy, error) {
p := newReverseProxy(&cfg.ConnectionPool)
if err := p.applyConfig(cfg); err != nil {
return p, fmt.Errorf("error while loading config: %s", err)
}
return p, nil
}
func init() {
// we need to initiliaze prometheus metrics
// otherwise the calls the proxy.applyConfig will fail
// due to memory issues if someone only runs proxy_test
registerMetrics(goodCfg)
}
func TestNewReverseProxy(t *testing.T) {
proxy := newReverseProxy(&goodCfg.ConnectionPool)
if err := proxy.applyConfig(goodCfg); err != nil {
t.Fatalf("error while loading config: %s", err)
}
if len(proxy.clusters) != 1 {
t.Fatalf("got %d hosts; expResponse: %d", len(proxy.clusters), 1)
}
c := proxy.clusters["cluster"]
r := c.replicas[0]
if len(r.hosts) != 1 {
t.Fatalf("got %d hosts; expResponse: %d", len(r.hosts), 1)
}
if r.hosts[0].Host() != "localhost:8123" {
t.Fatalf("got %s host; expResponse: %s", r.hosts[0].Host(), "localhost:8123")
}
if len(proxy.users) != 1 {
t.Fatalf("got %d users; expResponse: %d", len(proxy.users), 1)
}
if _, ok := proxy.users[defaultUsername]; !ok {
t.Fatalf("expected user %q to be present in users", defaultUsername)
}
}
var badCfg = &config.Config{
Clusters: []config.Cluster{
{
Name: "badCfg",
Scheme: "http",
Nodes: []string{"localhost:8123"},
ClusterUsers: []config.ClusterUser{
{
Name: defaultUsername,
},
},
},
},
Users: []config.User{
{
Name: defaultUsername,
ToCluster: "cluster",
ToUser: "foo",
},
},
}
var badCfgWithNoHeartBeatUser = &config.Config{
Clusters: []config.Cluster{
{
Name: "badCfgWithNoHeartBeatUser",
Scheme: "http",
Nodes: []string{"localhost:8123"},
ClusterUsers: []config.ClusterUser{
{
Name: defaultUsername,
},
},
HeartBeat: config.HeartBeat{
Request: "/not_ping",
},
},
},
Users: []config.User{
{
Name: "analyst_*",
IsWildcarded: true,
ToCluster: "badCfgWithNoHeartBeatUser",
ToUser: defaultUsername,
},
},
}
func TestApplyConfig(t *testing.T) {
proxy, err := newConfiguredProxy(goodCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if err = proxy.applyConfig(badCfg); err == nil {
t.Fatalf("error expected; got nil")
}
if _, ok := proxy.clusters["badCfg"]; ok {
t.Fatalf("bad config applied; expected previous config")
}
if err := proxy.applyConfig(badCfgWithNoHeartBeatUser); err == nil {
t.Fatalf("error expected; got nil")
} else if err.Error() != "`cluster.heartbeat.user ` cannot be unset for \"badCfgWithNoHeartBeatUser\" because a wildcarded user cannot send heartbeat" {
t.Fatalf("unexpected error %s", err.Error())
}
if _, ok := proxy.clusters["badCfgWithNoHeartBeatUser"]; ok {
t.Fatalf("bad config applied; expected previous config")
}
}
var authCfg = &config.Config{
Clusters: []config.Cluster{
{
Name: "cluster",
Scheme: "http",
Nodes: []string{"localhost:8123"},
ClusterUsers: []config.ClusterUser{
{
Name: "web",
Password: "webpass",
},
},
},
},
Users: []config.User{
{
Name: "foo",
Password: "bar",
ToCluster: "cluster",
ToUser: "web",
},
},
}
var wildcardedCfg = &config.Config{
Clusters: []config.Cluster{
{
Name: "cluster",
Scheme: "http",
Nodes: []string{"localhost:8123"},
ClusterUsers: []config.ClusterUser{
{
Name: "web",
Password: "webpass",
},
{
Name: "analyst_*",
},
{
Name: "*-UK",
},
},
},
},
Users: []config.User{
{
Name: "analyst_*",
ToCluster: "cluster",
ToUser: "analyst_*",
IsWildcarded: true,
},
{
Name: "*-UK",
ToCluster: "cluster",
ToUser: "*-UK",
IsWildcarded: true,
},
},
}
var fullWildcardedCfg = &config.Config{
Clusters: []config.Cluster{
{
Name: "cluster",
Scheme: "http",
Nodes: []string{"localhost:8123"},
ClusterUsers: []config.ClusterUser{
{
Name: "web",
Password: "webpass",
},
{
Name: "*",
},
},
},
},
Users: []config.User{
{
Name: "*",
ToCluster: "cluster",
ToUser: "*",
IsWildcarded: true,
},
},
}
func TestReverseProxy_ServeHTTP1(t *testing.T) {
testCases := []struct {
cfg *config.Config
name string
expResponse string
expStatusCode int
f func(p *reverseProxy) *http.Response
}{
{
cfg: goodCfg,
name: "Bad gatway response without cache",
expResponse: badGatewayResponse,
expStatusCode: http.StatusBadGateway,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("GET", fmt.Sprintf("%s/badGateway?query=SELECT123456", fakeServer.URL), nil)
return makeCustomRequest(p, req)
},
},
{
cfg: goodCfgWithCache,
name: "Bad gatway response with cache",
expResponse: badGatewayResponse,
expStatusCode: http.StatusBadGateway,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("GET", fmt.Sprintf("%s/badGateway?query=SELECT123456", fakeServer.URL), nil)
// cleaning the cache to be sure it will be a cache miss although the query isn't supposed to be cached
os.RemoveAll(testCacheDir)
return makeCustomRequest(p, req)
},
},
{
cfg: goodCfg,
name: "Ok response",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response { return makeRequest(p) },
},
{
cfg: goodCfg,
name: "max concurrent queries for cluster user",
expResponse: "limits for cluster user \"web\" are exceeded: max_concurrent_queries limit: 1;",
expStatusCode: http.StatusTooManyRequests,
f: func(p *reverseProxy) *http.Response {
p.clusters["cluster"].users["web"].maxConcurrentQueries = 1
runHeavyRequestInGoroutine(p, 1, true)
return makeRequest(p)
},
},
{
cfg: goodCfg,
name: "max time for cluster user",
expResponse: "timeout for cluster user \"web\" exceeded: 10ms",
expStatusCode: http.StatusGatewayTimeout,
f: func(p *reverseProxy) *http.Response {
p.clusters["cluster"].users["web"].maxExecutionTime = time.Millisecond * 10
return makeHeavyRequest(p, time.Millisecond*20)
},
},
{
cfg: goodCfg,
name: "choose max time between users",
expResponse: fmt.Sprintf("timeout for user \"%s\" exceeded: 10ms", defaultUsername),
expStatusCode: http.StatusGatewayTimeout,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxExecutionTime = time.Millisecond * 10
p.clusters["cluster"].users["web"].maxExecutionTime = time.Millisecond * 15
return makeHeavyRequest(p, time.Millisecond*20)
},
},
{
cfg: goodCfg,
name: "choose max time between users2",
expResponse: "timeout for cluster user \"web\" exceeded: 10ms",
expStatusCode: http.StatusGatewayTimeout,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxExecutionTime = time.Millisecond * 15
p.clusters["cluster"].users["web"].maxExecutionTime = time.Millisecond * 10
return makeHeavyRequest(p, time.Millisecond*20)
},
},
{
cfg: goodCfg,
name: "max concurrent queries for user",
expResponse: fmt.Sprintf("limits for user \"%s\" are exceeded: max_concurrent_queries limit: 1;", defaultUsername),
expStatusCode: http.StatusTooManyRequests,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxConcurrentQueries = 1
runHeavyRequestInGoroutine(p, 1, true)
return makeRequest(p)
},
},
{
cfg: goodCfg,
name: "queuing queries for user",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxConcurrentQueries = 1
p.users[defaultUsername].queueCh = make(chan struct{}, 2)
runHeavyRequestInGoroutine(p, 1, true)
return makeRequest(p)
},
},
{
cfg: goodCfg,
name: "queuing queries for cluster user",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxConcurrentQueries = 1
p.clusters["cluster"].users["web"].queueCh = make(chan struct{}, 2)
runHeavyRequestInGoroutine(p, 1, true)
return makeRequest(p)
},
},
{
cfg: goodCfg,
name: "max payload size limit",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
p.caches["max_payload_size"] = &cache.AsyncCache{
MaxPayloadSize: 8 * 1024 * 1024,
}
p.users[defaultUsername].cache = p.caches["max_payload_size"]
return makeRequest(p)
},
},
{
cfg: goodCfg,
name: "queue overflow for user",
expResponse: fmt.Sprintf("limits for user \"%s\" are exceeded: max_concurrent_queries limit: 1", defaultUsername),
expStatusCode: http.StatusTooManyRequests,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxConcurrentQueries = 1
p.users[defaultUsername].queueCh = make(chan struct{}, 1)
// we don't wait the requests to be handled by the fakeServer because one of them will be enqueued and not handled
// this is why we handle this part manually
nbRequest := atomic.LoadUint64(&totalNbOfRequests)
runHeavyRequestInGoroutine(p, 2, false)
counter := 0
for atomic.LoadUint64(&totalNbOfRequests) < nbRequest+2 && counter < 200 {
time.Sleep(1 * time.Millisecond)
counter++
}
return makeRequest(p)
},
},
{
cfg: authCfg,
name: "disallow https",
expResponse: "user \"foo\" is not allowed to access via https",
expStatusCode: http.StatusForbidden,
f: func(p *reverseProxy) *http.Response {
p.users["foo"].denyHTTPS = true
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.SetBasicAuth("foo", "bar")
req.TLS = &tls.ConnectionState{
Version: tls.VersionTLS12,
HandshakeComplete: true,
}
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "basic auth ok",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.SetBasicAuth("foo", "bar")
return makeCustomRequest(p, req)
},
},
{
cfg: goodCfg,
name: "disallow http",
expResponse: fmt.Sprintf("user \"%s\" is not allowed to access via http", defaultUsername),
expStatusCode: http.StatusForbidden,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].denyHTTP = true
return makeRequest(p)
},
},
{
cfg: authCfg,
name: "basic auth wrong name",
expResponse: "invalid username or password for user \"fooo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.SetBasicAuth("fooo", "bar")
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "basic auth wrong pass",
expResponse: "invalid username or password for user \"foo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.SetBasicAuth("foo", "baar")
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "auth ok",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
uri := fmt.Sprintf("%s?user=foo&password=bar", fakeServer.URL)
req := httptest.NewRequest("POST", uri, nil)
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "auth wrong name",
expResponse: "invalid username or password for user \"fooo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
uri := fmt.Sprintf("%s?user=fooo&password=bar", fakeServer.URL)
req := httptest.NewRequest("POST", uri, nil)
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "auth wrong name",
expResponse: "invalid username or password for user \"foo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
uri := fmt.Sprintf("%s?user=foo&password=baar", fakeServer.URL)
req := httptest.NewRequest("POST", uri, nil)
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "headers auth ok",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "foo")
req.Header.Set("X-ClickHouse-Key", "bar")
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "header auth wrong name",
expResponse: "invalid username or password for user \"fooo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "fooo")
req.Header.Set("X-ClickHouse-Key", "bar")
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "header auth wrong name",
expResponse: "invalid username or password for user \"foo\"",
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "foo")
req.Header.Set("X-ClickHouse-Key", "baar")
return makeCustomRequest(p, req)
},
},
{
cfg: authCfg,
name: "post request max payload size",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
uri := fmt.Sprintf("%s?user=foo&password=bar", fakeServer.URL)
req := httptest.NewRequest("POST", uri, nil)
p.caches["max_payload_size"] = &cache.AsyncCache{
MaxPayloadSize: 8 * 1024 * 1024,
}
p.users["foo"].cache = p.caches["max_payload_size"]
return makeCustomRequest(p, req)
},
},
{
cfg: wildcardedCfg,
name: "wildcarded Ok1",
expResponse: "user: analyst_jane, password: jane_pass\n" + okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "analyst_jane")
req.Header.Set("X-ClickHouse-Key", "jane_pass")
return makeCustomRequest(p, req)
},
},
{
cfg: wildcardedCfg,
name: "wildcarded Ok2",
expResponse: "user: john-UK, password: john_pass\n" + okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "john-UK")
req.Header.Set("X-ClickHouse-Key", "john_pass")
return makeCustomRequest(p, req)
},
},
{
cfg: fullWildcardedCfg,
name: "wildcarded Ok3",
expResponse: "user: toto, password: titi\n" + okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", "toto")
req.Header.Set("X-ClickHouse-Key", "titi")
return makeCustomRequest(p, req)
},
},
{
cfg: fullWildcardedCfg,
name: "wildcarded Ko for default user",
expResponse: fmt.Sprintf("invalid username or password for user \"%s\"", defaultUsername),
expStatusCode: http.StatusUnauthorized,
f: func(p *reverseProxy) *http.Response {
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.Header.Set("X-ClickHouse-User", defaultUsername)
req.Header.Set("X-ClickHouse-Key", "")
return makeCustomRequest(p, req)
},
},
{
cfg: goodCfg,
name: "request packet size token limit for user",
expResponse: "limits for user \"default\" is exceeded: request_packet_size_tokens_burst limit: 4",
expStatusCode: http.StatusTooManyRequests,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].reqPacketSizeTokensBurst = 4
p.users[defaultUsername].reqPacketSizeTokenLimiter = rate.NewLimiter(
rate.Limit(1), 4)
go makeHeavyRequest(p, time.Millisecond*20)
return makeHeavyRequest(p, time.Millisecond*200)
},
},
{
cfg: goodCfg,
name: "request packet size token limit for cluster user",
expResponse: "limits for cluster user \"web\" is exceeded: request_packet_size_tokens_burst limit: 4",
expStatusCode: http.StatusTooManyRequests,
f: func(p *reverseProxy) *http.Response {
p.clusters["cluster"].users["web"].reqPacketSizeTokensBurst = 4
p.clusters["cluster"].users["web"].reqPacketSizeTokenLimiter = rate.NewLimiter(
rate.Limit(1), 4)
go makeHeavyRequest(p, time.Millisecond*20)
return makeHeavyRequest(p, time.Millisecond*200)
},
},
{
cfg: goodCfg,
name: "queuing request packet size token limit for user",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].reqPacketSizeTokensBurst = 5
p.users[defaultUsername].reqPacketSizeTokenLimiter = rate.NewLimiter(
rate.Limit(1), 5)
p.users[defaultUsername].queueCh = make(chan struct{}, 2)
p.users[defaultUsername].maxQueueTime = 10 * time.Second
runHeavyRequestInGoroutine(p, 1, true)
return makeHeavyRequest(p, time.Millisecond*200)
},
},
{
cfg: goodCfg,
name: "queuing request with packet size token limit for cluster user",
expResponse: okResponse,
expStatusCode: http.StatusOK,
f: func(p *reverseProxy) *http.Response {
p.clusters["cluster"].users["web"].reqPacketSizeTokensBurst = 5
p.clusters["cluster"].users["web"].reqPacketSizeTokenLimiter = rate.NewLimiter(
rate.Limit(1), 5)
p.clusters["cluster"].users["web"].queueCh = make(chan struct{}, 2)
p.clusters["cluster"].users["web"].maxQueueTime = 10 * time.Second
runHeavyRequestInGoroutine(p, 1, true)
return makeHeavyRequest(p, time.Millisecond*200)
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
stopAllRequestsInFlight()
proxy, err := getProxy(tc.cfg)
if err != nil {
t.Fatalf("unexpected error: %s for %q", err, tc.name)
}
resp := tc.f(proxy)
b := bbToString(t, resp.Body)
resp.Body.Close()
if !strings.Contains(b, tc.expResponse) {
t.Fatalf("expected response: %q; got: %q for %q", tc.expResponse, b, tc.name)
}
if tc.expStatusCode != resp.StatusCode {
t.Fatalf("unexpected status code: %d; expected: %d for %q", resp.StatusCode, tc.expStatusCode, tc.name)
}
})
}
t.Run("basicauth success", func(t *testing.T) {
proxy, err := getProxy(authCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
req := httptest.NewRequest("POST", fakeServer.URL, nil)
req.SetBasicAuth("foo", "bar")
resp := makeCustomRequest(proxy, req)
expected := okResponse
b := bbToString(t, resp.Body)
if !strings.Contains(b, expected) {
t.Fatalf("expected response: %q; got: %q", expected, b)
}
resp.Body.Close()
user, pass := getAuth(req)
if user != authCfg.Clusters[0].ClusterUsers[0].Name {
t.Fatalf("user name expected to be %q; got %q", authCfg.Clusters[0].ClusterUsers[0].Name, user)
}
if pass != authCfg.Clusters[0].ClusterUsers[0].Password {
t.Fatalf("user password expected to be %q; got %q", authCfg.Clusters[0].ClusterUsers[0].Password, pass)
}
})
t.Run("auth success", func(t *testing.T) {
proxy, err := getProxy(authCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
uri := fmt.Sprintf("%s?user=foo&password=bar", fakeServer.URL)
req := httptest.NewRequest("POST", uri, nil)
resp := makeCustomRequest(proxy, req)
expected := okResponse
b := bbToString(t, resp.Body)
if !strings.Contains(b, expected) {
t.Fatalf("expected response: %q; got: %q", expected, b)
}
resp.Body.Close()
user, pass := getAuth(req)
if user != authCfg.Clusters[0].ClusterUsers[0].Name {
t.Fatalf("user name expected to be %q; got %q", authCfg.Clusters[0].ClusterUsers[0].Name, user)
}
if pass != authCfg.Clusters[0].ClusterUsers[0].Password {
t.Fatalf("user password expected to be %q; got %q", authCfg.Clusters[0].ClusterUsers[0].Password, pass)
}
})
}
func TestKillQuery(t *testing.T) {
testCases := []struct {
name string
f func(p *reverseProxy) *http.Response
}{
{
name: "timeout user",
f: func(p *reverseProxy) *http.Response {
p.users[defaultUsername].maxExecutionTime = time.Millisecond * 5
return makeHeavyRequest(p, time.Millisecond*40)
},
},
{
name: "timeout cluster user",
f: func(p *reverseProxy) *http.Response {
p.clusters["cluster"].users["web"].maxExecutionTime = time.Millisecond * 5
return makeHeavyRequest(p, time.Millisecond*40)
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
proxy, err := getProxy(goodCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
resp := tc.f(proxy)
b := bbToString(t, resp.Body)
id := extractID(scopeIDRe, b)
if len(id) == 0 {
t.Fatalf("expected Id to be extracted from %q", b)
}
// waiting btw 5 and 200 msec to get the answer from CHProxy
// because this code on github is unstable due to the poor performances
// of the server running the CI.
loop := true
counter := 0
for loop {
time.Sleep(time.Millisecond * 5)
counter++
_, err := registry.get(id)
if err == nil || counter > 40 {
loop = false
}
}
state, err := registry.get(id)
if err != nil {
t.Fatalf("unexpected requestRegistry err for key %q: %s", id, err)
}
if !state {
t.Fatalf("query expected to be killed; response: %s", b)
}
})
}
}
func TestReverseProxy_ServeHTTPConcurrent(t *testing.T) {
addr, err := url.Parse(fakeServer.URL)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
goodCfg.Clusters[0].Nodes = []string{addr.Host}
proxy, err := newConfiguredProxy(goodCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
t.Run("parallel requests", func(t *testing.T) {
f := func() {
req := httptest.NewRequest("GET", fmt.Sprintf("%s/fast", fakeServer.URL), nil)
makeCustomRequest(proxy, req)
}
if err := testConcurrent(f, 500); err != nil {
t.Fatalf("concurrent test err: %s", err)
}
})
t.Run("parallel requests with config reloading", func(t *testing.T) {
f := func() {
proxy.applyConfig(newConfig())
req := httptest.NewRequest("GET", fmt.Sprintf("%s/fast", fakeServer.URL), nil)
makeCustomRequest(proxy, req)
}
if err := testConcurrent(f, 100); err != nil {
t.Fatalf("concurrent test err: %s", err)
}
})
}
func TestReverseProxy_ServeHTTP2(t *testing.T) {
testCases := []struct {
name string
allowedNetworks config.Networks
expResponse string
}{
{
name: "empty allowed networks",
allowedNetworks: config.Networks{},
},
{
name: "allow addr",
allowedNetworks: config.Networks{getNetwork("192.0.2.1")},
},
{
name: "allow addr by mask",
allowedNetworks: config.Networks{getNetwork("192.0.2.1/32")},
},
}
f := func(cfg *config.Config) {
proxy, err := getProxy(cfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
resp := makeRequest(proxy)
b := bbToString(t, resp.Body)
resp.Body.Close()
if !strings.Contains(b, okResponse) {
t.Fatalf("expected response: %q; got: %q", okResponse, b)
}
}
for _, tc := range testCases {
t.Run("user "+tc.name, func(t *testing.T) {
goodCfg.Users[0].AllowedNetworks = tc.allowedNetworks
f(goodCfg)
})
t.Run("cluster user "+tc.name, func(t *testing.T) {
goodCfg.Clusters[0].ClusterUsers[0].AllowedNetworks = tc.allowedNetworks
f(goodCfg)
})
}
t.Run("cluster user disallow addr", func(t *testing.T) {
goodCfg.Clusters[0].ClusterUsers[0].AllowedNetworks = config.Networks{getNetwork("192.0.2.2/32"), getNetwork("192.0.2.2")}
proxy, err := getProxy(goodCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
resp := makeRequest(proxy)
expected := "cluster user \"web\" is not allowed to access"
b := bbToString(t, resp.Body)
resp.Body.Close()
if !strings.Contains(b, expected) {
t.Fatalf("expected response: %q; got: %q", expected, b)
}
})
t.Run("user disallow addr", func(t *testing.T) {
goodCfg.Users[0].AllowedNetworks = config.Networks{getNetwork("192.0.2.2/32"), getNetwork("192.0.2.2")}
proxy, err := getProxy(goodCfg)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
resp := makeRequest(proxy)
expected := fmt.Sprintf("user \"%s\" is not allowed to access", defaultUsername)
b := bbToString(t, resp.Body)
resp.Body.Close()
if !strings.Contains(b, expected) {
t.Fatalf("expected response: %q; got: %q", expected, b)
}
})
}
func getNetwork(s string) *net.IPNet {
if !strings.Contains(s, `/`) {
s += "/32"
}
_, ipnet, _ := net.ParseCIDR(s)
return ipnet
}
const killQueryPattern = "KILL QUERY WHERE query_id"
var (
// quick fix until the test file is refactored.
// Many tests rely on concurrency of goroutines.
// But, because of the use of sleep, only a few goroutine can run in concurrence and the other are blocked
// cf: https://stackoverflow.com/questions/62527705/will-time-sleep-block-goroutine
// Because of that, on most tests the goroutines are running sequencially
// This id why we increase the number concurrent goroutines (the default number is the number of cpu of the computer running the tests, which is quite low on github actions)
// we must increase this number before the instanciation of the fakeServer, otherwise it's not taken into account during the tests
_ = increaseMaxConccurentGoroutine()
registry = newRequestRegistry()
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt64(&nbRequestsInflight, 1)
defer atomic.AddInt64(&nbRequestsInflight, -1)
if r.URL.Path == "/fast" {
fmt.Fprintln(w, okResponse)
return
}
if r.URL.Path == "/badGateway" {
w.WriteHeader(http.StatusBadGateway)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
panic(err)
}
b := string(body)
r.Body.Close()
if n, p, found := r.BasicAuth(); found {
fmt.Fprintf(w, "user: %s, password: %s\n", n, p)
}
qid := r.URL.Query().Get("query_id")
if len(qid) == 0 && len(b) == 0 {
// it's could be a health-check
fmt.Fprintln(w, okResponse)
return
}
registry.set(qid, false)
if len(b) != 0 {
if strings.Contains(b, killQueryPattern) {
qid = extractID(queryIDRe, b)
registry.set(qid, true)
} else {