forked from ContentSquare/chproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
1220 lines (1126 loc) · 36 KB
/
main_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"
"compress/gzip"
"context"
"crypto/tls"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"os"
"regexp"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/contentsquare/chproxy/cache"
"github.com/contentsquare/chproxy/config"
"github.com/contentsquare/chproxy/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/stretchr/testify/assert"
"github.com/contentsquare/chproxy/global/types"
)
var (
testDir = "./temp-test-data"
labels = prometheus.Labels{}
redisPort = types.RedisPort
chPort = types.ClickHousePort
)
func TestMain(m *testing.M) {
log.SuppressOutput(true)
retCode := m.Run()
log.SuppressOutput(false)
if err := os.RemoveAll(testDir); err != nil {
log.Fatalf("cannot remove %q: %s", testDir, err)
}
if redisClient != nil {
redisClient.Close()
}
os.Exit(retCode)
}
var redisClient *miniredis.Miniredis
func TestServe(t *testing.T) {
expectedOkResp := "Ok.\n"
var testCases = []struct {
name string
file string
testFn func(t *testing.T)
listenFn func() (*http.Server, chan struct{})
}{
{
"https request",
"testdata/https.yml",
func(t *testing.T) {
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusUnauthorized)
}
resp.Body.Close()
req, err = http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err = tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
resp.Body.Close()
},
startTLS,
},
{
"https cache",
"testdata/https.cache.yml",
func(t *testing.T) {
// do request which response must be cached
q := "SELECT 123"
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(q), nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
checkResponse(t, resp.Body, expectedOkResp)
checkHeader(t, resp, "X-Cache", "MISS")
// check cached response
credHash, _ := calcCredentialHash("default", "qwerty")
key := &cache.Key{
Query: []byte(q),
AcceptEncoding: "gzip",
Version: cache.Version,
UserCredentialHash: credHash,
}
path := fmt.Sprintf("%s/cache/%s", testDir, key.String())
if _, err := os.Stat(path); err != nil {
t.Fatalf("err while getting file %q info: %s", path, err)
}
rw := httptest.NewRecorder()
cc := proxy.caches["https_cache"]
cachedData, err := cc.Get(key)
if err != nil {
t.Fatalf("unexpected error while getting response from cache: %s", err)
}
err = RespondWithData(rw, cachedData.Data, cachedData.ContentMetadata, cachedData.Ttl, XCacheHit, 200, labels)
if err != nil {
t.Fatalf("unexpected error while getting response from cache: %s", err)
}
checkResponse(t, rw.Body, expectedOkResp)
checkHeader(t, rw.Result(), "X-Cache", XCacheHit)
},
startTLS,
},
{
"https cache max payload size",
"testdata/https.cache.max-payload-size.yml",
func(t *testing.T) {
q := "SELECT MaxPayloadSize"
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(q), nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
req.Close = true
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
checkResponse(t, resp.Body, expectedOkResp)
checkHeader(t, resp, "X-Cache", XCacheNA)
key := &cache.Key{
Query: []byte(q),
AcceptEncoding: "gzip",
Version: cache.Version,
}
cc := proxy.caches["https_cache_max_payload_size"]
cachedData, err := cc.Get(key)
if cachedData != nil || err == nil {
t.Fatal("response bigger than maxPayloadSize should not be cached")
}
resp.Body.Close()
},
startTLS,
},
{
"https cache max payload size not reached",
"testdata/https.cache.max-payload-size-not-reached.yml",
func(t *testing.T) {
q := "SELECT MaxPayloadSize"
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(q), nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
req.Close = true
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
checkResponse(t, resp.Body, expectedOkResp)
credHash, _ := calcCredentialHash("default", "qwerty")
key := &cache.Key{
Query: []byte(q),
AcceptEncoding: "gzip",
Version: cache.Version,
UserCredentialHash: credHash,
}
rw := httptest.NewRecorder()
cc := proxy.caches["https_cache_max_payload_size"]
cachedData, err := cc.Get(key)
if err != nil {
t.Fatalf("unexpected error while getting response from cache: %s", err)
}
err = RespondWithData(rw, cachedData.Data, cachedData.ContentMetadata, cachedData.Ttl, XCacheHit, 200, labels)
if err != nil {
t.Fatalf("unexpected error while getting response from cache: %s", err)
}
checkResponse(t, rw.Body, expectedOkResp)
cachedData.Data.Close()
resp.Body.Close()
},
startTLS,
},
{
"https cache with mix query source",
"testdata/https.cache.yml",
func(t *testing.T) {
// do request which response must be cached
queryURLParam := "SELECT * FROM system.numbers"
queryBody := "LIMIT 10"
expectedQuery := queryURLParam + "\n" + queryBody
buf := bytes.NewBufferString(queryBody)
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(queryURLParam), buf)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
resp.Body.Close()
// check cached response
credHash, _ := calcCredentialHash("default", "qwerty")
key := &cache.Key{
Query: []byte(expectedQuery),
AcceptEncoding: "gzip",
Version: cache.Version,
UserCredentialHash: credHash,
}
path := fmt.Sprintf("%s/cache/%s", testDir, key.String())
if _, err := os.Stat(path); err != nil {
t.Fatalf("err while getting file %q info: %s", path, err)
}
rw := httptest.NewRecorder()
cc := proxy.caches["https_cache"]
cachedData, err := cc.Get(key)
if err != nil {
t.Fatalf("unexpected error while writing reposnse from cache: %s", err)
}
err = RespondWithData(rw, cachedData.Data, cachedData.ContentMetadata, cachedData.Ttl, XCacheMiss, 200, labels)
if err != nil {
t.Fatalf("unexpected error while getting response from cache: %s", err)
}
expected := expectedOkResp
checkResponse(t, rw.Body, expected)
},
startTLS,
},
{
"bad https cache",
"testdata/https.cache.yml",
func(t *testing.T) {
// do request which cause an error
q := "SELECT ERROR"
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(q), nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusInternalServerError {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode,
http.StatusInternalServerError)
}
resp.Body.Close()
// check cached response
credHash, _ := calcCredentialHash("default", "qwerty")
key := &cache.Key{
Query: []byte(q),
AcceptEncoding: "gzip",
Version: cache.Version,
UserCredentialHash: credHash,
}
path := fmt.Sprintf("%s/cache/%s", testDir, key.String())
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Fatalf("err while getting file %q info: %s", path, err)
}
// check refreshCacheMetrics()
req, err = http.NewRequest("GET", "https://127.0.0.1:8443/metrics", nil)
checkErr(t, err)
resp, err = tlsClient.Do(req)
if err != nil {
t.Fatalf("unexpected error while doing request: %s", err)
}
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
resp.Body.Close()
},
startTLS,
},
{
"deny https",
"testdata/https.deny.https.yml",
func(t *testing.T) {
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusForbidden)
}
expected := "user \"default\" is not allowed to access via https"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startTLS,
},
{
"https networks",
"testdata/https.networks.yml",
func(t *testing.T) {
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusForbidden)
}
expected := "https connections are not allowed from 127.0.0.1"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startTLS,
},
{
"https user networks",
"testdata/https.user.networks.yml",
func(t *testing.T) {
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusForbidden)
}
expected := "user \"default\" is not allowed to access"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startTLS,
},
{
"https cluster user networks",
"testdata/https.cluster.user.networks.yml",
func(t *testing.T) {
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query=asd", nil)
checkErr(t, err)
req.SetBasicAuth("default", "qwerty")
resp, err := tlsClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusForbidden)
}
expected := "cluster user \"web\" is not allowed to access"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startTLS,
},
{
"routing",
"testdata/http.yml",
func(t *testing.T) {
req, err := http.NewRequest(http.MethodOptions, "http://127.0.0.1:9090?query=asd", nil)
checkErr(t, err)
resp, err := http.DefaultClient.Do(req)
checkErr(t, err)
expectedAllowHeader := "GET,POST"
if resp.Header.Get("Allow") != expectedAllowHeader {
t.Fatalf("header `Allow` got: %q; expected: %q", resp.Header.Get("Allow"), expectedAllowHeader)
}
resp.Body.Close()
req, err = http.NewRequest(http.MethodConnect, "http://127.0.0.1:9090?query=asd", nil)
checkErr(t, err)
resp, err = http.DefaultClient.Do(req)
checkErr(t, err)
expected := fmt.Sprintf("unsupported method %q", http.MethodConnect)
checkResponse(t, resp.Body, expected)
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusMethodNotAllowed)
}
resp.Body.Close()
resp = httpGet(t, "http://127.0.0.1:9090/foobar", http.StatusBadRequest)
expected = fmt.Sprintf("unsupported path: \"/foobar\"")
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http POST request with session id",
"testdata/http-session-id.yml",
func(t *testing.T) {
req, err := http.NewRequest("POST",
"http://127.0.0.1:9090/?query_id=45395792-a432-4b92-8cc9-536c14e1e1a9&extremes=0&session_id=default-session-id233",
bytes.NewBufferString("SELECT * FROM system.numbers LIMIT 10"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded;") // This makes it work
checkErr(t, err)
resp, err := http.DefaultClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK || resp.StatusCode != http.StatusOK && resp.Header.Get("X-Clickhouse-Server-Session-Id") == "" {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
resp.Body.Close()
},
startHTTP,
},
{
"http request",
"testdata/http.yml",
func(t *testing.T) {
httpGet(t, "http://127.0.0.1:9090?query=asd", http.StatusOK)
httpGet(t, "http://127.0.0.1:9090/metrics", http.StatusOK)
},
startHTTP,
},
{
"http requests with caching in redis ",
"testdata/http.cache.redis.yml",
func(t *testing.T) {
q := "SELECT redis_cache_mate"
req, err := http.NewRequest("GET", "http://127.0.0.1:9090?query="+url.QueryEscape(q), nil)
checkErr(t, err)
keys := redisClient.Keys()
// redis should be empty before the test
if len(keys) != 0 {
t.Fatalf("unexpected amount of keys in redis: %v", len(keys))
}
resp, err := httpRequest(t, req, http.StatusOK)
checkErr(t, err)
checkResponse(t, resp.Body, expectedOkResp)
resp2, err := httpRequest(t, req, http.StatusOK)
checkErr(t, err)
checkResponse(t, resp2.Body, expectedOkResp)
keys = redisClient.Keys()
if len(keys) != 2 { // expected 2 because there is a record stored for transaction and a cache item
t.Fatalf("unexpected amount of keys in redis: %v", len(keys))
}
// check cached response
credHash, _ := calcCredentialHash("default", "")
key := &cache.Key{
Query: []byte(q),
AcceptEncoding: "gzip",
Version: cache.Version,
UserCredentialHash: credHash,
}
duration := redisClient.TTL(key.String())
if duration > 1*time.Minute || duration < 30*time.Second {
t.Fatalf("ttl on redis key was wrongly set: %s", duration.String())
}
},
startHTTP,
},
{
"http requests with caching in redis (testcase for base64 encoding/decoding)",
"testdata/http.cache.redis.yml",
func(t *testing.T) {
redisClient.FlushAll()
q := "SELECT 1 FORMAT TabSeparatedWithNamesAndTypes"
keys := redisClient.Keys()
// redis should be empty before the test
if len(keys) != 0 {
t.Fatalf("unexpected amount of keys in redis: %v", len(keys))
}
req, err := http.NewRequest("GET", "http://127.0.0.1:9090?query="+url.QueryEscape(q), nil)
checkErr(t, err)
resp, err := httpRequest(t, req, http.StatusOK)
checkErr(t, err)
checkResponse(t, resp.Body, string(bytesWithInvalidUTFPairs))
resp2, err := httpRequest(t, req, http.StatusOK)
checkErr(t, err)
// if we do not use base64 to encode/decode the cached payload, EOF error will be thrown here.
checkResponse(t, resp2.Body, string(bytesWithInvalidUTFPairs))
keys = redisClient.Keys()
if len(keys) != 2 { // 2 because there is a record stored for transaction, and a cache item
t.Fatalf("unexpected amount of keys in redis: %v", len(keys))
}
},
startHTTP,
},
{
"http gzipped POST request",
"testdata/http.cache.yml",
func(t *testing.T) {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write([]byte("SELECT * FROM system.numbers LIMIT 10"))
checkErr(t, err)
zw.Close()
req, err := http.NewRequest("POST", "http://127.0.0.1:9090", &buf)
checkErr(t, err)
req.Header.Set("Content-Encoding", "gzip")
resp, err := http.DefaultClient.Do(req)
checkErr(t, err)
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d; body: %s", resp.StatusCode, http.StatusOK,
string(body))
}
resp.Body.Close()
},
startHTTP,
},
{
"http POST request",
"testdata/http.yml",
func(t *testing.T) {
buf := bytes.NewBufferString("SELECT * FROM system.numbers LIMIT 10")
req, err := http.NewRequest("POST", "http://127.0.0.1:9090", buf)
checkErr(t, err)
resp, err := http.DefaultClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
resp.Body.Close()
},
startHTTP,
},
{
"http gzipped POST execution time",
"testdata/http.execution.time.yml",
func(t *testing.T) {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write([]byte("SELECT * FROM system.numbers LIMIT 1000"))
checkErr(t, err)
zw.Close()
req, err := http.NewRequest("POST", "http://127.0.0.1:9090", &buf)
checkErr(t, err)
req.Header.Set("Content-Encoding", "gzip")
resp, err := http.DefaultClient.Do(req)
checkErr(t, err)
if resp.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusGatewayTimeout)
}
resp.Body.Close()
},
startHTTP,
},
{
"deny http",
"testdata/http.deny.http.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090?query=asd", http.StatusForbidden)
expected := "user \"default\" is not allowed to access via http"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http networks",
"testdata/http.networks.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090?query=asd", http.StatusForbidden)
expected := "http connections are not allowed from 127.0.0.1"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http metrics networks",
"testdata/http.metrics.networks.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090/metrics", http.StatusForbidden)
expected := "connections to /metrics are not allowed from 127.0.0.1"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http metrics namespace",
"testdata/http.metrics.namespace.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090/metrics", http.StatusOK)
assert.GreaterOrEqual(t, len(getStringFromResponse(t, resp.Body)), 10000)
resp.Body.Close()
},
startHTTP,
},
{
"http user networks",
"testdata/http.user.networks.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090?query=asd", http.StatusForbidden)
expected := "user \"default\" is not allowed to access"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http cluster user networks",
"testdata/http.cluster.user.networks.yml",
func(t *testing.T) {
resp := httpGet(t, "http://127.0.0.1:9090?query=asd", http.StatusForbidden)
expected := "cluster user \"web\" is not allowed to access"
checkResponse(t, resp.Body, expected)
resp.Body.Close()
},
startHTTP,
},
{
"http shared cache for them user",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
// actually we can check that cache-file is shared via metrics
// but it needs additional library for doing this
// so it would be just files amount check
cacheDir := "temp-test-data/shared_cache1"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test1", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test1", http.StatusOK)
// request from different user expected to be served with already cached,
// so count of files should be the same
checkFilesCount(t, cacheDir, 1)
},
startHTTP,
},
{
"http not share cache for same user with different pwd",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
// because of the wildcarded feature that delegate the authentication to clickouse
// we can't afford to return a cached of the same user without reaching clickhouse
// if the pwd is not the same than the one used for the cached query
cacheDir := "temp-test-data/shared_cache2"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test2&password=toto", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user2_test2&password=titi", http.StatusOK)
checkFilesCount(t, cacheDir, 2)
},
startHTTP,
},
{
"http not share cache for different user",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
cacheDir := "temp-test-data/shared_cache3"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test3", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user2_test3", http.StatusOK)
checkFilesCount(t, cacheDir, 2)
},
startHTTP,
},
{
"http share cache for same user with different pwd",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
// because of the wildcarded feature that delegate the authentication to clickouse
// we can't afford to return a cached of the same user without reaching clickhouse
// if the pwd is not the same than the one used for the cached query
cacheDir := "temp-test-data/shared_cache4"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test4&password=toto", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user2_test4&password=titi", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
},
startHTTP,
},
{
"http share cache for different user",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
cacheDir := "temp-test-data/shared_cache5"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test5", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user2_test5", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
},
startHTTP,
},
{
"http not share cache for different user using wildcarded feature",
"testdata/http.shared.cache.yml",
func(t *testing.T) {
cacheDir := "temp-test-data/shared_cache6"
checkFilesCount(t, cacheDir, 0)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user1_test6", http.StatusOK)
checkFilesCount(t, cacheDir, 1)
httpGet(t, "http://127.0.0.1:9090?query=SELECT&user=user2_test6", http.StatusOK)
checkFilesCount(t, cacheDir, 2)
},
startHTTP,
},
{
"http cached gzipped deadline",
"testdata/http.cache.deadline.yml",
func(t *testing.T) {
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
_, err := zw.Write([]byte("SELECT SLEEP"))
checkErr(t, err)
zw.Close()
req, err := http.NewRequest("POST", "http://127.0.0.1:9090", &buf)
checkErr(t, err)
req.Header.Set("Content-Encoding", "gzip")
cacheDir := "temp-test-data/cache_deadline"
checkFilesCount(t, cacheDir, 0)
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond))
defer cancel()
req = req.WithContext(ctx)
_, err = http.DefaultClient.Do(req)
expErr := "context deadline exceeded"
if err == nil {
t.Fatal("expected deadline error")
}
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Fatalf("unexpected error: %s; expected: %s", err, expErr)
}
// verifies if query isn't cached and if kill query was launched.
select {
case <-fakeCHState.syncCH:
// wait while chproxy will detect that request was canceled and will drop temp file
time.Sleep(time.Millisecond * 200)
checkFilesCount(t, cacheDir, 0)
case <-time.After(time.Second * 5):
t.Fatalf("expected deadline query to be killed")
}
},
startHTTP,
},
{
"http concurrent transaction from cache",
"testdata/http.concurrent.transaction.yml",
func(t *testing.T) {
// max_exec_time = 300 ms, grace_time = 160 ms (> max_exec_time/2)
// scenario: 1st query completes before grace_time elapsed. 2nd query is served from cache.
q := "SELECT SLEEP100"
executeTwoConcurrentRequests(t, q, http.StatusOK, http.StatusOK, "success mate", "success mate")
},
startHTTP,
},
{
"http concurrent transaction failure scenario",
"testdata/http.concurrent.transaction.yml",
func(t *testing.T) {
// max_exec_time = 300 ms, grace_time = 160 ms (> max_exec_time/2)
// scenario: 1st query fails before grace_time elapsed. 2nd query fails as well.
q := "SELECT ERROR"
executeTwoConcurrentRequests(t, q, http.StatusInternalServerError, http.StatusInternalServerError,
"DB::Exception\n", "[concurrent query failed] DB::Exception\n")
},
startHTTP,
},
{
"http concurrent transaction failure scenario - transaction completed, not failed - query is recoverable",
"testdata/http.concurrent.transaction.yml",
func(t *testing.T) {
// max_exec_time = 300 ms, grace_time = 160 ms (> max_exec_time/2)
// scenario: 1st query fails before grace_time elapsed. 2nd query fails as well.
q := "SELECT RECOVERABLE-ERROR"
executeTwoConcurrentRequests(t, q, http.StatusServiceUnavailable, http.StatusServiceUnavailable,
"DB::Unavailable\n", "DB::Unavailable\n")
},
startHTTP,
},
{
"http request with default proxy headers",
"testdata/https.proxy-enabled.yml",
func(t *testing.T) {
query := "SELECT 1"
req, err := http.NewRequest("GET", "https://127.0.0.1:8443?query="+url.QueryEscape(query), nil)
checkErr(t, err)
req.Close = true
req.SetBasicAuth("default", "qwerty")
req.Header.Add("X-Forwarded-For", "10.0.0.1")
resp, err := tlsClient.Do(req)
checkErr(t, err)
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("unexpected status code: %d; expected: %d", resp.StatusCode, http.StatusOK)
}
checkResponse(t, resp.Body, expectedOkResp)
},
startTLS,
},
}
// Wait until CHServer starts.
go startCHServer()
redisClient = startRedis(t)
startTime := time.Now()
i := 0
for i < 10 {
if _, err := http.Get(fmt.Sprintf("http://127.0.0.1:%s/", chPort)); err == nil {
break
}
time.Sleep(10 * time.Millisecond)
i++
}
if i >= 10 {
t.Fatalf("CHServer didn't start in %s", time.Since(startTime))
}
cfg := &config.Config{}
registerMetrics(cfg)
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
*configFile = tc.file
s, done := tc.listenFn()
defer func() {
if err := s.Shutdown(context.Background()); err != nil {
t.Fatalf("unexpected error while closing server: %s", err)
}
<-done
}()
var c *cluster
for _, cluster := range proxy.clusters {
c = cluster
break
}
var i int
for {
if i > 3 {
t.Fatal("unable to find active hosts")
}
if h := c.getHost(); h != nil {
break
}
i++
time.Sleep(time.Millisecond * 10)
}
tc.testFn(t)
})
}
}
func checkFilesCount(t *testing.T, dir string, expectedLen int) {
files, err := os.ReadDir(dir)
if err != nil {
t.Fatalf("error while reading dir %q: %s", dir, err)
}
if expectedLen != len(files) {
t.Fatalf("expected %d files in cache dir %s; got: %d", expectedLen, dir, len(files))
}
}
var tlsClient = &http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}}
func startTLS() (*http.Server, chan struct{}) {
cfg, err := loadConfig()
if err != nil {
panic(fmt.Sprintf("error while loading config: %s", err))
}
if err = applyConfig(cfg); err != nil {
panic(fmt.Sprintf("error while applying config: %s", err))
}
done := make(chan struct{})
ln, err := net.Listen("tcp4", cfg.Server.HTTPS.ListenAddr)
if err != nil {
panic(fmt.Sprintf("cannot listen for %q: %s", cfg.Server.HTTPS.ListenAddr, err))
}
tlsCfg, err := cfg.Server.HTTPS.TLS.BuildTLSConfig(autocertManager)
if err != nil {
panic(fmt.Sprintf("cannot build TLS config: %s", err))
}
tln := tls.NewListener(ln, tlsCfg)
h := http.HandlerFunc(serveHTTP)
s := newServer(tln, h, config.TimeoutCfg{})
go func() {
s.Serve(tln)
close(done)
}()
return s, done
}
func startHTTP() (*http.Server, chan struct{}) {
cfg, err := loadConfig()
if err != nil {
panic(fmt.Sprintf("error while loading config: %s", err))
}
if err = applyConfig(cfg); err != nil {
panic(fmt.Sprintf("error while applying config: %s", err))
}
done := make(chan struct{})
ln, err := net.Listen("tcp4", cfg.Server.HTTP.ListenAddr)
if err != nil {
panic(fmt.Sprintf("cannot listen for %q: %s", cfg.Server.HTTP.ListenAddr, err))
}
h := http.HandlerFunc(serveHTTP)
s := newServer(ln, h, config.TimeoutCfg{})
go func() {
s.Serve(ln)
close(done)
}()
return s, done
}
// TODO randomise port for each instance of the mock
func startRedis(t *testing.T) *miniredis.Miniredis {
redis := miniredis.NewMiniRedis()
if err := redis.StartAddr("127.0.0.1:" + redisPort); err != nil {
t.Fatalf("Failed to create redis server: %s", err)
}
return redis
}
// TODO randomise port for each instance of the mock
func startCHServer() {
http.ListenAndServe(":"+chPort, http.HandlerFunc(fakeCHHandler))
}
var patt = regexp.MustCompile(`(\d+)$`)
func fakeCHHandler(w http.ResponseWriter, r *http.Request) {
query, err := getFullQuery(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "error while reading query: %s", err)
return
}
if len(query) == 0 && r.Method != http.MethodGet {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "got empty query for non-GET request")
return
}
defer func() {
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}()
q := string(query)
switch {
case q == "SELECT ERROR":
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprint(w, "DB::Exception\n")
case q == "SELECT RECOVERABLE-ERROR":
println("called clickhouse recoverable")
w.WriteHeader(http.StatusServiceUnavailable)
fmt.Fprint(w, "DB::Unavailable\n")
case q == "SELECT SLEEP":
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "foo")
fakeCHState.sleep()
fmt.Fprint(w, "bar")
case strings.Contains(q, "SELECT SLEEP"):
numberStrings := patt.FindAllStringSubmatch(q, -1)
if len(numberStrings) == 0 {
panic("couldn't extract number from sleep call to clickhouse mock")
}
nr, err := strconv.Atoi(numberStrings[0][1])
if err != nil {