-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathvirtualserver.go
2045 lines (1751 loc) · 62.8 KB
/
virtualserver.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 configs
import (
"fmt"
"strconv"
"strings"
"github.com/golang/glog"
"github.com/nginxinc/kubernetes-ingress/internal/k8s/secrets"
"github.com/nginxinc/kubernetes-ingress/internal/nginx"
conf_v1alpha1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1alpha1"
api_v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"github.com/nginxinc/kubernetes-ingress/internal/configs/version2"
conf_v1 "github.com/nginxinc/kubernetes-ingress/pkg/apis/configuration/v1"
)
const (
nginx502Server = "unix:/var/lib/nginx/nginx-502-server.sock"
internalLocationPrefix = "internal_location_"
nginx418Server = "unix:/var/lib/nginx/nginx-418-server.sock"
specContext = "spec"
routeContext = "route"
subRouteContext = "subroute"
)
var incompatibleLBMethodsForSlowStart = map[string]bool{
"random": true,
"ip_hash": true,
"random two": true,
"random two least_conn": true,
"random two least_time=header": true,
"random two least_time=last_byte": true,
}
// MeshPodOwner contains the type and name of the K8s resource that owns the pod.
// This owner information is needed for NGINX Service Mesh metrics.
type MeshPodOwner struct {
// OwnerType is one of the following: statefulset, daemonset, deployment.
OwnerType string
// OwnerName is the name of the statefulset, daemonset, or deployment.
OwnerName string
}
// PodInfo contains the name of the Pod and the MeshPodOwner information
// which is used for NGINX Service Mesh metrics.
type PodInfo struct {
Name string
MeshPodOwner
}
// VirtualServerEx holds a VirtualServer along with the resources that are referenced in this VirtualServer.
type VirtualServerEx struct {
VirtualServer *conf_v1.VirtualServer
Endpoints map[string][]string
VirtualServerRoutes []*conf_v1.VirtualServerRoute
ExternalNameSvcs map[string]bool
Policies map[string]*conf_v1.Policy
PodsByIP map[string]PodInfo
SecretRefs map[string]*secrets.SecretReference
}
func (vsx *VirtualServerEx) String() string {
if vsx == nil {
return "<nil>"
}
if vsx.VirtualServer == nil {
return "VirtualServerEx has no VirtualServer"
}
return fmt.Sprintf("%s/%s", vsx.VirtualServer.Namespace, vsx.VirtualServer.Name)
}
// GenerateEndpointsKey generates a key for the Endpoints map in VirtualServerEx.
func GenerateEndpointsKey(
serviceNamespace string,
serviceName string,
subselector map[string]string,
port uint16,
) string {
if len(subselector) > 0 {
return fmt.Sprintf("%s/%s_%s:%d", serviceNamespace, serviceName, labels.Set(subselector).String(), port)
}
return fmt.Sprintf("%s/%s:%d", serviceNamespace, serviceName, port)
}
type upstreamNamer struct {
prefix string
namespace string
}
func newUpstreamNamerForVirtualServer(virtualServer *conf_v1.VirtualServer) *upstreamNamer {
return &upstreamNamer{
prefix: fmt.Sprintf("vs_%s_%s", virtualServer.Namespace, virtualServer.Name),
namespace: virtualServer.Namespace,
}
}
func newUpstreamNamerForVirtualServerRoute(
virtualServer *conf_v1.VirtualServer,
virtualServerRoute *conf_v1.VirtualServerRoute,
) *upstreamNamer {
return &upstreamNamer{
prefix: fmt.Sprintf(
"vs_%s_%s_vsr_%s_%s",
virtualServer.Namespace,
virtualServer.Name,
virtualServerRoute.Namespace,
virtualServerRoute.Name,
),
namespace: virtualServerRoute.Namespace,
}
}
func newUpstreamNamerForTransportServer(transportServer *conf_v1alpha1.TransportServer) *upstreamNamer {
return &upstreamNamer{
prefix: fmt.Sprintf("ts_%s_%s", transportServer.Namespace, transportServer.Name),
}
}
func (namer *upstreamNamer) GetNameForUpstreamFromAction(action *conf_v1.Action) string {
var upstream string
if action.Proxy != nil && action.Proxy.Upstream != "" {
upstream = action.Proxy.Upstream
} else {
upstream = action.Pass
}
return fmt.Sprintf("%s_%s", namer.prefix, upstream)
}
func (namer *upstreamNamer) GetNameForUpstream(upstream string) string {
return fmt.Sprintf("%s_%s", namer.prefix, upstream)
}
type variableNamer struct {
safeNsName string
}
func newVariableNamer(virtualServer *conf_v1.VirtualServer) *variableNamer {
safeNsName := strings.ReplaceAll(fmt.Sprintf("%s_%s", virtualServer.Namespace, virtualServer.Name), "-", "_")
return &variableNamer{
safeNsName: safeNsName,
}
}
func (namer *variableNamer) GetNameForSplitClientVariable(index int) string {
return fmt.Sprintf("$vs_%s_splits_%d", namer.safeNsName, index)
}
func (namer *variableNamer) GetNameForVariableForMatchesRouteMap(
matchesIndex int,
matchIndex int,
conditionIndex int,
) string {
return fmt.Sprintf("$vs_%s_matches_%d_match_%d_cond_%d", namer.safeNsName, matchesIndex, matchIndex, conditionIndex)
}
func (namer *variableNamer) GetNameForVariableForMatchesRouteMainMap(matchesIndex int) string {
return fmt.Sprintf("$vs_%s_matches_%d", namer.safeNsName, matchesIndex)
}
func newHealthCheckWithDefaults(
upstream conf_v1.Upstream,
upstreamName string,
cfgParams *ConfigParams,
) *version2.HealthCheck {
return &version2.HealthCheck{
Name: upstreamName,
URI: "/",
Interval: "5s",
Jitter: "0s",
Fails: 1,
Passes: 1,
Port: int(upstream.Port),
ProxyPass: fmt.Sprintf("%v://%v", generateProxyPassProtocol(upstream.TLS.Enable), upstreamName),
ProxyConnectTimeout: generateString(upstream.ProxyConnectTimeout, cfgParams.ProxyConnectTimeout),
ProxyReadTimeout: generateString(upstream.ProxyReadTimeout, cfgParams.ProxyReadTimeout),
ProxySendTimeout: generateString(upstream.ProxySendTimeout, cfgParams.ProxySendTimeout),
Headers: make(map[string]string),
}
}
// VirtualServerConfigurator generates a VirtualServer configuration
type virtualServerConfigurator struct {
cfgParams *ConfigParams
isPlus bool
isResolverConfigured bool
isTLSPassthrough bool
enableSnippets bool
warnings Warnings
spiffeCerts bool
}
func (vsc *virtualServerConfigurator) addWarningf(obj runtime.Object, msgFmt string, args ...interface{}) {
vsc.warnings.AddWarningf(obj, msgFmt, args...)
}
func (vsc *virtualServerConfigurator) addWarnings(obj runtime.Object, msgs []string) {
for _, msg := range msgs {
vsc.warnings.AddWarning(obj, msg)
}
}
func (vsc *virtualServerConfigurator) clearWarnings() {
vsc.warnings = make(map[runtime.Object][]string)
}
// newVirtualServerConfigurator creates a new VirtualServerConfigurator
func newVirtualServerConfigurator(
cfgParams *ConfigParams,
isPlus bool,
isResolverConfigured bool,
staticParams *StaticConfigParams,
) *virtualServerConfigurator {
return &virtualServerConfigurator{
cfgParams: cfgParams,
isPlus: isPlus,
isResolverConfigured: isResolverConfigured,
isTLSPassthrough: staticParams.TLSPassthrough,
enableSnippets: staticParams.EnableSnippets,
warnings: make(map[runtime.Object][]string),
spiffeCerts: staticParams.NginxServiceMesh,
}
}
func (vsc *virtualServerConfigurator) generateEndpointsForUpstream(
owner runtime.Object,
namespace string,
upstream conf_v1.Upstream,
virtualServerEx *VirtualServerEx,
) []string {
endpointsKey := GenerateEndpointsKey(namespace, upstream.Service, upstream.Subselector, upstream.Port)
externalNameSvcKey := GenerateExternalNameSvcKey(namespace, upstream.Service)
endpoints := virtualServerEx.Endpoints[endpointsKey]
if !vsc.isPlus && len(endpoints) == 0 {
return []string{nginx502Server}
}
_, isExternalNameSvc := virtualServerEx.ExternalNameSvcs[externalNameSvcKey]
if isExternalNameSvc && !vsc.isResolverConfigured {
msgFmt := "Type ExternalName service %v in upstream %v will be ignored. To use ExternaName services, a resolver must be configured in the ConfigMap"
vsc.addWarningf(owner, msgFmt, upstream.Service, upstream.Name)
endpoints = []string{}
}
return endpoints
}
// GenerateVirtualServerConfig generates a full configuration for a VirtualServer
func (vsc *virtualServerConfigurator) GenerateVirtualServerConfig(vsEx *VirtualServerEx) (version2.VirtualServerConfig, Warnings) {
vsc.clearWarnings()
sslConfig := vsc.generateSSLConfig(vsEx.VirtualServer, vsEx.VirtualServer.Spec.TLS, vsEx.VirtualServer.Namespace, vsEx.SecretRefs, vsc.cfgParams)
tlsRedirectConfig := generateTLSRedirectConfig(vsEx.VirtualServer.Spec.TLS)
policyOpts := policyOptions{
tls: sslConfig != nil,
secretRefs: vsEx.SecretRefs,
}
ownerDetails := policyOwnerDetails{
owner: vsEx.VirtualServer,
ownerNamespace: vsEx.VirtualServer.Namespace,
vsNamespace: vsEx.VirtualServer.Namespace,
vsName: vsEx.VirtualServer.Name,
}
policiesCfg := vsc.generatePolicies(ownerDetails, vsEx.VirtualServer.Spec.Policies, vsEx.Policies, specContext, policyOpts)
// crUpstreams maps an UpstreamName to its conf_v1.Upstream as they are generated
// necessary for generateLocation to know what Upstream each Location references
crUpstreams := make(map[string]conf_v1.Upstream)
virtualServerUpstreamNamer := newUpstreamNamerForVirtualServer(vsEx.VirtualServer)
var upstreams []version2.Upstream
var statusMatches []version2.StatusMatch
var healthChecks []version2.HealthCheck
var limitReqZones []version2.LimitReqZone
limitReqZones = append(limitReqZones, policiesCfg.LimitReqZones...)
// generate upstreams for VirtualServer
for _, u := range vsEx.VirtualServer.Spec.Upstreams {
if (vsEx.VirtualServer.Spec.TLS != nil || !vsc.cfgParams.HTTP2) && u.GRPC {
vsc.addWarningf(vsEx.VirtualServer, "gRPC will not be enabled for upstream %s. gRPC requires enabled HTTP/2 and TLS termination", u.Name)
}
upstreamName := virtualServerUpstreamNamer.GetNameForUpstream(u.Name)
upstreamNamespace := vsEx.VirtualServer.Namespace
endpoints := vsc.generateEndpointsForUpstream(vsEx.VirtualServer, upstreamNamespace, u, vsEx)
// isExternalNameSvc is always false for OSS
_, isExternalNameSvc := vsEx.ExternalNameSvcs[GenerateExternalNameSvcKey(upstreamNamespace, u.Service)]
ups := vsc.generateUpstream(vsEx.VirtualServer, upstreamName, u, isExternalNameSvc, endpoints)
upstreams = append(upstreams, ups)
u.TLS.Enable = isTLSEnabled(u, vsc.spiffeCerts)
crUpstreams[upstreamName] = u
if hc := generateHealthCheck(u, upstreamName, vsc.cfgParams); hc != nil {
healthChecks = append(healthChecks, *hc)
if u.HealthCheck.StatusMatch != "" {
statusMatches = append(
statusMatches,
generateUpstreamStatusMatch(upstreamName, u.HealthCheck.StatusMatch),
)
}
}
}
// generate upstreams for each VirtualServerRoute
for _, vsr := range vsEx.VirtualServerRoutes {
upstreamNamer := newUpstreamNamerForVirtualServerRoute(vsEx.VirtualServer, vsr)
for _, u := range vsr.Spec.Upstreams {
if (vsEx.VirtualServer.Spec.TLS != nil || !vsc.cfgParams.HTTP2) && u.GRPC {
vsc.addWarningf(vsr, "gRPC will not be enabled for upstream %s. gRPC requires enabled HTTP/2 and TLS termination", u.Name)
}
upstreamName := upstreamNamer.GetNameForUpstream(u.Name)
upstreamNamespace := vsr.Namespace
endpoints := vsc.generateEndpointsForUpstream(vsr, upstreamNamespace, u, vsEx)
// isExternalNameSvc is always false for OSS
_, isExternalNameSvc := vsEx.ExternalNameSvcs[GenerateExternalNameSvcKey(upstreamNamespace, u.Service)]
ups := vsc.generateUpstream(vsr, upstreamName, u, isExternalNameSvc, endpoints)
upstreams = append(upstreams, ups)
u.TLS.Enable = isTLSEnabled(u, vsc.spiffeCerts)
crUpstreams[upstreamName] = u
if hc := generateHealthCheck(u, upstreamName, vsc.cfgParams); hc != nil {
healthChecks = append(healthChecks, *hc)
if u.HealthCheck.StatusMatch != "" {
statusMatches = append(
statusMatches,
generateUpstreamStatusMatch(upstreamName, u.HealthCheck.StatusMatch),
)
}
}
}
}
var locations []version2.Location
var internalRedirectLocations []version2.InternalRedirectLocation
var returnLocations []version2.ReturnLocation
var splitClients []version2.SplitClient
var maps []version2.Map
var errorPageLocations []version2.ErrorPageLocation
var vsrErrorPagesFromVs = make(map[string][]conf_v1.ErrorPage)
var vsrErrorPagesRouteIndex = make(map[string]int)
var vsrLocationSnippetsFromVs = make(map[string]string)
var vsrPoliciesFromVs = make(map[string][]conf_v1.PolicyReference)
isVSR := false
matchesRoutes := 0
variableNamer := newVariableNamer(vsEx.VirtualServer)
// generates config for VirtualServer routes
for _, r := range vsEx.VirtualServer.Spec.Routes {
errorPageIndex := len(errorPageLocations)
errorPageLocations = append(errorPageLocations, generateErrorPageLocations(errorPageIndex, r.ErrorPages)...)
// ignore routes that reference VirtualServerRoute
if r.Route != "" {
name := r.Route
if !strings.Contains(name, "/") {
name = fmt.Sprintf("%v/%v", vsEx.VirtualServer.Namespace, r.Route)
}
// store route location snippet for the referenced VirtualServerRoute in case they don't define their own
if r.LocationSnippets != "" {
vsrLocationSnippetsFromVs[name] = r.LocationSnippets
}
// store route error pages and route index for the referenced VirtualServerRoute in case they don't define their own
if len(r.ErrorPages) > 0 {
vsrErrorPagesFromVs[name] = r.ErrorPages
vsrErrorPagesRouteIndex[name] = errorPageIndex
}
// store route policies for the referenced VirtualServerRoute in case they don't define their own
if len(r.Policies) > 0 {
vsrPoliciesFromVs[name] = r.Policies
}
continue
}
vsLocSnippets := r.LocationSnippets
ownerDetails := policyOwnerDetails{
owner: vsEx.VirtualServer,
ownerNamespace: vsEx.VirtualServer.Namespace,
vsNamespace: vsEx.VirtualServer.Namespace,
vsName: vsEx.VirtualServer.Name,
}
routePoliciesCfg := vsc.generatePolicies(ownerDetails, r.Policies, vsEx.Policies, routeContext, policyOpts)
limitReqZones = append(limitReqZones, routePoliciesCfg.LimitReqZones...)
if len(r.Matches) > 0 {
cfg := generateMatchesConfig(
r,
virtualServerUpstreamNamer,
crUpstreams,
variableNamer,
matchesRoutes,
len(splitClients),
vsc.cfgParams,
r.ErrorPages,
errorPageIndex,
vsLocSnippets,
vsc.enableSnippets,
len(returnLocations),
isVSR,
"", "",
)
addPoliciesCfgToLocations(routePoliciesCfg, cfg.Locations)
maps = append(maps, cfg.Maps...)
locations = append(locations, cfg.Locations...)
internalRedirectLocations = append(internalRedirectLocations, cfg.InternalRedirectLocation)
returnLocations = append(returnLocations, cfg.ReturnLocations...)
splitClients = append(splitClients, cfg.SplitClients...)
matchesRoutes++
} else if len(r.Splits) > 0 {
cfg := generateDefaultSplitsConfig(r, virtualServerUpstreamNamer, crUpstreams, variableNamer, len(splitClients),
vsc.cfgParams, r.ErrorPages, errorPageIndex, r.Path, vsLocSnippets, vsc.enableSnippets, len(returnLocations), isVSR, "", "")
addPoliciesCfgToLocations(routePoliciesCfg, cfg.Locations)
splitClients = append(splitClients, cfg.SplitClients...)
locations = append(locations, cfg.Locations...)
internalRedirectLocations = append(internalRedirectLocations, cfg.InternalRedirectLocation)
returnLocations = append(returnLocations, cfg.ReturnLocations...)
} else {
upstreamName := virtualServerUpstreamNamer.GetNameForUpstreamFromAction(r.Action)
upstream := crUpstreams[upstreamName]
proxySSLName := generateProxySSLName(upstream.Service, vsEx.VirtualServer.Namespace)
loc, returnLoc := generateLocation(r.Path, upstreamName, upstream, r.Action, vsc.cfgParams, r.ErrorPages, false,
errorPageIndex, proxySSLName, r.Path, vsLocSnippets, vsc.enableSnippets, len(returnLocations), isVSR, "", "")
addPoliciesCfgToLocation(routePoliciesCfg, &loc)
locations = append(locations, loc)
if returnLoc != nil {
returnLocations = append(returnLocations, *returnLoc)
}
}
}
// generate config for subroutes of each VirtualServerRoute
for _, vsr := range vsEx.VirtualServerRoutes {
isVSR := true
upstreamNamer := newUpstreamNamerForVirtualServerRoute(vsEx.VirtualServer, vsr)
for _, r := range vsr.Spec.Subroutes {
errorPageIndex := len(errorPageLocations)
errorPageLocations = append(errorPageLocations, generateErrorPageLocations(errorPageIndex, r.ErrorPages)...)
errorPages := r.ErrorPages
vsrNamespaceName := fmt.Sprintf("%v/%v", vsr.Namespace, vsr.Name)
// use the VirtualServer error pages if the route does not define any
if r.ErrorPages == nil {
if vsErrorPages, ok := vsrErrorPagesFromVs[vsrNamespaceName]; ok {
errorPages = vsErrorPages
errorPageIndex = vsrErrorPagesRouteIndex[vsrNamespaceName]
}
}
locSnippets := r.LocationSnippets
// use the VirtualServer location snippet if the route does not define any
if r.LocationSnippets == "" {
locSnippets = vsrLocationSnippetsFromVs[vsrNamespaceName]
}
var ownerDetails policyOwnerDetails
var policyRefs []conf_v1.PolicyReference
var context string
if len(r.Policies) == 0 {
// use the VirtualServer route policies if the route does not define any
ownerDetails = policyOwnerDetails{
owner: vsEx.VirtualServer,
ownerNamespace: vsEx.VirtualServer.Namespace,
vsNamespace: vsEx.VirtualServer.Namespace,
vsName: vsEx.VirtualServer.Name,
}
policyRefs = vsrPoliciesFromVs[vsrNamespaceName]
context = routeContext
} else {
ownerDetails = policyOwnerDetails{
owner: vsr,
ownerNamespace: vsr.Namespace,
vsNamespace: vsEx.VirtualServer.Namespace,
vsName: vsEx.VirtualServer.Name,
}
policyRefs = r.Policies
context = subRouteContext
}
routePoliciesCfg := vsc.generatePolicies(ownerDetails, policyRefs, vsEx.Policies, context, policyOpts)
limitReqZones = append(limitReqZones, routePoliciesCfg.LimitReqZones...)
if len(r.Matches) > 0 {
cfg := generateMatchesConfig(
r,
upstreamNamer,
crUpstreams,
variableNamer,
matchesRoutes,
len(splitClients),
vsc.cfgParams,
errorPages,
errorPageIndex,
locSnippets,
vsc.enableSnippets,
len(returnLocations),
isVSR,
vsr.Name,
vsr.Namespace,
)
addPoliciesCfgToLocations(routePoliciesCfg, cfg.Locations)
maps = append(maps, cfg.Maps...)
locations = append(locations, cfg.Locations...)
internalRedirectLocations = append(internalRedirectLocations, cfg.InternalRedirectLocation)
returnLocations = append(returnLocations, cfg.ReturnLocations...)
splitClients = append(splitClients, cfg.SplitClients...)
matchesRoutes++
} else if len(r.Splits) > 0 {
cfg := generateDefaultSplitsConfig(r, upstreamNamer, crUpstreams, variableNamer, len(splitClients), vsc.cfgParams,
errorPages, errorPageIndex, r.Path, locSnippets, vsc.enableSnippets, len(returnLocations), isVSR, vsr.Name, vsr.Namespace)
addPoliciesCfgToLocations(routePoliciesCfg, cfg.Locations)
splitClients = append(splitClients, cfg.SplitClients...)
locations = append(locations, cfg.Locations...)
internalRedirectLocations = append(internalRedirectLocations, cfg.InternalRedirectLocation)
returnLocations = append(returnLocations, cfg.ReturnLocations...)
} else {
upstreamName := upstreamNamer.GetNameForUpstreamFromAction(r.Action)
upstream := crUpstreams[upstreamName]
proxySSLName := generateProxySSLName(upstream.Service, vsr.Namespace)
loc, returnLoc := generateLocation(r.Path, upstreamName, upstream, r.Action, vsc.cfgParams, errorPages, false,
errorPageIndex, proxySSLName, r.Path, locSnippets, vsc.enableSnippets, len(returnLocations), isVSR, vsr.Name, vsr.Namespace)
addPoliciesCfgToLocation(routePoliciesCfg, &loc)
locations = append(locations, loc)
if returnLoc != nil {
returnLocations = append(returnLocations, *returnLoc)
}
}
}
}
httpSnippets := generateSnippets(vsc.enableSnippets, vsEx.VirtualServer.Spec.HTTPSnippets, []string{""})
serverSnippets := generateSnippets(
vsc.enableSnippets,
vsEx.VirtualServer.Spec.ServerSnippets,
vsc.cfgParams.ServerSnippets,
)
vsCfg := version2.VirtualServerConfig{
Upstreams: upstreams,
SplitClients: splitClients,
Maps: maps,
StatusMatches: statusMatches,
LimitReqZones: removeDuplicateLimitReqZones(limitReqZones),
HTTPSnippets: httpSnippets,
Server: version2.Server{
ServerName: vsEx.VirtualServer.Spec.Host,
StatusZone: vsEx.VirtualServer.Spec.Host,
ProxyProtocol: vsc.cfgParams.ProxyProtocol,
SSL: sslConfig,
ServerTokens: vsc.cfgParams.ServerTokens,
SetRealIPFrom: vsc.cfgParams.SetRealIPFrom,
RealIPHeader: vsc.cfgParams.RealIPHeader,
RealIPRecursive: vsc.cfgParams.RealIPRecursive,
Snippets: serverSnippets,
InternalRedirectLocations: internalRedirectLocations,
Locations: locations,
ReturnLocations: returnLocations,
HealthChecks: healthChecks,
TLSRedirect: tlsRedirectConfig,
ErrorPageLocations: errorPageLocations,
TLSPassthrough: vsc.isTLSPassthrough,
Allow: policiesCfg.Allow,
Deny: policiesCfg.Deny,
LimitReqOptions: policiesCfg.LimitReqOptions,
LimitReqs: policiesCfg.LimitReqs,
JWTAuth: policiesCfg.JWTAuth,
IngressMTLS: policiesCfg.IngressMTLS,
EgressMTLS: policiesCfg.EgressMTLS,
PoliciesErrorReturn: policiesCfg.ErrorReturn,
VSNamespace: vsEx.VirtualServer.Namespace,
VSName: vsEx.VirtualServer.Name,
},
SpiffeCerts: vsc.spiffeCerts,
}
return vsCfg, vsc.warnings
}
type policiesCfg struct {
Allow []string
Deny []string
LimitReqOptions version2.LimitReqOptions
LimitReqZones []version2.LimitReqZone
LimitReqs []version2.LimitReq
JWTAuth *version2.JWTAuth
IngressMTLS *version2.IngressMTLS
EgressMTLS *version2.EgressMTLS
ErrorReturn *version2.Return
}
func newPoliciesConfig() *policiesCfg {
return &policiesCfg{}
}
type policyOwnerDetails struct {
owner runtime.Object
ownerNamespace string
vsNamespace string
vsName string
}
type policyOptions struct {
tls bool
secretRefs map[string]*secrets.SecretReference
}
type validationResults struct {
isError bool
warnings []string
}
func newValidationResults() *validationResults {
return &validationResults{}
}
func (v *validationResults) addWarningf(msgFmt string, args ...interface{}) {
v.warnings = append(v.warnings, fmt.Sprintf(msgFmt, args...))
}
func (p *policiesCfg) addAccessControlConfig(accessControl *conf_v1.AccessControl) *validationResults {
res := newValidationResults()
p.Allow = append(p.Allow, accessControl.Allow...)
p.Deny = append(p.Deny, accessControl.Deny...)
if len(p.Allow) > 0 && len(p.Deny) > 0 {
res.addWarningf(
"AccessControl policy (or policies) with deny rules is overridden by policy (or policies) with allow rules",
)
}
return res
}
func (p *policiesCfg) addRateLimitConfig(
rateLimit *conf_v1.RateLimit,
polKey string,
polNamespace string,
polName string,
vsNamespace string,
vsName string,
) *validationResults {
res := newValidationResults()
rlZoneName := fmt.Sprintf("pol_rl_%v_%v_%v_%v", polNamespace, polName, vsNamespace, vsName)
p.LimitReqs = append(p.LimitReqs, generateLimitReq(rlZoneName, rateLimit))
p.LimitReqZones = append(p.LimitReqZones, generateLimitReqZone(rlZoneName, rateLimit))
if len(p.LimitReqs) == 1 {
p.LimitReqOptions = generateLimitReqOptions(rateLimit)
} else {
curOptions := generateLimitReqOptions(rateLimit)
if curOptions.DryRun != p.LimitReqOptions.DryRun {
res.addWarningf("RateLimit policy %q with limit request option dryRun=%v is overridden to dryRun=%v by the first policy reference in this context", polKey, curOptions.DryRun, p.LimitReqOptions.DryRun)
}
if curOptions.LogLevel != p.LimitReqOptions.LogLevel {
res.addWarningf("RateLimit policy %q with limit request option logLevel=%v is overridden to logLevel=%v by the first policy reference in this context", polKey, curOptions.LogLevel, p.LimitReqOptions.LogLevel)
}
if curOptions.RejectCode != p.LimitReqOptions.RejectCode {
res.addWarningf("RateLimit policy %q with limit request option rejectCode=%v is overridden to rejectCode=%v by the first policy reference in this context", polKey, curOptions.RejectCode, p.LimitReqOptions.RejectCode)
}
}
return res
}
func (p *policiesCfg) addJWTAuthConfig(
jwtAuth *conf_v1.JWTAuth,
polKey string,
polNamespace string,
secretRefs map[string]*secrets.SecretReference,
) *validationResults {
res := newValidationResults()
if p.JWTAuth != nil {
res.addWarningf("Multiple jwt policies in the same context is not valid. JWT policy %q will be ignored", polKey)
return res
}
jwtSecretKey := fmt.Sprintf("%v/%v", polNamespace, jwtAuth.Secret)
secret := secretRefs[jwtSecretKey]
if secret.Type != "" && secret.Type != secrets.SecretTypeJWK {
res.addWarningf("JWT policy %q references a Secret of an incorrect type %q", polKey, secret.Type)
res.isError = true
return res
} else if secret.Error != nil {
res.addWarningf("JWT policy %q references an invalid Secret: %v", polKey, secret.Error)
res.isError = true
return res
}
p.JWTAuth = &version2.JWTAuth{
Secret: secret.Path,
Realm: jwtAuth.Realm,
Token: jwtAuth.Token,
}
return res
}
func (p *policiesCfg) addIngressMTLSConfig(
ingressMTLS *conf_v1.IngressMTLS,
polKey string,
polNamespace string,
context string,
tls bool,
secretRefs map[string]*secrets.SecretReference,
) *validationResults {
res := newValidationResults()
if !tls {
res.addWarningf("TLS configuration needed for IngressMTLS policy")
res.isError = true
return res
}
if context != specContext {
res.addWarningf("IngressMTLS policy is not allowed in the %v context", context)
res.isError = true
return res
}
if p.IngressMTLS != nil {
res.addWarningf("Multiple ingressMTLS policies are not allowed. IngressMTLS policy %q will be ignored", polKey)
return res
}
secretKey := fmt.Sprintf("%v/%v", polNamespace, ingressMTLS.ClientCertSecret)
secret := secretRefs[secretKey]
if secret.Type != "" && secret.Type != secrets.SecretTypeCA {
res.addWarningf("IngressMTLS policy %q references a Secret of an incorrect type %q", polKey, secret.Type)
res.isError = true
return res
} else if secret.Error != nil {
res.addWarningf("IngressMTLS policy %q references an invalid Secret: %v", polKey, secret.Error)
res.isError = true
return res
}
verifyDepth := 1
verifyClient := "on"
if ingressMTLS.VerifyDepth != nil {
verifyDepth = *ingressMTLS.VerifyDepth
}
if ingressMTLS.VerifyClient != "" {
verifyClient = ingressMTLS.VerifyClient
}
p.IngressMTLS = &version2.IngressMTLS{
ClientCert: secret.Path,
VerifyClient: verifyClient,
VerifyDepth: verifyDepth,
}
return res
}
func (p *policiesCfg) addEgressMTLSConfig(
egressMTLS *conf_v1.EgressMTLS,
polKey string,
polNamespace string,
secretRefs map[string]*secrets.SecretReference,
) *validationResults {
res := newValidationResults()
if p.EgressMTLS != nil {
res.addWarningf(
"Multiple egressMTLS policies in the same context is not valid. EgressMTLS policy %q will be ignored",
polKey,
)
return res
}
var tlsSecretPath string
if egressMTLS.TLSSecret != "" {
egressTLSSecret := fmt.Sprintf("%v/%v", polNamespace, egressMTLS.TLSSecret)
tlsSecret := secretRefs[egressTLSSecret]
if tlsSecret.Type != "" && tlsSecret.Type != api_v1.SecretTypeTLS {
res.addWarningf("EgressMTLS policy %q references a Secret of an incorrect type %q", polKey, tlsSecret.Type)
res.isError = true
return res
} else if tlsSecret.Error != nil {
res.addWarningf("EgressMTLS policy %q references an invalid Secret: %v", polKey, tlsSecret.Error)
res.isError = true
return res
}
tlsSecretPath = tlsSecret.Path
}
var trustedSecretPath string
if egressMTLS.TrustedCertSecret != "" {
trustedCertSecret := fmt.Sprintf("%v/%v", polNamespace, egressMTLS.TrustedCertSecret)
trustedSecret := secretRefs[trustedCertSecret]
if trustedSecret.Type != "" && trustedSecret.Type != secrets.SecretTypeCA {
res.addWarningf("EgressMTLS policy %q references a Secret of an incorrect type %q", polKey, trustedSecret.Type)
res.isError = true
return res
} else if trustedSecret.Error != nil {
res.addWarningf("EgressMTLS policy %q references an invalid Secret: %v", polKey, trustedSecret.Error)
res.isError = true
return res
}
trustedSecretPath = trustedSecret.Path
}
p.EgressMTLS = &version2.EgressMTLS{
Certificate: tlsSecretPath,
CertificateKey: tlsSecretPath,
Ciphers: generateString(egressMTLS.Ciphers, "DEFAULT"),
Protocols: generateString(egressMTLS.Protocols, "TLSv1 TLSv1.1 TLSv1.2"),
VerifyServer: egressMTLS.VerifyServer,
VerifyDepth: generateIntFromPointer(egressMTLS.VerifyDepth, 1),
SessionReuse: generateBool(egressMTLS.SessionReuse, true),
ServerName: egressMTLS.ServerName,
TrustedCert: trustedSecretPath,
SSLName: generateString(egressMTLS.SSLName, "$proxy_host"),
}
return res
}
func (vsc *virtualServerConfigurator) generatePolicies(
ownerDetails policyOwnerDetails,
policyRefs []conf_v1.PolicyReference,
policies map[string]*conf_v1.Policy,
context string,
policyOpts policyOptions,
) policiesCfg {
config := newPoliciesConfig()
for _, p := range policyRefs {
polNamespace := p.Namespace
if polNamespace == "" {
polNamespace = ownerDetails.ownerNamespace
}
key := fmt.Sprintf("%s/%s", polNamespace, p.Name)
if pol, exists := policies[key]; exists {
var res *validationResults
switch {
case pol.Spec.AccessControl != nil:
res = config.addAccessControlConfig(pol.Spec.AccessControl)
case pol.Spec.RateLimit != nil:
res = config.addRateLimitConfig(
pol.Spec.RateLimit,
key,
polNamespace,
p.Name,
ownerDetails.vsNamespace,
ownerDetails.vsName,
)
case pol.Spec.JWTAuth != nil:
res = config.addJWTAuthConfig(pol.Spec.JWTAuth, key, polNamespace, policyOpts.secretRefs)
case pol.Spec.IngressMTLS != nil:
res = config.addIngressMTLSConfig(
pol.Spec.IngressMTLS,
key,
polNamespace,
context,
policyOpts.tls,
policyOpts.secretRefs,
)
case pol.Spec.EgressMTLS != nil:
res = config.addEgressMTLSConfig(pol.Spec.EgressMTLS, key, polNamespace, policyOpts.secretRefs)
default:
res = newValidationResults()
}
vsc.addWarnings(ownerDetails.owner, res.warnings)
if res.isError {
return policiesCfg{
ErrorReturn: &version2.Return{Code: 500},
}
}
} else {
vsc.addWarningf(ownerDetails.owner, "Policy %s is missing or invalid", key)
return policiesCfg{
ErrorReturn: &version2.Return{Code: 500},
}
}
}
return *config
}
func generateLimitReq(zoneName string, rateLimitPol *conf_v1.RateLimit) version2.LimitReq {
var limitReq version2.LimitReq
limitReq.ZoneName = zoneName
if rateLimitPol.Burst != nil {
limitReq.Burst = *rateLimitPol.Burst
}
if rateLimitPol.Delay != nil {
limitReq.Delay = *rateLimitPol.Delay
}
limitReq.NoDelay = generateBool(rateLimitPol.NoDelay, false)
if limitReq.NoDelay {
limitReq.Delay = 0
}
return limitReq
}
func generateLimitReqZone(zoneName string, rateLimitPol *conf_v1.RateLimit) version2.LimitReqZone {
return version2.LimitReqZone{
ZoneName: zoneName,
Key: rateLimitPol.Key,
ZoneSize: rateLimitPol.ZoneSize,
Rate: rateLimitPol.Rate,
}
}
func generateLimitReqOptions(rateLimitPol *conf_v1.RateLimit) version2.LimitReqOptions {
return version2.LimitReqOptions{
DryRun: generateBool(rateLimitPol.DryRun, false),
LogLevel: generateString(rateLimitPol.LogLevel, "error"),
RejectCode: generateIntFromPointer(rateLimitPol.RejectCode, 503),
}
}
func removeDuplicateLimitReqZones(rlz []version2.LimitReqZone) []version2.LimitReqZone {
encountered := make(map[string]bool)
result := []version2.LimitReqZone{}
for _, v := range rlz {
if !encountered[v.ZoneName] {
encountered[v.ZoneName] = true
result = append(result, v)
}
}
return result
}
func addPoliciesCfgToLocation(cfg policiesCfg, location *version2.Location) {
location.Allow = cfg.Allow
location.Deny = cfg.Deny
location.LimitReqOptions = cfg.LimitReqOptions
location.LimitReqs = cfg.LimitReqs
location.JWTAuth = cfg.JWTAuth
location.EgressMTLS = cfg.EgressMTLS
location.PoliciesErrorReturn = cfg.ErrorReturn
}
func addPoliciesCfgToLocations(cfg policiesCfg, locations []version2.Location) {
for i := range locations {
addPoliciesCfgToLocation(cfg, &locations[i])
}
}
func getUpstreamResourceLabels(owner runtime.Object) version2.UpstreamLabels {
var resourceType, resourceName, resourceNamespace string
switch owner := owner.(type) {
case *conf_v1.VirtualServer:
resourceType = "virtualserver"
resourceName = owner.Name
resourceNamespace = owner.Namespace
case *conf_v1.VirtualServerRoute:
resourceType = "virtualserverroute"
resourceName = owner.Name
resourceNamespace = owner.Namespace
}
return version2.UpstreamLabels{
ResourceType: resourceType,
ResourceName: resourceName,
ResourceNamespace: resourceNamespace,
}
}
func (vsc *virtualServerConfigurator) generateUpstream(
owner runtime.Object,
upstreamName string,
upstream conf_v1.Upstream,
isExternalNameSvc bool,
endpoints []string,
) version2.Upstream {
var upsServers []version2.UpstreamServer
for _, e := range endpoints {
s := version2.UpstreamServer{
Address: e,
}
upsServers = append(upsServers, s)
}