-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathingress_test.go
More file actions
6202 lines (5624 loc) · 197 KB
/
Copy pathingress_test.go
File metadata and controls
6202 lines (5624 loc) · 197 KB
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 configs
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/nginx/kubernetes-ingress/internal/configs/version1"
"github.com/nginx/kubernetes-ingress/internal/configs/version2"
"github.com/nginx/kubernetes-ingress/internal/k8s/secrets"
conf_v1 "github.com/nginx/kubernetes-ingress/pkg/apis/configuration/v1"
v1 "k8s.io/api/core/v1"
networking "k8s.io/api/networking/v1"
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
)
func TestGenerateNginxCfg(t *testing.T) {
t.Parallel()
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
expected := createExpectedConfigForCafeIngressEx(isPlus)
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: new(createCafeIngressEx()),
apResources: nil,
dosResource: nil,
isMinion: false,
isPlus: isPlus,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if diff := cmp.Diff(expected, result); diff != "" {
t.Errorf("generateNginxCfg() returned unexpected result (-want +got):\n%s", diff)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg() returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgForAddHeaderInherit(t *testing.T) {
t.Parallel()
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[AddHeaderInheritAnnotation] = addHeaderInheritMerge
expected := createExpectedConfigForCafeIngressEx(isPlus)
expected.Servers[0].AddHeaderInherit = addHeaderInheritMerge
expected.Ingress.Annotations[AddHeaderInheritAnnotation] = addHeaderInheritMerge
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
apResources: nil,
dosResource: nil,
isMinion: false,
isPlus: isPlus,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if diff := cmp.Diff(expected, result); diff != "" {
t.Errorf("generateNginxCfg() returned unexpected result (-want +got):\n%s", diff)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg() returned warnings: %v", warnings)
}
}
func TestGetNameForUpstreamUsesTokenForEmptyHost(t *testing.T) {
t.Parallel()
ing := &networking.Ingress{ObjectMeta: meta_v1.ObjectMeta{Name: "cafe-ingress", Namespace: "default"}}
backend := &networking.IngressBackend{
Service: &networking.IngressServiceBackend{
Name: "tea-svc",
Port: networking.ServiceBackendPort{Number: 80},
},
}
got := getNameForUpstream(ing, emptyHostName, backend)
want := "default-cafe-ingress-_-tea-svc-80"
if got != want {
t.Fatalf("getNameForUpstream() = %q, want %q", got, want)
}
}
func TestGenerateNginxCfgForJWT(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[JWTKeyAnnotation] = "cafe-jwk"
cafeIngressEx.Ingress.Annotations[JWTRealmAnnotation] = "Cafe App"
cafeIngressEx.Ingress.Annotations[JWTTokenAnnotation] = "$cookie_auth_token"
cafeIngressEx.Ingress.Annotations[JWTLoginURLAnnotation] = "https://login.example.com"
cafeIngressEx.SecretRefs["cafe-jwk"] = &secrets.SecretReference{
Secret: &v1.Secret{
Type: secrets.SecretTypeJWK,
},
Path: "/etc/nginx/secrets/default-cafe-jwk",
}
isPlus := true
configParams := NewDefaultConfigParams(context.Background(), isPlus)
expected := createExpectedConfigForCafeIngressEx(isPlus)
expected.Servers[0].JWTAuth = &version1.JWTAuth{
Key: "/etc/nginx/secrets/default-cafe-jwk",
Realm: "Cafe App",
Token: "$cookie_auth_token",
RedirectLocationName: "@login_url_default-cafe-ingress",
}
expected.Servers[0].JWTRedirectLocations = []version1.JWTRedirectLocation{
{
Name: "@login_url_default-cafe-ingress",
LoginURL: "https://login.example.com",
},
}
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
apResources: nil,
dosResource: nil,
isMinion: false,
isPlus: true,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if !reflect.DeepEqual(result.Servers[0].JWTAuth, expected.Servers[0].JWTAuth) {
t.Errorf("generateNginxCfg returned \n%v, but expected \n%v", result.Servers[0].JWTAuth, expected.Servers[0].JWTAuth)
}
if !reflect.DeepEqual(result.Servers[0].JWTRedirectLocations, expected.Servers[0].JWTRedirectLocations) {
t.Errorf("generateNginxCfg returned \n%v, but expected \n%v", result.Servers[0].JWTRedirectLocations, expected.Servers[0].JWTRedirectLocations)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgForBasicAuth(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations["nginx.org/basic-auth-secret"] = "cafe-htpasswd"
cafeIngressEx.Ingress.Annotations["nginx.org/basic-auth-realm"] = "Cafe App"
cafeIngressEx.SecretRefs["cafe-htpasswd"] = &secrets.SecretReference{
Secret: &v1.Secret{
Type: secrets.SecretTypeHtpasswd,
},
Path: "/etc/nginx/secrets/default-cafe-htpasswd",
}
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
expected := createExpectedConfigForCafeIngressEx(isPlus)
expected.Servers[0].BasicAuth = &version1.BasicAuth{
Secret: "/etc/nginx/secrets/default-cafe-htpasswd",
Realm: "Cafe App",
}
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
apResources: nil,
dosResource: nil,
isMinion: false,
isPlus: true,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if !reflect.DeepEqual(result.Servers[0].BasicAuth, expected.Servers[0].BasicAuth) {
t.Errorf("generateNginxCfg returned \n%v, but expected \n%v", result.Servers[0].BasicAuth, expected.Servers[0].BasicAuth)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgForAppRoot(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations["nginx.org/app-root"] = "/coffee"
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
expected := createExpectedConfigForCafeIngressEx(isPlus)
expected.Servers[0].AppRoot = "/coffee"
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
apResources: nil,
dosResource: nil,
isMinion: false,
isPlus: isPlus,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if result.Servers[0].AppRoot != expected.Servers[0].AppRoot {
t.Errorf("generateNginxCfg returned AppRoot %v, but expected %v", result.Servers[0].AppRoot, expected.Servers[0].AppRoot)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgForCORSPolicy(t *testing.T) {
t.Parallel()
allowCredentials := true
maxAge := 3600
tests := []struct {
name string
allowOrigin []string
wantMap bool
wantOrigin string
wantVaryHeader bool
}{
{
// Single exact origin should produce direct header value (no map).
name: "single origin without map",
allowOrigin: []string{"https://example.com"},
wantMap: false,
wantOrigin: "https://example.com",
wantVaryHeader: true,
},
{
// Multiple/wildcard origins should be validated through a generated map variable.
name: "multiple origins with map",
allowOrigin: []string{"https://example.com", "https://*.example.com"},
wantMap: true,
wantVaryHeader: true,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations["nginx.org/policies"] = "cors-policy"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/cors-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "cors-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
CORS: &conf_v1.CORS{
AllowOrigin: test.allowOrigin,
AllowMethods: []string{"GET", "POST", "OPTIONS"},
AllowHeaders: []string{"Authorization", "Content-Type"},
AllowCredentials: &allowCredentials,
MaxAge: &maxAge,
},
},
},
}
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: isPlus,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
if len(warnings) != 0 {
t.Fatalf("generateNginxCfg() returned warnings: %v", warnings)
}
if test.wantMap && len(result.Maps) != 1 {
t.Fatalf("expected 1 CORS map, got %d", len(result.Maps))
}
if !test.wantMap && len(result.Maps) != 0 {
t.Fatalf("expected no CORS map, got %d", len(result.Maps))
}
originValue := test.wantOrigin
if test.wantMap {
if result.Maps[0].Source != "$http_origin" {
t.Fatalf("unexpected map source: %s", result.Maps[0].Source)
}
originValue = result.Maps[0].Variable
}
for _, server := range result.Servers {
for _, loc := range server.Locations {
if !loc.CORSEnabled {
t.Fatalf("location %s should have CORS enabled", loc.Path)
}
originHeader, ok := getHeaderValue(loc.AddHeaders, "Access-Control-Allow-Origin")
if !ok {
t.Fatalf("location %s missing Access-Control-Allow-Origin header", loc.Path)
}
if originHeader != originValue {
t.Fatalf("location %s origin header = %q, want %q", loc.Path, originHeader, originValue)
}
_, hasVary := getHeaderValue(loc.AddHeaders, "Vary")
if hasVary != test.wantVaryHeader {
t.Fatalf("location %s vary header present = %v, want %v", loc.Path, hasVary, test.wantVaryHeader)
}
}
}
})
}
}
func TestGenerateNginxCfgForMergeableIngressesCORSPolicy(t *testing.T) {
t.Parallel()
tests := []struct {
name string
masterOrigin string
coffeeMinionOrigin string
expectCoffeeFromMin bool
expectedTeaOriginVal string
}{
{
// Master policy should flow to minion locations when minion has no CORS policy.
name: "inherits master cors in all minions",
masterOrigin: "https://master.example.com",
expectCoffeeFromMin: false,
expectedTeaOriginVal: "https://master.example.com",
},
{
// Minion policy should override master fallback for that minion only.
name: "keeps minion cors when configured",
masterOrigin: "https://master.example.com",
coffeeMinionOrigin: "https://coffee.example.com",
expectCoffeeFromMin: true,
expectedTeaOriginVal: "https://master.example.com",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
mergeableIngresses := createMergeableCafeIngress()
mergeableIngresses.Master.Ingress.Annotations["nginx.org/policies"] = "master-cors"
mergeableIngresses.Master.Policies = map[string]*conf_v1.Policy{
"default/master-cors": {
ObjectMeta: meta_v1.ObjectMeta{Name: "master-cors", Namespace: "default"},
Spec: conf_v1.PolicySpec{
CORS: &conf_v1.CORS{AllowOrigin: []string{test.masterOrigin}},
},
},
}
if test.coffeeMinionOrigin != "" {
mergeableIngresses.Minions[0].Ingress.Annotations["nginx.org/policies"] = "coffee-cors"
mergeableIngresses.Minions[0].Policies = map[string]*conf_v1.Policy{
"default/coffee-cors": {
ObjectMeta: meta_v1.ObjectMeta{Name: "coffee-cors", Namespace: "default"},
Spec: conf_v1.PolicySpec{
CORS: &conf_v1.CORS{AllowOrigin: []string{test.coffeeMinionOrigin}},
},
},
}
}
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
result, warnings := generateNginxCfgForMergeableIngresses(NginxCfgParams{
mergeableIngs: mergeableIngresses,
BaseCfgParams: configParams,
isPlus: isPlus,
isResolverConfigured: false,
staticParams: &StaticConfigParams{},
isWildcardEnabled: false,
})
if len(warnings) != 0 {
t.Fatalf("generateNginxCfgForMergeableIngresses() returned warnings: %v", warnings)
}
if len(result.Maps) != 0 {
t.Fatalf("expected no CORS maps for single-origin policies, got %d", len(result.Maps))
}
for _, loc := range result.Servers[0].Locations {
if !loc.CORSEnabled {
t.Fatalf("location %s should have CORS enabled", loc.Path)
}
originHeader, ok := getHeaderValue(loc.AddHeaders, "Access-Control-Allow-Origin")
if !ok {
t.Fatalf("location %s missing Access-Control-Allow-Origin header", loc.Path)
}
switch loc.MinionIngress.Name {
case "cafe-ingress-coffee-minion":
expectedCoffeeOrigin := test.masterOrigin
if test.expectCoffeeFromMin {
expectedCoffeeOrigin = test.coffeeMinionOrigin
}
if originHeader != expectedCoffeeOrigin {
t.Fatalf("coffee minion origin = %q, want %q", originHeader, expectedCoffeeOrigin)
}
case "cafe-ingress-tea-minion":
if originHeader != test.expectedTeaOriginVal {
t.Fatalf("tea minion origin = %q, want %q", originHeader, test.expectedTeaOriginVal)
}
default:
t.Fatalf("unexpected minion %s", loc.MinionIngress.Name)
}
}
})
}
}
func getHeaderValue(headers []version2.AddHeader, headerName string) (string, bool) {
for _, header := range headers {
if header.Name == headerName {
return header.Value, true
}
}
return "", false
}
func TestFilterIngressPolicyRefs(t *testing.T) {
t.Parallel()
tests := []struct {
name string
annotationValue string
policies map[string]*conf_v1.Policy
policyRefs []conf_v1.PolicyReference
expectedRefs []conf_v1.PolicyReference
expectError bool
warningSubstr string
}{
{
name: "filters waf policy from nginx org policies",
annotationValue: "waf-policy",
policies: map[string]*conf_v1.Policy{
"default/waf-policy": {
ObjectMeta: meta_v1.ObjectMeta{Name: "waf-policy", Namespace: "default"},
Spec: conf_v1.PolicySpec{WAF: &conf_v1.WAF{Enable: true, ApPolicy: "dataguard-alarm"}},
},
},
policyRefs: []conf_v1.PolicyReference{{Name: "waf-policy"}},
expectedRefs: nil,
expectError: true,
warningSubstr: "WAF policy default/waf-policy is not supported in annotation nginx.org/policies",
},
{
name: "keeps non plus policy from nginx org policies",
annotationValue: "cors-policy",
policies: map[string]*conf_v1.Policy{
"default/cors-policy": {
ObjectMeta: meta_v1.ObjectMeta{Name: "cors-policy", Namespace: "default"},
Spec: conf_v1.PolicySpec{CORS: &conf_v1.CORS{AllowOrigin: []string{"https://example.com"}}},
},
},
policyRefs: []conf_v1.PolicyReference{{Name: "cors-policy"}},
expectedRefs: []conf_v1.PolicyReference{{Name: "cors-policy"}},
expectError: false,
},
{
name: "keeps plus annotation ref when same policy is referenced there",
annotationValue: "other-policy",
policies: map[string]*conf_v1.Policy{
"default/waf-policy": {
ObjectMeta: meta_v1.ObjectMeta{Name: "waf-policy", Namespace: "default"},
Spec: conf_v1.PolicySpec{WAF: &conf_v1.WAF{Enable: true, ApPolicy: "dataguard-alarm"}},
},
},
policyRefs: []conf_v1.PolicyReference{{Name: "waf-policy"}},
expectedRefs: []conf_v1.PolicyReference{{Name: "waf-policy"}},
expectError: false,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
ingEx := createCafeIngressEx()
ingEx.Ingress.Annotations[PoliciesAnnotation] = test.annotationValue
ingEx.Policies = test.policies
result, warnings, isError := filterIngressPolicyRefs(test.policyRefs, &ingEx)
if diff := cmp.Diff(test.expectedRefs, result); diff != "" {
t.Fatalf("filterIngressPolicyRefs() returned unexpected refs (-want +got):\n%s", diff)
}
if isError != test.expectError {
t.Fatalf("filterIngressPolicyRefs() returned isError=%v, want %v", isError, test.expectError)
}
ingressWarnings := warnings[ingEx.Ingress]
if test.warningSubstr == "" {
if len(ingressWarnings) != 0 {
t.Fatalf("expected no warnings, got %v", ingressWarnings)
}
return
}
if len(ingressWarnings) != 1 || !strings.Contains(ingressWarnings[0], test.warningSubstr) {
t.Fatalf("expected warning containing %q, got %v", test.warningSubstr, ingressWarnings)
}
})
}
}
func TestGetIngressPolicyRefs(t *testing.T) {
t.Parallel()
tests := []struct {
name string
ingEx *IngressEx
expectedRefs []conf_v1.PolicyReference
}{
{
name: "nil ingress ex returns nil",
ingEx: nil,
expectedRefs: nil,
},
{
name: "merges annotations and de duplicates normalized refs",
ingEx: func() *IngressEx {
ingEx := createCafeIngressEx()
ingEx.Ingress.Annotations[PoliciesAnnotation] = "cors-policy, other-ns/other-policy, dup-policy"
ingEx.Ingress.Annotations[PoliciesAnnotationPlus] = "default/dup-policy, waf-ns/waf-policy, cors-policy"
return &ingEx
}(),
expectedRefs: []conf_v1.PolicyReference{
{Name: "cors-policy", Namespace: "default"},
{Name: "other-policy", Namespace: "other-ns"},
{Name: "dup-policy", Namespace: "default"},
{Name: "waf-policy", Namespace: "waf-ns"},
},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
result := getIngressPolicyRefs(test.ingEx)
if diff := cmp.Diff(test.expectedRefs, result); diff != "" {
t.Fatalf("getIngressPolicyRefs() returned unexpected refs (-want +got):\n%s", diff)
}
})
}
}
func TestResolveIngressAppProtectResources(t *testing.T) {
t.Parallel()
baseResources := &AppProtectResources{
AppProtectPolicy: "policy.json",
AppProtectLogconfs: []string{"log.json stderr"},
}
tests := []struct {
name string
ingEx *IngressEx
policyCfg policiesCfg
expectedResources *AppProtectResources
warningSubstr string
}{
{
name: "returns original resources when waf policy is absent",
ingEx: &IngressEx{Ingress: createCafeIngressEx().Ingress},
policyCfg: policiesCfg{},
expectedResources: baseResources,
},
{
name: "returns original resources when ingress has no app protect annotations",
ingEx: &IngressEx{Ingress: createCafeIngressEx().Ingress},
policyCfg: policiesCfg{WAF: &version2.WAF{Enable: "on"}},
expectedResources: baseResources,
},
{
name: "policy waf takes precedence over app protect annotations",
ingEx: func() *IngressEx {
ingEx := createCafeIngressEx()
ingEx.Ingress.Annotations[AppProtectPolicyAnnotation] = "default/ap-policy"
return &ingEx
}(),
policyCfg: policiesCfg{WAF: &version2.WAF{Enable: "on"}},
expectedResources: &AppProtectResources{},
warningSubstr: "WAF cannot be configured through both Policy and App Protect annotations",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
result, warnings := resolveIngressAppProtectResources(test.ingEx, baseResources, test.policyCfg)
if diff := cmp.Diff(test.expectedResources, result); diff != "" {
t.Fatalf("resolveIngressAppProtectResources() returned unexpected resources (-want +got):\n%s", diff)
}
ingressWarnings := warnings[test.ingEx.Ingress]
if test.warningSubstr == "" {
if len(ingressWarnings) != 0 {
t.Fatalf("expected no warnings, got %v", ingressWarnings)
}
return
}
if len(ingressWarnings) != 1 || !strings.Contains(ingressWarnings[0], test.warningSubstr) {
t.Fatalf("expected warning containing %q, got %v", test.warningSubstr, ingressWarnings)
}
})
}
}
func TestGenerateNginxCfgForAccessControl(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations["nginx.org/policies"] = "my-test-policy"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/my-test-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "my-test-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
AccessControl: &conf_v1.AccessControl{
Allow: []string{"10.1.0.0/24"},
},
},
},
}
isPlus := false
configParams := NewDefaultConfigParams(context.Background(), isPlus)
expected := createExpectedConfigForCafeIngressEx(isPlus)
expected.Servers[0].Allow = []string{"10.1.0.0/24"}
expected.Ingress.Annotations["nginx.org/policies"] = "my-test-policy"
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: isPlus,
BaseCfgParams: configParams,
})
if diff := cmp.Diff(expected, result); diff != "" {
t.Errorf("generateNginxCfg() returned unexpected result (-want +got):\n%s", diff)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg() returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgForEgressMTLSPolicy(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[PoliciesAnnotation] = "egress-mtls-policy"
cafeIngressEx.Ingress.Annotations["nginx.org/ssl-services"] = "coffee-svc,tea-svc"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/egress-mtls-policy": newEgressMTLSPolicy(
"egress-mtls-policy",
"egress-mtls-secret",
"egress-trusted-ca-secret",
"secure-app.example.com",
true,
2,
),
}
addEgressMTLSSecretRefs(cafeIngressEx.SecretRefs)
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: false,
BaseCfgParams: NewDefaultConfigParams(context.Background(), false),
isResolverConfigured: false,
isWildcardEnabled: false,
})
if len(warnings) != 0 {
t.Fatalf("generateNginxCfg() returned warnings: %v", warnings)
}
expectedEgressMTLS := expectedEgressMTLSConfig(
"/etc/nginx/secrets/default-egress-mtls-secret",
"/etc/nginx/secrets/default-egress-trusted-ca-secret",
"secure-app.example.com",
true,
2,
)
for _, server := range result.Servers {
if diff := cmp.Diff(expectedEgressMTLS, server.EgressMTLS); diff != "" {
t.Fatalf("server %s egress mTLS mismatch (-want +got):\n%s", server.Name, diff)
}
for _, loc := range server.Locations {
if loc.EgressMTLS != nil {
t.Fatalf("location %s should inherit egress mTLS from server context", loc.Path)
}
if !loc.SSL {
t.Fatalf("location %s should proxy to a TLS upstream", loc.Path)
}
if !strings.HasPrefix(loc.ProxyPass, "https://") {
t.Fatalf("location %s proxy pass = %q, want https upstream", loc.Path, loc.ProxyPass)
}
}
}
}
func TestGenerateNginxCfgForWAFPolicyApPolicy(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[PoliciesAnnotationPlus] = "waf-policy"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/waf-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "waf-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
WAF: &conf_v1.WAF{
Enable: true,
ApPolicy: "dataguard-alarm",
SecurityLogs: []*conf_v1.SecurityLog{
{
Enable: true,
ApLogConf: "logconf",
LogDest: "syslog:server=127.0.0.1:514",
},
},
},
},
},
}
cafeIngressEx.ApPolRefs = map[string]*unstructured.Unstructured{
"default/dataguard-alarm": {
Object: map[string]interface{}{},
},
}
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetNamespace("default")
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetName("dataguard-alarm")
cafeIngressEx.LogConfRefs = map[string]*unstructured.Unstructured{
"default/logconf": {
Object: map[string]interface{}{},
},
}
cafeIngressEx.LogConfRefs["default/logconf"].SetNamespace("default")
cafeIngressEx.LogConfRefs["default/logconf"].SetName("logconf")
configParams := NewDefaultConfigParams(context.Background(), true)
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: true,
BaseCfgParams: configParams,
isResolverConfigured: false,
isWildcardEnabled: false,
})
expectedWAF := &version2.WAF{
Enable: "on",
ApPolicy: "/etc/nginx/waf/nac-policies/default_dataguard-alarm",
ApSecurityLogEnable: true,
ApLogConf: []string{"/etc/nginx/waf/nac-logconfs/default_logconf syslog:server=127.0.0.1:514"},
}
if diff := cmp.Diff(expectedWAF, result.Servers[0].WAF); diff != "" {
t.Errorf("generateNginxCfg() returned unexpected WAF config (-want +got):\n%s", diff)
}
if len(warnings) != 0 {
t.Errorf("generateNginxCfg() returned warnings: %v", warnings)
}
}
func TestGenerateNginxCfgRejectsPoliciesRequiringPlusAnnotationFromNginxOrgPolicies(t *testing.T) {
t.Parallel()
tests := []struct {
name string
annotations map[string]string
expectWarning bool
expectWAFApplied bool
expect500 bool
}{
{
name: "waf policy via nginx.org/policies is rejected",
annotations: map[string]string{
PoliciesAnnotation: "waf-policy",
},
expectWarning: true,
expectWAFApplied: false,
expect500: true,
},
{
name: "waf policy via both annotations is rejected",
annotations: map[string]string{
PoliciesAnnotation: "waf-policy",
PoliciesAnnotationPlus: "waf-policy",
},
expectWarning: true,
expectWAFApplied: false,
expect500: true,
},
{
name: "waf policy via nginx.com/policies is accepted",
annotations: map[string]string{
PoliciesAnnotationPlus: "waf-policy",
},
expectWarning: false,
expectWAFApplied: true,
expect500: false,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
cafeIngressEx := createCafeIngressEx()
for key, value := range test.annotations {
cafeIngressEx.Ingress.Annotations[key] = value
}
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/waf-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "waf-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
WAF: &conf_v1.WAF{
Enable: true,
ApPolicy: "dataguard-alarm",
},
},
},
}
cafeIngressEx.ApPolRefs = map[string]*unstructured.Unstructured{
"default/dataguard-alarm": {
Object: map[string]interface{}{},
},
}
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetNamespace("default")
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetName("dataguard-alarm")
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: true,
BaseCfgParams: NewDefaultConfigParams(context.Background(), true),
isResolverConfigured: false,
isWildcardEnabled: false,
})
ingressWarnings := warnings[cafeIngressEx.Ingress]
if test.expectWarning {
if len(ingressWarnings) != 1 {
t.Fatalf("expected 1 ingress warning, got %d: %v", len(ingressWarnings), ingressWarnings)
}
if !strings.Contains(ingressWarnings[0], "WAF policy default/waf-policy is not supported in annotation nginx.org/policies") {
t.Fatalf("expected nginx.org/policies warning, got: %v", ingressWarnings[0])
}
} else if len(ingressWarnings) != 0 {
t.Fatalf("expected no ingress warnings, got: %v", ingressWarnings)
}
hasWAF := result.Servers[0].WAF != nil
if hasWAF != test.expectWAFApplied {
t.Fatalf("expected WAF applied=%v, got %v", test.expectWAFApplied, hasWAF)
}
hasPolicyErrorReturn := result.Servers[0].PoliciesErrorReturn != nil
if hasPolicyErrorReturn != test.expect500 {
t.Fatalf("expected policy 500=%v, got %v", test.expect500, hasPolicyErrorReturn)
}
if test.expect500 && result.Servers[0].PoliciesErrorReturn.Code != 500 {
t.Fatalf("expected policy error return code 500, got %d", result.Servers[0].PoliciesErrorReturn.Code)
}
})
}
}
func TestGenerateNginxCfgAppliesWAFAndCORSFromDifferentPolicyAnnotations(t *testing.T) {
t.Parallel()
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[PoliciesAnnotation] = "cors-policy"
cafeIngressEx.Ingress.Annotations[PoliciesAnnotationPlus] = "waf-policy"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{
"default/cors-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "cors-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
CORS: &conf_v1.CORS{
AllowOrigin: []string{"https://example.com"},
},
},
},
"default/waf-policy": {
ObjectMeta: meta_v1.ObjectMeta{
Name: "waf-policy",
Namespace: "default",
},
Spec: conf_v1.PolicySpec{
WAF: &conf_v1.WAF{
Enable: true,
ApPolicy: "dataguard-alarm",
},
},
},
}
cafeIngressEx.ApPolRefs = map[string]*unstructured.Unstructured{
"default/dataguard-alarm": {
Object: map[string]interface{}{},
},
}
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetNamespace("default")
cafeIngressEx.ApPolRefs["default/dataguard-alarm"].SetName("dataguard-alarm")
result, warnings := generateNginxCfg(NginxCfgParams{
staticParams: &StaticConfigParams{},
ingEx: &cafeIngressEx,
isPlus: true,
BaseCfgParams: NewDefaultConfigParams(context.Background(), true),
isResolverConfigured: false,
isWildcardEnabled: false,
})
if len(warnings) != 0 {
t.Fatalf("generateNginxCfg() returned warnings: %v", warnings)
}
if result.Servers[0].WAF == nil {
t.Fatal("expected WAF config to be generated")
}
if result.Servers[0].WAF.ApPolicy != "/etc/nginx/waf/nac-policies/default_dataguard-alarm" {
t.Fatalf("expected WAF policy file path to be set, got %q", result.Servers[0].WAF.ApPolicy)
}
for _, loc := range result.Servers[0].Locations {
if !loc.CORSEnabled {
t.Fatalf("location %s should have CORS enabled", loc.Path)
}
originHeader, ok := getHeaderValue(loc.AddHeaders, "Access-Control-Allow-Origin")
if !ok {
t.Fatalf("location %s missing Access-Control-Allow-Origin header", loc.Path)
}
if originHeader != "https://example.com" {
t.Fatalf("location %s origin header = %q, want %q", loc.Path, originHeader, "https://example.com")
}
}
}
func TestGenerateNginxCfgForWAFPolicyApBundle(t *testing.T) {
t.Parallel()
bundleDir := t.TempDir()
bundleName := "wafv5.tgz"
bundlePath := filepath.Join(bundleDir, bundleName)
if err := os.WriteFile(bundlePath, []byte("bundle"), 0o600); err != nil {
t.Fatalf("failed to create test bundle file: %v", err)
}
cafeIngressEx := createCafeIngressEx()
cafeIngressEx.Ingress.Annotations[PoliciesAnnotationPlus] = "waf-policy"
cafeIngressEx.Policies = map[string]*conf_v1.Policy{