-
Notifications
You must be signed in to change notification settings - Fork 352
/
filters.go
901 lines (815 loc) · 29.1 KB
/
filters.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
// Copyright Envoy Gateway Authors
// SPDX-License-Identifier: Apache-2.0
// The full text of the Apache license is available in the LICENSE file at
// the root of the repo.
package gatewayapi
import (
"fmt"
"net"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/gateway-api/apis/v1alpha2"
"sigs.k8s.io/gateway-api/apis/v1beta1"
egv1a1 "github.com/envoyproxy/gateway/api/v1alpha1"
"github.com/envoyproxy/gateway/internal/ir"
)
type FiltersTranslator interface {
HTTPFiltersTranslator
}
var _ FiltersTranslator = (*Translator)(nil)
type HTTPFiltersTranslator interface {
processURLRewriteFilter(rewrite *v1beta1.HTTPURLRewriteFilter, filterContext *HTTPFiltersContext)
processRedirectFilter(redirect *v1beta1.HTTPRequestRedirectFilter, filterContext *HTTPFiltersContext)
processRequestHeaderModifierFilter(headerModifier *v1beta1.HTTPHeaderFilter, filterContext *HTTPFiltersContext)
processResponseHeaderModifierFilter(headerModifier *v1beta1.HTTPHeaderFilter, filterContext *HTTPFiltersContext)
processRequestMirrorFilter(mirror *v1beta1.HTTPRequestMirrorFilter, filterContext *HTTPFiltersContext, resources *Resources)
processExtensionRefHTTPFilter(extRef *v1beta1.LocalObjectReference, filterContext *HTTPFiltersContext, resources *Resources)
processUnsupportedHTTPFilter(filterType string, filterContext *HTTPFiltersContext)
}
// HTTPFiltersContext is the context of http filters processing.
type HTTPFiltersContext struct {
*HTTPFilterIR
ParentRef *RouteParentContext
Route RouteContext
}
// HTTPFilterIR contains the ir processing results.
type HTTPFilterIR struct {
DirectResponse *ir.DirectResponse
RedirectResponse *ir.Redirect
URLRewrite *ir.URLRewrite
AddRequestHeaders []ir.AddHeader
RemoveRequestHeaders []string
AddResponseHeaders []ir.AddHeader
RemoveResponseHeaders []string
Mirrors []*ir.RouteDestination
RequestAuthentication *ir.RequestAuthentication
RateLimit *ir.RateLimit
ExtensionRefs []*ir.UnstructuredRef
}
// ProcessHTTPFilters translates gateway api http filters to IRs.
func (t *Translator) ProcessHTTPFilters(parentRef *RouteParentContext,
route RouteContext,
filters []v1beta1.HTTPRouteFilter,
resources *Resources) *HTTPFiltersContext {
httpFiltersContext := &HTTPFiltersContext{
ParentRef: parentRef,
Route: route,
HTTPFilterIR: &HTTPFilterIR{},
}
for i := range filters {
filter := filters[i]
// If an invalid filter type has been configured then skip processing any more filters
if httpFiltersContext.DirectResponse != nil {
break
}
if err := ValidateHTTPRouteFilter(&filter, t.ExtensionGroupKinds...); err != nil {
t.processInvalidHTTPFilter(string(filter.Type), httpFiltersContext, err)
break
}
switch filter.Type {
case v1beta1.HTTPRouteFilterURLRewrite:
t.processURLRewriteFilter(filter.URLRewrite, httpFiltersContext)
case v1beta1.HTTPRouteFilterRequestRedirect:
t.processRedirectFilter(filter.RequestRedirect, httpFiltersContext)
case v1beta1.HTTPRouteFilterRequestHeaderModifier:
t.processRequestHeaderModifierFilter(filter.RequestHeaderModifier, httpFiltersContext)
case v1beta1.HTTPRouteFilterResponseHeaderModifier:
t.processResponseHeaderModifierFilter(filter.ResponseHeaderModifier, httpFiltersContext)
case v1beta1.HTTPRouteFilterRequestMirror:
t.processRequestMirrorFilter(filter.RequestMirror, httpFiltersContext, resources)
case v1beta1.HTTPRouteFilterExtensionRef:
t.processExtensionRefHTTPFilter(filter.ExtensionRef, httpFiltersContext, resources)
default:
t.processUnsupportedHTTPFilter(string(filter.Type), httpFiltersContext)
}
}
return httpFiltersContext
}
// ProcessGRPCFilters translates gateway api grpc filters to IRs.
func (t *Translator) ProcessGRPCFilters(parentRef *RouteParentContext,
route RouteContext,
filters []v1alpha2.GRPCRouteFilter,
resources *Resources) *HTTPFiltersContext {
httpFiltersContext := &HTTPFiltersContext{
ParentRef: parentRef,
Route: route,
HTTPFilterIR: &HTTPFilterIR{},
}
for i := range filters {
filter := filters[i]
// If an invalid filter type has been configured then skip processing any more filters
if httpFiltersContext.DirectResponse != nil {
break
}
if err := ValidateGRPCRouteFilter(&filter); err != nil {
t.processInvalidHTTPFilter(string(filter.Type), httpFiltersContext, err)
break
}
switch filter.Type {
case v1alpha2.GRPCRouteFilterRequestHeaderModifier:
t.processRequestHeaderModifierFilter(filter.RequestHeaderModifier, httpFiltersContext)
case v1alpha2.GRPCRouteFilterResponseHeaderModifier:
t.processResponseHeaderModifierFilter(filter.ResponseHeaderModifier, httpFiltersContext)
case v1alpha2.GRPCRouteFilterRequestMirror:
t.processRequestMirrorFilter(filter.RequestMirror, httpFiltersContext, resources)
default:
t.processUnsupportedHTTPFilter(string(filter.Type), httpFiltersContext)
}
}
return httpFiltersContext
}
func (t *Translator) processURLRewriteFilter(
rewrite *v1beta1.HTTPURLRewriteFilter,
filterContext *HTTPFiltersContext) {
if filterContext.URLRewrite != nil {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"Cannot configure multiple urlRewrite filters for a single HTTPRouteRule",
)
return
}
if rewrite == nil {
return
}
newURLRewrite := &ir.URLRewrite{}
if rewrite.Hostname != nil {
if err := t.validateHostname(string(*rewrite.Hostname)); err != nil {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
err.Error(),
)
return
}
redirectHost := string(*rewrite.Hostname)
newURLRewrite.Hostname = &redirectHost
}
if rewrite.Path != nil {
switch rewrite.Path.Type {
case v1beta1.FullPathHTTPPathModifier:
if rewrite.Path.ReplacePrefixMatch != nil {
errMsg := "ReplacePrefixMatch cannot be set when rewrite path type is \"ReplaceFullPath\""
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
if rewrite.Path.ReplaceFullPath == nil {
errMsg := "ReplaceFullPath must be set when rewrite path type is \"ReplaceFullPath\""
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
if rewrite.Path.ReplaceFullPath != nil {
newURLRewrite.Path = &ir.HTTPPathModifier{
FullReplace: rewrite.Path.ReplaceFullPath,
}
}
case v1beta1.PrefixMatchHTTPPathModifier:
if rewrite.Path.ReplaceFullPath != nil {
errMsg := "ReplaceFullPath cannot be set when rewrite path type is \"ReplacePrefixMatch\""
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
if rewrite.Path.ReplacePrefixMatch == nil {
errMsg := "ReplacePrefixMatch must be set when rewrite path type is \"ReplacePrefixMatch\""
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
if rewrite.Path.ReplacePrefixMatch != nil {
newURLRewrite.Path = &ir.HTTPPathModifier{
PrefixMatchReplace: rewrite.Path.ReplacePrefixMatch,
}
}
default:
errMsg := fmt.Sprintf("Rewrite path type: %s is invalid, only \"ReplaceFullPath\" and \"ReplacePrefixMatch\" are supported", rewrite.Path.Type)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
}
filterContext.URLRewrite = newURLRewrite
}
func (t *Translator) processRedirectFilter(
redirect *v1beta1.HTTPRequestRedirectFilter,
filterContext *HTTPFiltersContext) {
// Can't have two redirects for the same route
if filterContext.RedirectResponse != nil {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"Cannot configure multiple requestRedirect filters for a single HTTPRouteRule",
)
return
}
if redirect == nil {
return
}
redir := &ir.Redirect{}
if redirect.Scheme != nil {
// Note that gateway API may support additional schemes in the future, but unknown values
// must result in an UnsupportedValue status
if *redirect.Scheme == "http" || *redirect.Scheme == "https" {
redir.Scheme = redirect.Scheme
} else {
errMsg := fmt.Sprintf("Scheme: %s is unsupported, only 'https' and 'http' are supported", *redirect.Scheme)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
}
if redirect.Hostname != nil {
if err := t.validateHostname(string(*redirect.Hostname)); err != nil {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
err.Error(),
)
} else {
redirectHost := string(*redirect.Hostname)
redir.Hostname = &redirectHost
}
}
if redirect.Path != nil {
switch redirect.Path.Type {
case v1beta1.FullPathHTTPPathModifier:
if redirect.Path.ReplaceFullPath != nil {
redir.Path = &ir.HTTPPathModifier{
FullReplace: redirect.Path.ReplaceFullPath,
}
}
case v1beta1.PrefixMatchHTTPPathModifier:
if redirect.Path.ReplacePrefixMatch != nil {
redir.Path = &ir.HTTPPathModifier{
PrefixMatchReplace: redirect.Path.ReplacePrefixMatch,
}
}
default:
errMsg := fmt.Sprintf("Redirect path type: %s is invalid, only \"ReplaceFullPath\" and \"ReplacePrefixMatch\" are supported", redirect.Path.Type)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
}
if redirect.StatusCode != nil {
redirectCode := int32(*redirect.StatusCode)
// Envoy supports 302, 303, 307, and 308, but gateway API only includes 301 and 302
if redirectCode == 301 || redirectCode == 302 {
redir.StatusCode = &redirectCode
} else {
errMsg := fmt.Sprintf("Status code %d is invalid, only 302 and 301 are supported", redirectCode)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
return
}
}
if redirect.Port != nil {
redirectPort := uint32(*redirect.Port)
redir.Port = &redirectPort
}
filterContext.RedirectResponse = redir
}
func (t *Translator) processRequestHeaderModifierFilter(
headerModifier *v1beta1.HTTPHeaderFilter,
filterContext *HTTPFiltersContext) {
// Make sure the header modifier config actually exists
if headerModifier == nil {
return
}
emptyFilterConfig := true // keep track of whether the provided config is empty or not
// Add request headers
if headersToAdd := headerModifier.Add; headersToAdd != nil {
if len(headersToAdd) > 0 {
emptyFilterConfig = false
}
for _, addHeader := range headersToAdd {
emptyFilterConfig = false
if addHeader.Name == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot add a header with an empty name",
)
// try to process the rest of the headers and produce a valid config.
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(addHeader.Name), "/") || strings.Contains(string(addHeader.Name), ":") {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: %q", string(addHeader.Name)),
)
continue
}
// Check if the header is a duplicate
headerKey := string(addHeader.Name)
canAddHeader := true
for _, h := range filterContext.AddRequestHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
continue
}
newHeader := ir.AddHeader{
Name: headerKey,
Append: true,
Value: addHeader.Value,
}
filterContext.AddRequestHeaders = append(filterContext.AddRequestHeaders, newHeader)
}
}
// Set headers
if headersToSet := headerModifier.Set; headersToSet != nil {
if len(headersToSet) > 0 {
emptyFilterConfig = false
}
for _, setHeader := range headersToSet {
if setHeader.Name == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot set a header with an empty name",
)
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(setHeader.Name), "/") || strings.Contains(string(setHeader.Name), ":") {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("RequestHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: '%s'", string(setHeader.Name)),
)
continue
}
// Check if the header to be set has already been configured
headerKey := string(setHeader.Name)
canAddHeader := true
for _, h := range filterContext.AddRequestHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
continue
}
newHeader := ir.AddHeader{
Name: string(setHeader.Name),
Append: false,
Value: setHeader.Value,
}
filterContext.AddRequestHeaders = append(filterContext.AddRequestHeaders, newHeader)
}
}
// Remove request headers
// As far as Envoy is concerned, it is ok to configure a header to be added/set and also in the list of
// headers to remove. It will remove the original header if present and then add/set the header after.
if headersToRemove := headerModifier.Remove; headersToRemove != nil {
if len(headersToRemove) > 0 {
emptyFilterConfig = false
}
for _, removedHeader := range headersToRemove {
if removedHeader == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter cannot remove a header with an empty name",
)
continue
}
canRemHeader := true
for _, h := range filterContext.RemoveRequestHeaders {
if strings.EqualFold(h, removedHeader) {
canRemHeader = false
break
}
}
if !canRemHeader {
continue
}
filterContext.RemoveRequestHeaders = append(filterContext.RemoveRequestHeaders, removedHeader)
}
}
// Update the status if the filter failed to configure any valid headers to add/remove
if len(filterContext.AddRequestHeaders) == 0 && len(filterContext.RemoveRequestHeaders) == 0 && !emptyFilterConfig {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"RequestHeaderModifier Filter did not provide valid configuration to add/set/remove any headers",
)
}
}
func (t *Translator) processResponseHeaderModifierFilter(
headerModifier *v1beta1.HTTPHeaderFilter,
filterContext *HTTPFiltersContext) {
// Make sure the header modifier config actually exists
if headerModifier == nil {
return
}
emptyFilterConfig := true // keep track of whether the provided config is empty or not
// Add response headers
if headersToAdd := headerModifier.Add; headersToAdd != nil {
if len(headersToAdd) > 0 {
emptyFilterConfig = false
}
for _, addHeader := range headersToAdd {
emptyFilterConfig = false
if addHeader.Name == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"ResponseHeaderModifier Filter cannot add a header with an empty name",
)
// try to process the rest of the headers and produce a valid config.
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(addHeader.Name), "/") || strings.Contains(string(addHeader.Name), ":") {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("ResponseHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: %q", string(addHeader.Name)),
)
continue
}
// Check if the header is a duplicate
headerKey := string(addHeader.Name)
canAddHeader := true
for _, h := range filterContext.AddResponseHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
continue
}
newHeader := ir.AddHeader{
Name: headerKey,
Append: true,
Value: addHeader.Value,
}
filterContext.AddResponseHeaders = append(filterContext.AddResponseHeaders, newHeader)
}
}
// Set headers
if headersToSet := headerModifier.Set; headersToSet != nil {
if len(headersToSet) > 0 {
emptyFilterConfig = false
}
for _, setHeader := range headersToSet {
if setHeader.Name == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"ResponseHeaderModifier Filter cannot set a header with an empty name",
)
continue
}
// Per Gateway API specification on HTTPHeaderName, : and / are invalid characters in header names
if strings.Contains(string(setHeader.Name), "/") || strings.Contains(string(setHeader.Name), ":") {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
fmt.Sprintf("ResponseHeaderModifier Filter cannot set headers with a '/' or ':' character in them. Header: '%s'", string(setHeader.Name)),
)
continue
}
// Check if the header to be set has already been configured
headerKey := string(setHeader.Name)
canAddHeader := true
for _, h := range filterContext.AddResponseHeaders {
if strings.EqualFold(h.Name, headerKey) {
canAddHeader = false
break
}
}
if !canAddHeader {
continue
}
newHeader := ir.AddHeader{
Name: string(setHeader.Name),
Append: false,
Value: setHeader.Value,
}
filterContext.AddResponseHeaders = append(filterContext.AddResponseHeaders, newHeader)
}
}
// Remove response headers
// As far as Envoy is concerned, it is ok to configure a header to be added/set and also in the list of
// headers to remove. It will remove the original header if present and then add/set the header after.
if headersToRemove := headerModifier.Remove; headersToRemove != nil {
if len(headersToRemove) > 0 {
emptyFilterConfig = false
}
for _, removedHeader := range headersToRemove {
if removedHeader == "" {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"ResponseHeaderModifier Filter cannot remove a header with an empty name",
)
continue
}
canRemHeader := true
for _, h := range filterContext.RemoveResponseHeaders {
if strings.EqualFold(h, removedHeader) {
canRemHeader = false
break
}
}
if !canRemHeader {
continue
}
filterContext.RemoveResponseHeaders = append(filterContext.RemoveResponseHeaders, removedHeader)
}
}
// Update the status if the filter failed to configure any valid headers to add/remove
if len(filterContext.AddResponseHeaders) == 0 && len(filterContext.RemoveResponseHeaders) == 0 && !emptyFilterConfig {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
"ResponseHeaderModifier Filter did not provide valid configuration to add/set/remove any headers",
)
}
}
func (t *Translator) processExtensionRefHTTPFilter(extFilter *v1beta1.LocalObjectReference, filterContext *HTTPFiltersContext, resources *Resources) {
// Make sure the config actually exists.
if extFilter == nil {
return
}
filterNs := filterContext.Route.GetNamespace()
// Set the filter context and return early if a matching AuthenticationFilter is found.
if string(extFilter.Kind) == egv1a1.KindAuthenticationFilter {
for _, authenFilter := range resources.AuthenticationFilters {
if authenFilter.Namespace == filterNs &&
authenFilter.Name == string(extFilter.Name) {
filterContext.HTTPFilterIR.RequestAuthentication = &ir.RequestAuthentication{
JWT: &ir.JwtRequestAuthentication{
Providers: authenFilter.Spec.JwtProviders,
},
}
return
}
}
}
// Set the filter context and return early if a matching RateLimitFilter is found.
if string(extFilter.Kind) == egv1a1.KindRateLimitFilter {
for _, rateLimitFilter := range resources.RateLimitFilters {
if rateLimitFilter.Namespace == filterNs &&
rateLimitFilter.Name == string(extFilter.Name) {
if rateLimitFilter.Spec.Global == nil {
errMsg := fmt.Sprintf("Global configuration empty for RateLimitFilter: %s/%s", filterNs,
extFilter.Name)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
return
}
if !t.GlobalRateLimitEnabled {
errMsg := fmt.Sprintf("Enable Ratelimit in the EnvoyGateway config to configure RateLimitFilter: %s/%s",
filterNs, extFilter.Name)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
return
}
rateLimit := &ir.RateLimit{
Global: &ir.GlobalRateLimit{
Rules: make([]*ir.RateLimitRule, len(rateLimitFilter.Spec.Global.Rules)),
},
}
rules := rateLimit.Global.Rules
for i, rule := range rateLimitFilter.Spec.Global.Rules {
rules[i] = &ir.RateLimitRule{
Limit: &ir.RateLimitValue{
Requests: rule.Limit.Requests,
Unit: ir.RateLimitUnit(rule.Limit.Unit),
},
HeaderMatches: make([]*ir.StringMatch, 0),
}
for _, match := range rule.ClientSelectors {
for _, header := range match.Headers {
switch {
case header.Type == nil && header.Value != nil:
fallthrough
case *header.Type == egv1a1.HeaderMatchExact && header.Value != nil:
m := &ir.StringMatch{
Name: header.Name,
Exact: header.Value,
}
rules[i].HeaderMatches = append(rules[i].HeaderMatches, m)
case *header.Type == egv1a1.HeaderMatchRegularExpression && header.Value != nil:
m := &ir.StringMatch{
Name: header.Name,
SafeRegex: header.Value,
}
rules[i].HeaderMatches = append(rules[i].HeaderMatches, m)
case *header.Type == egv1a1.HeaderMatchDistinct && header.Value == nil:
m := &ir.StringMatch{
Name: header.Name,
Distinct: true,
}
rules[i].HeaderMatches = append(rules[i].HeaderMatches, m)
default:
// set negative status condition.
errMsg := fmt.Sprintf("Unable to translate RateLimitFilter. Either the header.Type is not valid or the header is missing a value: %s/%s", filterNs,
extFilter.Name)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
return
}
}
if match.SourceCIDR != nil || match.SourceIP != nil {
sourceCIDR := ""
// distinct means that each IP Address within the specified Source IP CIDR is treated as a
// distinct client selector and uses a separate rate limit bucket/counter.
distinct := false
if match.SourceCIDR != nil {
sourceCIDR = match.SourceCIDR.Value
if match.SourceCIDR.Type != nil && *match.SourceCIDR.Type == egv1a1.SourceMatchDistinct {
distinct = true
}
} else {
sourceCIDR = *match.SourceIP
}
ip, ipn, err := net.ParseCIDR(sourceCIDR)
if err != nil {
errMsg := fmt.Sprintf("Unable to translate RateLimitFilter: %s/%s", filterNs,
extFilter.Name)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
return
}
mask, _ := ipn.Mask.Size()
rules[i].CIDRMatch = &ir.CIDRMatch{
CIDR: ipn.String(),
IPv6: ip.To4() == nil,
MaskLen: mask,
Distinct: distinct,
}
}
}
}
filterContext.HTTPFilterIR.RateLimit = rateLimit
return
}
}
}
// This list of resources will be empty unless an extension is loaded (and introduces resources)
for _, res := range resources.ExtensionRefFilters {
if res.GetKind() == string(extFilter.Kind) && res.GetName() == string(extFilter.Name) && res.GetNamespace() == filterNs {
apiVers := res.GetAPIVersion()
// To get only the group we cut off the version.
// This could be a one liner but just to be safe we check that the APIVersion is properly formatted
idx := strings.IndexByte(apiVers, '/')
if idx == -1 {
errMsg := fmt.Sprintf("Unable to translate APIVersion for Extension Filter: kind: %s, %s/%s", res.GetKind(), filterNs, extFilter.Name)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
return
}
group := apiVers[:idx]
if group == string(extFilter.Group) {
resource := res // Capture loop variable
filterContext.ExtensionRefs = append(filterContext.ExtensionRefs, &ir.UnstructuredRef{
Object: &resource,
})
return
}
}
}
// Matching filter not found, so set negative status condition.
errMsg := fmt.Sprintf("Reference %s/%s not found for filter type: %v", filterNs,
extFilter.Name, extFilter.Kind)
t.processUnresolvedHTTPFilter(errMsg, filterContext)
}
func (t *Translator) processRequestMirrorFilter(
mirrorFilter *v1beta1.HTTPRequestMirrorFilter,
filterContext *HTTPFiltersContext,
resources *Resources) {
// Make sure the config actually exists
if mirrorFilter == nil {
return
}
mirrorBackend := mirrorFilter.BackendRef
// Wrap the filter's BackendObjectReference into a BackendRef so we can use existing tooling to check it
weight := int32(1)
mirrorBackendRef := v1beta1.BackendRef{
BackendObjectReference: mirrorBackend,
Weight: &weight,
}
// This sets the status on the HTTPRoute, should the usage be changed so that the status message reflects that the backendRef is from the filter?
filterNs := filterContext.Route.GetNamespace()
serviceNamespace := NamespaceDerefOr(mirrorBackend.Namespace, filterNs)
if !t.validateBackendRef(&mirrorBackendRef, filterContext.ParentRef, filterContext.Route,
resources, serviceNamespace, KindHTTPRoute) {
return
}
mirrorDests, _ := t.processRouteDestinations(mirrorBackendRef, filterContext.ParentRef, filterContext.Route, resources)
// Only add missing mirror destinations
for _, mirrorDest := range mirrorDests {
var found bool
for _, mirror := range filterContext.Mirrors {
if mirror != nil {
if mirror.Host == mirrorDest.Host && mirror.Port == mirrorDest.Port {
found = true
}
}
}
if !found {
filterContext.Mirrors = append(filterContext.Mirrors, mirrorDest)
}
}
}
func (t *Translator) processUnresolvedHTTPFilter(errMsg string, filterContext *HTTPFiltersContext) {
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionResolvedRefs,
metav1.ConditionFalse,
v1beta1.RouteReasonBackendNotFound,
errMsg,
)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
filterContext.DirectResponse = &ir.DirectResponse{
Body: &errMsg,
StatusCode: 500,
}
}
func (t *Translator) processUnsupportedHTTPFilter(filterType string, filterContext *HTTPFiltersContext) {
errMsg := fmt.Sprintf("Unsupported filter type: %s", filterType)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
filterContext.DirectResponse = &ir.DirectResponse{
Body: &errMsg,
StatusCode: 500,
}
}
func (t *Translator) processInvalidHTTPFilter(filterType string, filterContext *HTTPFiltersContext, err error) {
errMsg := fmt.Sprintf("Invalid filter %s: %v", filterType, err)
filterContext.ParentRef.SetCondition(filterContext.Route,
v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
v1beta1.RouteReasonUnsupportedValue,
errMsg,
)
filterContext.DirectResponse = &ir.DirectResponse{
Body: &errMsg,
StatusCode: 500,
}
}