-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
template_test.go
1955 lines (1759 loc) · 54.1 KB
/
template_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
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package template
import (
"bytes"
"encoding/base64"
"fmt"
"net"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
jsoniter "github.com/json-iterator/go"
"github.com/pmezard/go-difflib/difflib"
apiv1 "k8s.io/api/core/v1"
networking "k8s.io/api/networking/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/ingress-nginx/internal/ingress/annotations/authreq"
"k8s.io/ingress-nginx/internal/ingress/annotations/modsecurity"
"k8s.io/ingress-nginx/internal/ingress/annotations/opentelemetry"
"k8s.io/ingress-nginx/internal/ingress/annotations/ratelimit"
"k8s.io/ingress-nginx/internal/ingress/annotations/rewrite"
"k8s.io/ingress-nginx/internal/ingress/controller/config"
"k8s.io/ingress-nginx/internal/nginx"
"k8s.io/ingress-nginx/pkg/apis/ingress"
)
func init() {
// the default value of nginx.TemplatePath assumes the template exists in
// the root filesystem and not in the rootfs directory
absPath, err := filepath.Abs(filepath.Join("..", "..", "..", "..", "rootfs", nginx.TemplatePath))
if err == nil {
nginx.TemplatePath = absPath
}
}
var (
pathPrefix networking.PathType = networking.PathTypePrefix
// TODO: add tests for SSLPassthrough
tmplFuncTestcases = map[string]struct {
Path string
Target string
Location string
ProxyPass string
AutoHTTPProxyPass string
Sticky bool
XForwardedPrefix string
SecureBackend bool
enforceRegex bool
}{
"when secure backend enabled": {
"/",
"/",
"/",
"proxy_pass https://upstream_balancer;",
"proxy_pass https://upstream_balancer;",
false,
"",
true,
false,
},
"when secure backend and dynamic config enabled": {
"/",
"/",
"/",
"proxy_pass https://upstream_balancer;",
"proxy_pass https://upstream_balancer;",
false,
"",
true,
false,
},
"when secure backend, stickiness and dynamic config enabled": {
"/",
"/",
"/",
"proxy_pass https://upstream_balancer;",
"proxy_pass https://upstream_balancer;",
true,
"",
true,
false,
},
"invalid redirect / to / with dynamic config enabled": {
"/",
"/",
"/",
"proxy_pass http://upstream_balancer;",
"proxy_pass $scheme://upstream_balancer;",
false,
"",
false,
false,
},
"invalid redirect / to /": {
"/",
"/",
"/",
"proxy_pass http://upstream_balancer;",
"proxy_pass $scheme://upstream_balancer;",
false,
"",
false,
false,
},
"redirect / to /jenkins": {
"/",
"/jenkins",
`~* "^/"`,
`
rewrite "(?i)/" /jenkins break;
proxy_pass http://upstream_balancer;`,
`
rewrite "(?i)/" /jenkins break;
proxy_pass $scheme://upstream_balancer;`,
false,
"",
false,
true,
},
"redirect / to /something with sticky enabled": {
"/",
"/something",
`~* "^/"`,
`
rewrite "(?i)/" /something break;
proxy_pass http://upstream_balancer;`,
`
rewrite "(?i)/" /something break;
proxy_pass $scheme://upstream_balancer;`,
true,
"",
false,
true,
},
"redirect / to /something with sticky and dynamic config enabled": {
"/",
"/something",
`~* "^/"`,
`
rewrite "(?i)/" /something break;
proxy_pass http://upstream_balancer;`,
`
rewrite "(?i)/" /something break;
proxy_pass $scheme://upstream_balancer;`,
true,
"",
false,
true,
},
"add the X-Forwarded-Prefix header": {
"/there",
"/something",
`~* "^/there"`,
`
rewrite "(?i)/there" /something break;
proxy_set_header X-Forwarded-Prefix "/there";
proxy_pass http://upstream_balancer;`,
`
rewrite "(?i)/there" /something break;
proxy_set_header X-Forwarded-Prefix "/there";
proxy_pass $scheme://upstream_balancer;`,
true,
"/there",
false,
true,
},
"use ~* location modifier when ingress does not use rewrite/regex target but at least one other ingress does": {
"/something",
"/something",
`~* "^/something"`,
"proxy_pass http://upstream_balancer;",
"proxy_pass $scheme://upstream_balancer;",
false,
"",
false,
true,
},
}
)
const (
defaultBackend = "upstream-name"
defaultHost = "example.com"
fooAuthHost = "foo.com/auth"
)
func getTestDataDir() (string, error) {
pwd, err := os.Getwd()
if err != nil {
return "", err
}
return path.Join(pwd, "../../../../test/data"), nil
}
func TestBuildLuaSharedDictionaries(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
// config lua dict
cfg := config.Configuration{
LuaSharedDicts: map[string]int{
"configuration_data": 10240, "certificate_data": 20480,
},
}
actual := buildLuaSharedDictionaries(cfg, invalidType)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
servers := []*ingress.Server{
{
Hostname: "foo.bar",
Locations: []*ingress.Location{{Path: "/", PathType: &pathPrefix}},
},
{
Hostname: "another.host",
Locations: []*ingress.Location{{Path: "/", PathType: &pathPrefix}},
},
}
// returns value from config
configuration := buildLuaSharedDictionaries(cfg, servers)
if !strings.Contains(configuration, "lua_shared_dict configuration_data 10M;\n") {
t.Errorf("expected to include 'configuration_data' but got %s", configuration)
}
if !strings.Contains(configuration, "lua_shared_dict certificate_data 20M;\n") {
t.Errorf("expected to include 'certificate_data' but got %s", configuration)
}
// test invalid config
configuration = buildLuaSharedDictionaries(invalidType, servers)
if configuration != "" {
t.Errorf("expected an empty string, but got %s", configuration)
}
if actual != expected {
t.Errorf("Expected '%v' but returned '%v' ", expected, actual)
}
}
func TestLuaConfigurationRequestBodySize(t *testing.T) {
cfg := config.Configuration{
LuaSharedDicts: map[string]int{
"configuration_data": 10240, "certificate_data": 20480,
},
}
size := luaConfigurationRequestBodySize(cfg)
if size != "21M" {
t.Errorf("expected the size to be 21M but got: %v", size)
}
}
func TestFormatIP(t *testing.T) {
cases := map[string]struct {
Input, Output string
}{
"ipv4-localhost": {"127.0.0.1", "127.0.0.1"},
"ipv4-internet": {"8.8.8.8", "8.8.8.8"},
"ipv6-localhost": {"::1", "[::1]"},
"ipv6-internet": {"2001:4860:4860::8888", "[2001:4860:4860::8888]"},
"invalid-ip": {"nonsense", "nonsense"},
"empty-ip": {"", ""},
}
for k, tc := range cases {
res := formatIP(tc.Input)
if res != tc.Output {
t.Errorf("%s: called formatIp('%s'); expected '%v' but returned '%v'", k, tc.Input, tc.Output, res)
}
}
}
func TestQuote(t *testing.T) {
foo := "foo"
cases := map[interface{}]string{
"foo": `"foo"`,
"\"foo\"": `"\"foo\""`,
"foo\nbar": `"foo\nbar"`,
&foo: `"foo"`,
10: `"10"`,
}
for input, output := range cases {
actual := quote(input)
if actual != output {
t.Errorf("quote('%s'): expected '%v' but returned '%v'", input, output, actual)
}
}
}
func TestBuildLocation(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := "/"
actual := buildLocation(invalidType, true)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
PathType: &pathPrefix,
Rewrite: rewrite.Config{Target: tc.Target},
}
newLoc := buildLocation(loc, tc.enforceRegex)
if tc.Location != newLoc {
t.Errorf("%s: expected '%v' but returned %v", k, tc.Location, newLoc)
}
}
}
func TestBuildProxyPass(t *testing.T) {
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
PathType: &pathPrefix,
Rewrite: rewrite.Config{Target: tc.Target},
Backend: defaultBackend,
XForwardedPrefix: tc.XForwardedPrefix,
}
if tc.SecureBackend {
loc.BackendProtocol = httpsProtocol
}
backend := &ingress.Backend{
Name: defaultBackend,
}
if tc.Sticky {
backend.SessionAffinity = ingress.SessionAffinityConfig{
AffinityType: "cookie",
CookieSessionAffinity: ingress.CookieSessionAffinity{
Locations: map[string][]string{
defaultHost: {tc.Path},
},
},
}
}
backends := []*ingress.Backend{backend}
pp := buildProxyPass(defaultHost, backends, loc)
if !strings.EqualFold(tc.ProxyPass, pp) {
t.Errorf("%s: expected \n'%v'\nbut returned \n'%v'", k, tc.ProxyPass, pp)
}
}
}
func TestBuildProxyPassAutoHttp(t *testing.T) {
for k, tc := range tmplFuncTestcases {
loc := &ingress.Location{
Path: tc.Path,
Rewrite: rewrite.Config{Target: tc.Target},
Backend: defaultBackend,
XForwardedPrefix: tc.XForwardedPrefix,
}
if tc.SecureBackend {
loc.BackendProtocol = httpsProtocol
} else {
loc.BackendProtocol = autoHTTPProtocol
}
backend := &ingress.Backend{
Name: defaultBackend,
}
if tc.Sticky {
backend.SessionAffinity = ingress.SessionAffinityConfig{
AffinityType: "cookie",
CookieSessionAffinity: ingress.CookieSessionAffinity{
Locations: map[string][]string{
defaultHost: {tc.Path},
},
},
}
}
backends := []*ingress.Backend{backend}
pp := buildProxyPass(defaultHost, backends, loc)
if !strings.EqualFold(tc.AutoHTTPProxyPass, pp) {
t.Errorf("%s: expected \n'%v'\nbut returned \n'%v'", k, tc.ProxyPass, pp)
}
}
}
func TestBuildAuthLocation(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
actual := buildAuthLocation(invalidType, "")
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
authURL := fooAuthHost
globalAuthURL := "foo.com/global-auth"
loc := &ingress.Location{
ExternalAuth: authreq.Config{
URL: authURL,
},
Path: "/cat",
EnableGlobalAuth: true,
}
encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "")
externalAuthPath := fmt.Sprintf("/_external-auth-%v-default", encodedAuthURL)
testCases := []struct {
title string
authURL string
globalAuthURL string
enableglobalExternalAuth bool
expected string
}{
{"authURL, globalAuthURL and enabled", authURL, globalAuthURL, true, externalAuthPath},
{"authURL, globalAuthURL and disabled", authURL, globalAuthURL, false, externalAuthPath},
{"authURL, empty globalAuthURL and enabled", authURL, "", true, externalAuthPath},
{"authURL, empty globalAuthURL and disabled", authURL, "", false, externalAuthPath},
{"globalAuthURL and enabled", "", globalAuthURL, true, externalAuthPath},
{"globalAuthURL and disabled", "", globalAuthURL, false, ""},
{"all empty and enabled", "", "", true, ""},
{"all empty and disabled", "", "", false, ""},
}
for _, testCase := range testCases {
loc.ExternalAuth.URL = testCase.authURL
loc.EnableGlobalAuth = testCase.enableglobalExternalAuth
str := buildAuthLocation(loc, testCase.globalAuthURL)
if str != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, str)
}
}
}
func TestShouldApplyGlobalAuth(t *testing.T) {
authURL := fooAuthHost
globalAuthURL := "foo.com/global-auth"
loc := &ingress.Location{
ExternalAuth: authreq.Config{
URL: authURL,
},
Path: "/cat",
EnableGlobalAuth: true,
}
testCases := []struct {
title string
authURL string
globalAuthURL string
enableglobalExternalAuth bool
expected bool
}{
{"authURL, globalAuthURL and enabled", authURL, globalAuthURL, true, false},
{"authURL, globalAuthURL and disabled", authURL, globalAuthURL, false, false},
{"authURL, empty globalAuthURL and enabled", authURL, "", true, false},
{"authURL, empty globalAuthURL and disabled", authURL, "", false, false},
{"globalAuthURL and enabled", "", globalAuthURL, true, true},
{"globalAuthURL and disabled", "", globalAuthURL, false, false},
{"all empty and enabled", "", "", true, false},
{"all empty and disabled", "", "", false, false},
}
for _, testCase := range testCases {
loc.ExternalAuth.URL = testCase.authURL
loc.EnableGlobalAuth = testCase.enableglobalExternalAuth
result := shouldApplyGlobalAuth(loc, testCase.globalAuthURL)
if result != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, result)
}
}
}
func TestBuildAuthResponseHeaders(t *testing.T) {
externalAuthResponseHeaders := []string{"h1", "H-With-Caps-And-Dashes"}
tests := []struct {
headers []string
expected []string
lua bool
}{
{
headers: externalAuthResponseHeaders,
lua: false,
expected: []string{
"auth_request_set $authHeader0 $upstream_http_h1;",
"proxy_set_header 'h1' $authHeader0;",
"auth_request_set $authHeader1 $upstream_http_h_with_caps_and_dashes;",
"proxy_set_header 'H-With-Caps-And-Dashes' $authHeader1;",
},
},
{
headers: externalAuthResponseHeaders,
lua: true,
expected: []string{
"set $authHeader0 '';",
"proxy_set_header 'h1' $authHeader0;",
"set $authHeader1 '';",
"proxy_set_header 'H-With-Caps-And-Dashes' $authHeader1;",
},
},
}
for _, test := range tests {
got := buildAuthResponseHeaders(proxySetHeader(nil), test.headers, test.lua)
if !reflect.DeepEqual(test.expected, got) {
t.Errorf("Expected \n'%v'\nbut returned \n'%v'", test.expected, got)
}
}
}
func TestBuildAuthResponseLua(t *testing.T) {
externalAuthResponseHeaders := []string{"h1", "H-With-Caps-And-Dashes"}
expected := "h1,H-With-Caps-And-Dashes"
headers := buildAuthUpstreamLuaHeaders(externalAuthResponseHeaders)
if !reflect.DeepEqual(expected, headers) {
t.Errorf("Expected \n'%v'\nbut returned \n'%v'", expected, headers)
}
}
func TestBuildAuthProxySetHeaders(t *testing.T) {
proxySetHeaders := map[string]string{
"header1": "value1",
"header2": "value2",
}
expected := []string{
"proxy_set_header 'header1' 'value1';",
"proxy_set_header 'header2' 'value2';",
}
headers := buildAuthProxySetHeaders(proxySetHeaders)
if !reflect.DeepEqual(expected, headers) {
t.Errorf("Expected \n'%v'\nbut returned \n'%v'", expected, headers)
}
}
func TestBuildAuthUpstreamName(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
actual := buildAuthUpstreamName(invalidType, "")
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
loc := &ingress.Location{
ExternalAuth: authreq.Config{
URL: fooAuthHost,
},
Path: "/cat",
}
encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "")
externalAuthPath := fmt.Sprintf("external-auth-%v-default", encodedAuthURL)
testCases := []struct {
title string
host string
expected string
}{
{"valid host", "auth.my.site", fmt.Sprintf("%s-%s", "auth.my.site", externalAuthPath)},
{"valid host", "your.auth.site", fmt.Sprintf("%s-%s", "your.auth.site", externalAuthPath)},
{"empty host", "", ""},
}
for _, testCase := range testCases {
str := buildAuthUpstreamName(loc, testCase.host)
if str != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, str)
}
}
}
func TestShouldApplyAuthUpstream(t *testing.T) {
authURL := fooAuthHost
loc := &ingress.Location{
ExternalAuth: authreq.Config{
URL: authURL,
KeepaliveConnections: 0,
},
Path: "/cat",
}
cfg := config.Configuration{
UseHTTP2: false,
}
testCases := []struct {
title string
authURL string
keepaliveConnections int
expected bool
}{
{"authURL, no keepalive", authURL, 0, false},
{"authURL, keepalive", authURL, 10, true},
{"empty, no keepalive", "", 0, false},
{"empty, keepalive", "", 10, false},
}
for _, testCase := range testCases {
loc.ExternalAuth.URL = testCase.authURL
loc.ExternalAuth.KeepaliveConnections = testCase.keepaliveConnections
result := shouldApplyAuthUpstream(loc, cfg)
if result != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, result)
}
}
// keepalive is not supported with UseHTTP2
cfg.UseHTTP2 = true
for _, testCase := range testCases {
loc.ExternalAuth.URL = testCase.authURL
loc.ExternalAuth.KeepaliveConnections = testCase.keepaliveConnections
result := shouldApplyAuthUpstream(loc, cfg)
if result != false {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, false, result)
}
}
}
func TestExtractHostPort(t *testing.T) {
testCases := []struct {
title string
url string
expected string
}{
{"full URL", "https://my.auth.site:5000/path", "my.auth.site:5000"},
{"URL with no port", "http://my.auth.site/path", "my.auth.site"},
{"URL with no path", "https://my.auth.site:5000", "my.auth.site:5000"},
{"URL no port and path", "http://my.auth.site", "my.auth.site"},
{"missing method", "my.auth.site/path", ""},
{"all empty", "", ""},
}
for _, testCase := range testCases {
result := extractHostPort(testCase.url)
if result != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, result)
}
}
}
func TestChangeHostPort(t *testing.T) {
testCases := []struct {
title string
url string
host string
expected string
}{
{"full URL", "https://my.auth.site:5000/path", "your.domain", "https://your.domain/path"},
{"URL with no port", "http://my.auth.site/path", "your.domain", "http://your.domain/path"},
{"URL with no path", "http://my.auth.site:5000", "your.domain:8888", "http://your.domain:8888"},
{"URL with no port and path", "https://my.auth.site", "your.domain:8888", "https://your.domain:8888"},
{"invalid host", "my.auth.site/path", "", ""},
{"missing method", "my.auth.site/path", "your.domain", ""},
{"all empty", "", "", ""},
}
for _, testCase := range testCases {
result := changeHostPort(testCase.url, testCase.host)
if result != testCase.expected {
t.Errorf("%v: expected '%v' but returned '%v'", testCase.title, testCase.expected, result)
}
}
}
func TestTemplateWithData(t *testing.T) {
pwd, err := os.Getwd()
if err != nil {
t.Errorf("unexpected error: %v", err)
}
f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json"))
if err != nil {
t.Errorf("unexpected error reading json file: %v", err)
}
defer f.Close()
data, err := os.ReadFile(f.Name())
if err != nil {
t.Error("unexpected error reading json file: ", err)
}
var dat config.TemplateConfig
if err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(data, &dat); err != nil {
t.Errorf("unexpected error unmarshalling json: %v", err)
}
if dat.ListenPorts == nil {
dat.ListenPorts = &config.ListenPorts{}
}
ngxTpl, err := NewTemplate(nginx.TemplatePath)
if err != nil {
t.Errorf("invalid NGINX template: %v", err)
}
dat.Cfg.DefaultSSLCertificate = &ingress.SSLCert{}
rt, err := ngxTpl.Write(&dat)
if err != nil {
t.Errorf("invalid NGINX template: %v", err)
}
if !strings.Contains(string(rt), "listen [2001:db8:a0b:12f0::1]") {
t.Errorf("invalid NGINX template, expected IPV6 listen address not present")
}
if !strings.Contains(string(rt), "listen [3731:54:65fe:2::a7]") {
t.Errorf("invalid NGINX template, expected IPV6 listen address not present")
}
if !strings.Contains(string(rt), "listen 2.2.2.2") {
t.Errorf("invalid NGINX template, expected IPV4 listen address not present")
}
}
func BenchmarkTemplateWithData(b *testing.B) {
pwd, err := os.Getwd()
if err != nil {
b.Errorf("unexpected error: %v", err)
}
f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json"))
if err != nil {
b.Errorf("unexpected error reading json file: %v", err)
}
defer f.Close()
data, err := os.ReadFile(f.Name())
if err != nil {
b.Error("unexpected error reading json file: ", err)
}
var dat config.TemplateConfig
if err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(data, &dat); err != nil {
b.Errorf("unexpected error unmarshalling json: %v", err)
}
ngxTpl, err := NewTemplate(nginx.TemplatePath)
if err != nil {
b.Errorf("invalid NGINX template: %v", err)
}
for i := 0; i < b.N; i++ {
if _, err := ngxTpl.Write(&dat); err != nil {
b.Errorf("unexpected error writing template: %v", err)
}
}
}
func TestBuildDenyVariable(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
actual := buildDenyVariable(invalidType)
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
a := buildDenyVariable("host1.example.com_/.well-known/acme-challenge")
b := buildDenyVariable("host1.example.com_/.well-known/acme-challenge")
if !reflect.DeepEqual(a, b) {
t.Errorf("Expected '%v' but returned '%v'", a, b)
}
}
func TestBuildByteSize(t *testing.T) {
cases := []struct {
value interface{}
isOffset bool
expected bool
}{
{"1000", false, true},
{"1000k", false, true},
{"1m", false, true},
{"10g", false, false},
{" 1m ", false, true},
{"1000kk", false, false},
{"1000km", false, false},
{"1mm", false, false},
{nil, false, false},
{"", false, false},
{" ", false, false},
{"1G", true, true},
{"1000kk", true, false},
{"", true, false},
}
for _, tc := range cases {
val := isValidByteSize(tc.value, tc.isOffset)
if tc.expected != val {
t.Errorf("Expected '%v' but returned '%v'", tc.expected, val)
}
}
}
func TestIsLocationAllowed(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := false
actual := isLocationAllowed(invalidType)
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
loc := ingress.Location{
Denied: nil,
}
isAllowed := isLocationAllowed(&loc)
if !isAllowed {
t.Errorf("Expected '%v' but returned '%v'", true, isAllowed)
}
}
func TestBuildForwardedFor(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
actual := buildForwardedFor(invalidType)
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
inputStr := "X-Forwarded-For"
expected = "$http_x_forwarded_for"
actual = buildForwardedFor(inputStr)
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
}
func TestBuildResolvers(t *testing.T) {
ipOne := net.ParseIP("192.0.0.1")
ipTwo := net.ParseIP("2001:db8:1234:0000:0000:0000:0000:0000")
ipList := []net.IP{ipOne, ipTwo}
invalidType := &ingress.Ingress{}
expected := ""
actual := buildResolvers(invalidType, false)
// Invalid Type for []net.IP
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
actual = buildResolvers(ipList, invalidType)
// Invalid Type for bool
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
validResolver := "resolver 192.0.0.1 [2001:db8:1234::] valid=30s;"
resolver := buildResolvers(ipList, false)
if resolver != validResolver {
t.Errorf("Expected '%v' but returned '%v'", validResolver, resolver)
}
validResolver = "resolver 192.0.0.1 valid=30s ipv6=off;"
resolver = buildResolvers(ipList, true)
if resolver != validResolver {
t.Errorf("Expected '%v' but returned '%v'", validResolver, resolver)
}
}
func TestBuildNextUpstream(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := ""
actual := buildNextUpstream(invalidType, "")
if expected != actual {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
cases := map[string]struct {
NextUpstream string
NonIdempotent bool
Output string
}{
"default": {
"timeout http_500 http_502",
false,
"timeout http_500 http_502",
},
"global": {
"timeout http_500 http_502",
true,
"timeout http_500 http_502 non_idempotent",
},
"local": {
"timeout http_500 http_502 non_idempotent",
false,
"timeout http_500 http_502 non_idempotent",
},
}
for k, tc := range cases {
nextUpstream := buildNextUpstream(tc.NextUpstream, tc.NonIdempotent)
if nextUpstream != tc.Output {
t.Errorf(
"%s: called buildNextUpstream('%s', %v); expected '%v' but returned '%v'",
k,
tc.NextUpstream,
tc.NonIdempotent,
tc.Output,
nextUpstream,
)
}
}
}
func TestBuildRateLimit(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := []string{}
actual := buildRateLimit(invalidType)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
loc := &ingress.Location{}
loc.RateLimit.Connections.Name = "con"
loc.RateLimit.Connections.Limit = 1
loc.RateLimit.RPS.Name = "rps"
loc.RateLimit.RPS.Limit = 1
loc.RateLimit.RPS.Burst = 1
loc.RateLimit.RPM.Name = "rpm"
loc.RateLimit.RPM.Limit = 2
loc.RateLimit.RPM.Burst = 2
loc.RateLimit.LimitRateAfter = 1
loc.RateLimit.LimitRate = 1
validLimits := []string{
"limit_conn con 1;",
"limit_req zone=rps burst=1 nodelay;",
"limit_req zone=rpm burst=2 nodelay;",
"limit_rate_after 1k;",
"limit_rate 1k;",
}
limits := buildRateLimit(loc)
for i, limit := range limits {
if limit != validLimits[i] {
t.Errorf("Expected '%v' but returned '%v'", validLimits, limits)
}
}
// Invalid limit
limits = buildRateLimit(&ingress.Ingress{})
if !reflect.DeepEqual(expected, limits) {
t.Errorf("Expected '%v' but returned '%v'", expected, limits)
}
}
// TODO: Needs more tests
func TestBuildRateLimitZones(t *testing.T) {
invalidType := &ingress.Ingress{}
expected := []string{}
actual := buildRateLimitZones(invalidType)
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected '%v' but returned '%v'", expected, actual)
}
}