-
Notifications
You must be signed in to change notification settings - Fork 365
/
xds.go
1755 lines (1562 loc) · 66.3 KB
/
xds.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 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 ir
import (
"cmp"
"errors"
"net/http"
"net/netip"
"reflect"
"golang.org/x/exp/slices"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
gwv1a2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
"sigs.k8s.io/yaml"
egv1a1 "github.com/envoyproxy/gateway/api/v1alpha1"
egv1a1validation "github.com/envoyproxy/gateway/api/v1alpha1/validation"
)
var (
ErrListenerNameEmpty = errors.New("field Name must be specified")
ErrListenerAddressInvalid = errors.New("field Address must be a valid IP address")
ErrListenerPortInvalid = errors.New("field Port specified is invalid")
ErrHTTPListenerHostnamesEmpty = errors.New("field Hostnames must be specified with at least a single hostname entry")
ErrTCPListenerSNIsEmpty = errors.New("field SNIs must be specified with at least a single server name entry")
ErrTLSServerCertEmpty = errors.New("field ServerCertificate must be specified")
ErrTLSPrivateKey = errors.New("field PrivateKey must be specified")
ErrHTTPRouteNameEmpty = errors.New("field Name must be specified")
ErrHTTPRouteHostnameEmpty = errors.New("field Hostname must be specified")
ErrDestinationNameEmpty = errors.New("field Name must be specified")
ErrDestEndpointHostInvalid = errors.New("field Address must be a valid IP or FQDN address")
ErrDestEndpointPortInvalid = errors.New("field Port specified is invalid")
ErrStringMatchConditionInvalid = errors.New("only one of the Exact, Prefix, SafeRegex or Distinct fields must be set")
ErrStringMatchNameIsEmpty = errors.New("field Name must be specified")
ErrDirectResponseStatusInvalid = errors.New("only HTTP status codes 100 - 599 are supported for DirectResponse")
ErrRedirectUnsupportedStatus = errors.New("only HTTP status codes 301 and 302 are supported for redirect filters")
ErrRedirectUnsupportedScheme = errors.New("only http and https are supported for the scheme in redirect filters")
ErrHTTPPathModifierDoubleReplace = errors.New("redirect filter cannot have a path modifier that supplies both fullPathReplace and prefixMatchReplace")
ErrHTTPPathModifierNoReplace = errors.New("redirect filter cannot have a path modifier that does not supply either fullPathReplace or prefixMatchReplace")
ErrAddHeaderEmptyName = errors.New("header modifier filter cannot configure a header without a name to be added")
ErrAddHeaderDuplicate = errors.New("header modifier filter attempts to add the same header more than once (case insensitive)")
ErrRemoveHeaderDuplicate = errors.New("header modifier filter attempts to remove the same header more than once (case insensitive)")
ErrLoadBalancerInvalid = errors.New("loadBalancer setting is invalid, only one setting can be set")
ErrHealthCheckTimeoutInvalid = errors.New("field HealthCheck.Timeout must be specified")
ErrHealthCheckIntervalInvalid = errors.New("field HealthCheck.Interval must be specified")
ErrHealthCheckUnhealthyThresholdInvalid = errors.New("field HealthCheck.UnhealthyThreshold should be greater than 0")
ErrHealthCheckHealthyThresholdInvalid = errors.New("field HealthCheck.HealthyThreshold should be greater than 0")
ErrHealthCheckerInvalid = errors.New("health checker setting is invalid, only one health checker can be set")
ErrHCHTTPPathInvalid = errors.New("field HTTPHealthChecker.Path should be specified")
ErrHCHTTPMethodInvalid = errors.New("only one of the GET, HEAD, POST, DELETE, OPTIONS, TRACE, PATCH of HTTPHealthChecker.Method could be set")
ErrHCHTTPExpectedStatusesInvalid = errors.New("field HTTPHealthChecker.ExpectedStatuses should be specified")
ErrHealthCheckPayloadInvalid = errors.New("one of Text, Binary fields must be set in payload")
ErrHTTPStatusInvalid = errors.New("HTTPStatus should be in [200,600)")
ErrOutlierDetectionBaseEjectionTimeInvalid = errors.New("field OutlierDetection.BaseEjectionTime must be specified")
ErrOutlierDetectionIntervalInvalid = errors.New("field OutlierDetection.Interval must be specified")
redacted = []byte("[redacted]")
)
// Xds holds the intermediate representation of a Gateway and is
// used by the xDS Translator to convert it into xDS resources.
// +k8s:deepcopy-gen=true
type Xds struct {
// AccessLog configuration for the gateway.
AccessLog *AccessLog `json:"accessLog,omitempty" yaml:"accessLog,omitempty"`
// Tracing configuration for the gateway.
Tracing *Tracing `json:"tracing,omitempty" yaml:"tracing,omitempty"`
// Metrics configuration for the gateway.
Metrics *Metrics `json:"metrics,omitempty" yaml:"metrics,omitempty"`
// HTTP listeners exposed by the gateway.
HTTP []*HTTPListener `json:"http,omitempty" yaml:"http,omitempty"`
// TCP Listeners exposed by the gateway.
TCP []*TCPListener `json:"tcp,omitempty" yaml:"tcp,omitempty"`
// UDP Listeners exposed by the gateway.
UDP []*UDPListener `json:"udp,omitempty" yaml:"udp,omitempty"`
// EnvoyPatchPolicies is the intermediate representation of the EnvoyPatchPolicy resource
EnvoyPatchPolicies []*EnvoyPatchPolicy `json:"envoyPatchPolicies,omitempty" yaml:"envoyPatchPolicies,omitempty"`
}
// Equal implements the Comparable interface used by watchable.DeepEqual to skip unnecessary updates.
func (x *Xds) Equal(y *Xds) bool {
// Deep copy to avoid modifying the original ordering.
x = x.DeepCopy()
x.sort()
y = y.DeepCopy()
y.sort()
return reflect.DeepEqual(x, y)
}
// sort ensures the listeners are in a consistent order.
func (x *Xds) sort() {
slices.SortFunc(x.HTTP, func(l1, l2 *HTTPListener) int {
return cmp.Compare(l1.Name, l2.Name)
})
for _, l := range x.HTTP {
slices.SortFunc(l.Routes, func(r1, r2 *HTTPRoute) int {
return cmp.Compare(r1.Name, r2.Name)
})
}
slices.SortFunc(x.TCP, func(l1, l2 *TCPListener) int {
return cmp.Compare(l1.Name, l2.Name)
})
slices.SortFunc(x.UDP, func(l1, l2 *UDPListener) int {
return cmp.Compare(l1.Name, l2.Name)
})
}
// Validate the fields within the Xds structure.
func (x Xds) Validate() error {
var errs error
for _, http := range x.HTTP {
if err := http.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
for _, tcp := range x.TCP {
if err := tcp.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
for _, udp := range x.UDP {
if err := udp.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
func (x Xds) GetHTTPListener(name string) *HTTPListener {
for _, listener := range x.HTTP {
if listener.Name == name {
return listener
}
}
return nil
}
func (x Xds) GetTCPListener(name string) *TCPListener {
for _, listener := range x.TCP {
if listener.Name == name {
return listener
}
}
return nil
}
func (x Xds) GetUDPListener(name string) *UDPListener {
for _, listener := range x.UDP {
if listener.Name == name {
return listener
}
}
return nil
}
func (x Xds) YAMLString() string {
y, _ := yaml.Marshal(x.Printable())
return string(y)
}
// Printable returns a deep copy of the resource that can be safely logged.
func (x Xds) Printable() *Xds {
out := x.DeepCopy()
for _, listener := range out.HTTP {
// Omit field
if listener.TLS != nil {
for i := range listener.TLS.Certificates {
listener.TLS.Certificates[i].PrivateKey = redacted
}
}
for _, route := range listener.Routes {
// Omit field
if route.OIDC != nil {
route.OIDC.ClientSecret = redacted
route.OIDC.HMACSecret = redacted
}
if route.BasicAuth != nil {
route.BasicAuth.Users = redacted
}
}
}
return out
}
// HTTPListener holds the listener configuration.
// +k8s:deepcopy-gen=true
type HTTPListener struct {
// Name of the HttpListener
Name string `json:"name" yaml:"name"`
// Address that the listener should listen on.
Address string `json:"address" yaml:"address"`
// Port on which the service can be expected to be accessed by clients.
Port uint32 `json:"port" yaml:"port"`
// Hostnames (Host/Authority header value) with which the service can be expected to be accessed by clients.
// This field is required. Wildcard hosts are supported in the suffix or prefix form.
// Refer to https://www.envoyproxy.io/docs/envoy/latest/api-v3/config/route/v3/route_components.proto#config-route-v3-virtualhost
// for more info.
Hostnames []string `json:"hostnames" yaml:"hostnames"`
// Tls configuration. If omitted, the gateway will expose a plain text HTTP server.
TLS *TLSConfig `json:"tls,omitempty" yaml:"tls,omitempty"`
// Routes associated with HTTP traffic to the service.
Routes []*HTTPRoute `json:"routes,omitempty" yaml:"routes,omitempty"`
// IsHTTP2 is set if the listener is configured to serve HTTP2 traffic,
// grpc-web and grpc-stats are also enabled if this is set.
IsHTTP2 bool `json:"isHTTP2" yaml:"isHTTP2"`
// TCPKeepalive configuration for the listener
TCPKeepalive *TCPKeepalive `json:"tcpKeepalive,omitempty" yaml:"tcpKeepalive,omitempty"`
// Headers configures special header management for the listener
Headers *HeaderSettings `json:"headers,omitempty" yaml:"headers,omitempty"`
// EnableProxyProtocol enables the listener to interpret proxy protocol header
EnableProxyProtocol bool `json:"enableProxyProtocol,omitempty" yaml:"enableProxyProtocol,omitempty"`
// ClientIPDetection controls how the original client IP address is determined for requests.
ClientIPDetection *ClientIPDetectionSettings `json:"clientIPDetection,omitempty" yaml:"clientIPDetection,omitempty"`
// HTTP3 provides HTTP/3 configuration on the listener.
// +optional
HTTP3 *HTTP3Settings `json:"http3,omitempty"`
// Path contains settings for path URI manipulations
Path PathSettings `json:"path,omitempty"`
// HTTP1 provides HTTP/1 configuration on the listener
// +optional
HTTP1 *HTTP1Settings `json:"http1,omitempty" yaml:"http1,omitempty"`
// ClientTimeout sets the timeout configuration for downstream connections
Timeout *ClientTimeout `json:"timeout,omitempty" yaml:"clientTimeout,omitempty"`
}
// Validate the fields within the HTTPListener structure
func (h HTTPListener) Validate() error {
var errs error
if h.Name == "" {
errs = errors.Join(errs, ErrListenerNameEmpty)
}
if _, err := netip.ParseAddr(h.Address); err != nil {
errs = errors.Join(errs, ErrListenerAddressInvalid)
}
if h.Port == 0 {
errs = errors.Join(errs, ErrListenerPortInvalid)
}
if len(h.Hostnames) == 0 {
errs = errors.Join(errs, ErrHTTPListenerHostnamesEmpty)
}
if h.TLS != nil {
if err := h.TLS.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
for _, route := range h.Routes {
if err := route.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
type TLSVersion egv1a1.TLSVersion
const (
// TLSAuto allows Envoy to choose the optimal TLS Version
TLSAuto = TLSVersion(egv1a1.TLSAuto)
// TLSv10 specifies TLS version 1.0
TLSv10 = TLSVersion(egv1a1.TLSv10)
// TLSv11 specifies TLS version 1.1
TLSv11 = TLSVersion(egv1a1.TLSv11)
// TLSv12 specifies TLS version 1.2
TLSv12 = TLSVersion(egv1a1.TLSv12)
// TLSv13 specifies TLS version 1.3
TLSv13 = TLSVersion(egv1a1.TLSv13)
)
// TLSConfig holds the configuration for downstream TLS context.
// +k8s:deepcopy-gen=true
type TLSConfig struct {
// Certificates contains the set of certificates associated with this listener
Certificates []TLSCertificate `json:"certificates,omitempty" yaml:"certificates,omitempty"`
// CACertificate to verify the client
CACertificate *TLSCACertificate `json:"caCertificate,omitempty" yaml:"caCertificate,omitempty"`
// MinVersion defines the minimal version of the TLS protocol supported by this listener.
MinVersion *TLSVersion `json:"minVersion,omitempty" yaml:"version,omitempty"`
// MaxVersion defines the maximal version of the TLS protocol supported by this listener.
MaxVersion *TLSVersion `json:"maxVersion,omitempty" yaml:"version,omitempty"`
// CipherSuites supported by this listener
Ciphers []string `json:"ciphers,omitempty" yaml:"ciphers,omitempty"`
// EDCHCurves supported by this listener
ECDHCurves []string `json:"ecdhCurves,omitempty" yaml:"ecdhCurves,omitempty"`
// SignatureAlgorithms supported by this listener
SignatureAlgorithms []string `json:"signatureAlgorithms,omitempty" yaml:"signatureAlgorithms,omitempty"`
// ALPNProtocols exposed by this listener
ALPNProtocols []string `json:"alpnProtocols,omitempty" yaml:"alpnProtocols,omitempty"`
// TLS information required for TLS termination, If provided, incoming
// connections' server names are inspected and routed to backends accordingly.
Inspector TLSInspectorConfig `json:"inspector,omitempty" yaml:"inspector,omitempty"`
}
// TLSCertificate holds a single certificate's details
// +k8s:deepcopy-gen=true
type TLSCertificate struct {
// Name of the Secret object.
Name string `json:"name" yaml:"name"`
// ServerCertificate of the server.
ServerCertificate []byte `json:"serverCertificate,omitempty" yaml:"serverCertificate,omitempty"`
// PrivateKey for the server.
PrivateKey []byte `json:"privateKey,omitempty" yaml:"privateKey,omitempty"`
}
// TLSCACertificate holds CA Certificate to validate clients
// +k8s:deepcopy-gen=true
type TLSCACertificate struct {
// Name of the Secret object.
Name string `json:"name,omitempty" yaml:"name,omitempty"`
// Certificate content.
Certificate []byte `json:"certificate,omitempty" yaml:"certificate,omitempty"`
}
func (t TLSCertificate) Validate() error {
var errs error
if len(t.ServerCertificate) == 0 {
errs = errors.Join(errs, ErrTLSServerCertEmpty)
}
if len(t.PrivateKey) == 0 {
errs = errors.Join(errs, ErrTLSPrivateKey)
}
return errs
}
// Validate the fields within the TLSListenerConfig structure
func (t TLSConfig) Validate() error {
var errs error
for _, cert := range t.Certificates {
if err := cert.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
// Correct values for cipher suites, ECDH curves, and signature algorithms are
// dependent on the version of EnvoyProxy being used - different values are valid
// depending if Envoy was compiled against BoringSSL or OpenSSL, or even the exact version
// of each of these libraries.
// Validation for TLS versions was done with CEL
return errs
}
type PathEscapedSlashAction egv1a1.PathEscapedSlashAction
const (
KeepUnchangedAction = PathEscapedSlashAction(egv1a1.KeepUnchangedAction)
RejectRequestAction = PathEscapedSlashAction(egv1a1.RejectRequestAction)
UnescapeAndRedirect = PathEscapedSlashAction(egv1a1.UnescapeAndRedirect)
UnescapeAndForward = PathEscapedSlashAction(egv1a1.UnescapeAndForward)
)
// PathSettings holds configuration for path URI manipulations
// +k8s:deepcopy-gen=true
type PathSettings struct {
MergeSlashes bool `json:"mergeSlashes" yaml:"mergeSlashes"`
EscapedSlashesAction PathEscapedSlashAction `json:"escapedSlashesAction" yaml:"escapedSlashesAction"`
}
// ClientIPDetectionSettings provides configuration for determining the original client IP address for requests.
// +k8s:deepcopy-gen=true
type ClientIPDetectionSettings egv1a1.ClientIPDetectionSettings
// BackendWeights stores the weights of valid and invalid backends for the route so that 500 error responses can be returned in the same proportions
type BackendWeights struct {
Valid uint32 `json:"valid" yaml:"valid"`
Invalid uint32 `json:"invalid" yaml:"invalid"`
}
// HTTP1Settings provides HTTP/1 configuration on the listener.
// +k8s:deepcopy-gen=true
type HTTP1Settings struct {
EnableTrailers bool `json:"enableTrailers,omitempty" yaml:"enableTrailers,omitempty"`
PreserveHeaderCase bool `json:"preserveHeaderCase,omitempty" yaml:"preserveHeaderCase,omitempty"`
HTTP10 *HTTP10Settings `json:"http10,omitempty" yaml:"http10,omitempty"`
}
// HTTP10Settings provides HTTP/1.0 configuration on the listener.
// +k8s:deepcopy-gen=true
type HTTP10Settings struct {
// defaultHost is set to the default host that should be injected for HTTP10. If the hostname shouldn't
// be set, then defaultHost will be nil
DefaultHost *string `json:"defaultHost,omitempty" yaml:"defaultHost,omitempty"`
}
// HeaderSettings provides configuration related to header processing on the listener.
// +k8s:deepcopy-gen=true
type HeaderSettings struct {
// EnableEnvoyHeaders controls if "x-envoy-" headers are added by the HTTP Router filter.
// The default is to suppress these headers.
// Refer to https://www.envoyproxy.io/docs/envoy/latest/api-v3/extensions/filters/http/router/v3/router.proto#extensions-filters-http-router-v3-router
EnableEnvoyHeaders bool `json:"enableEnvoyHeaders,omitempty" yaml:"enableEnvoyHeaders,omitempty"`
}
// ClientTimeout sets the timeout configuration for downstream connections
// +k8s:deepcopy-gen=true
type ClientTimeout struct {
// Timeout settings for HTTP.
HTTP *HTTPClientTimeout `json:"http,omitempty" yaml:"http,omitempty"`
}
// HTTPClientTimeout set the configuration for client HTTP.
// +k8s:deepcopy-gen=true
type HTTPClientTimeout struct {
// The duration envoy waits for the complete request reception. This timer starts upon request
// initiation and stops when either the last byte of the request is sent upstream or when the response begins.
RequestReceivedTimeout *metav1.Duration `json:"requestReceivedTimeout,omitempty" yaml:"requestReceivedTimeout,omitempty"`
}
// HTTPRoute holds the route information associated with the HTTP Route
// +k8s:deepcopy-gen=true
type HTTPRoute struct {
// Name of the HTTPRoute
Name string `json:"name" yaml:"name"`
// Hostname that the route matches against
Hostname string `json:"hostname" yaml:"hostname,omitempty"`
// IsHTTP2 is set if the route is configured to serve HTTP2 traffic
IsHTTP2 bool `json:"isHTTP2" yaml:"isHTTP2"`
// PathMatch defines the match conditions on the path.
PathMatch *StringMatch `json:"pathMatch,omitempty" yaml:"pathMatch,omitempty"`
// HeaderMatches define the match conditions on the request headers for this route.
HeaderMatches []*StringMatch `json:"headerMatches,omitempty" yaml:"headerMatches,omitempty"`
// QueryParamMatches define the match conditions on the query parameters.
QueryParamMatches []*StringMatch `json:"queryParamMatches,omitempty" yaml:"queryParamMatches,omitempty"`
// DestinationWeights stores the weights of valid and invalid backends for the route so that 500 error responses can be returned in the same proportions
BackendWeights BackendWeights `json:"backendWeights" yaml:"backendWeights"`
// AddRequestHeaders defines header/value sets to be added to the headers of requests.
AddRequestHeaders []AddHeader `json:"addRequestHeaders,omitempty" yaml:"addRequestHeaders,omitempty"`
// RemoveRequestHeaders defines a list of headers to be removed from requests.
RemoveRequestHeaders []string `json:"removeRequestHeaders,omitempty" yaml:"removeRequestHeaders,omitempty"`
// AddResponseHeaders defines header/value sets to be added to the headers of response.
AddResponseHeaders []AddHeader `json:"addResponseHeaders,omitempty" yaml:"addResponseHeaders,omitempty"`
// RemoveResponseHeaders defines a list of headers to be removed from response.
RemoveResponseHeaders []string `json:"removeResponseHeaders,omitempty" yaml:"removeResponseHeaders,omitempty"`
// Direct responses to be returned for this route. Takes precedence over Destinations and Redirect.
DirectResponse *DirectResponse `json:"directResponse,omitempty" yaml:"directResponse,omitempty"`
// Redirections to be returned for this route. Takes precedence over Destinations.
Redirect *Redirect `json:"redirect,omitempty" yaml:"redirect,omitempty"`
// Destination that requests to this HTTPRoute will be mirrored to
Mirrors []*RouteDestination `json:"mirrors,omitempty" yaml:"mirrors,omitempty"`
// Destination associated with this matched route.
Destination *RouteDestination `json:"destination,omitempty" yaml:"destination,omitempty"`
// Rewrite to be changed for this route.
URLRewrite *URLRewrite `json:"urlRewrite,omitempty" yaml:"urlRewrite,omitempty"`
// RateLimit defines the more specific match conditions as well as limits for ratelimiting
// the requests on this route.
RateLimit *RateLimit `json:"rateLimit,omitempty" yaml:"rateLimit,omitempty"`
// load balancer policy to use when routing to the backend endpoints.
LoadBalancer *LoadBalancer `json:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty"`
// CORS policy for the route.
CORS *CORS `json:"cors,omitempty" yaml:"cors,omitempty"`
// JWT defines the schema for authenticating HTTP requests using JSON Web Tokens (JWT).
JWT *JWT `json:"jwt,omitempty" yaml:"jwt,omitempty"`
// OIDC defines the schema for authenticating HTTP requests using OpenID Connect (OIDC).
OIDC *OIDC `json:"oidc,omitempty" yaml:"oidc,omitempty"`
// Proxy Protocol Settings
ProxyProtocol *ProxyProtocol `json:"proxyProtocol,omitempty" yaml:"proxyProtocol,omitempty"`
// BasicAuth defines the schema for the HTTP Basic Authentication.
BasicAuth *BasicAuth `json:"basicAuth,omitempty" yaml:"basicAuth,omitempty"`
// ExtAuth defines the schema for the external authorization.
ExtAuth *ExtAuth `json:"extAuth,omitempty" yaml:"extAuth,omitempty"`
// HealthCheck defines the configuration for health checking on the upstream.
HealthCheck *HealthCheck `json:"healthCheck,omitempty" yaml:"healthCheck,omitempty"`
// FaultInjection defines the schema for injecting faults into HTTP requests.
FaultInjection *FaultInjection `json:"faultInjection,omitempty" yaml:"faultInjection,omitempty"`
// ExtensionRefs holds unstructured resources that were introduced by an extension and used on the HTTPRoute as extensionRef filters
ExtensionRefs []*UnstructuredRef `json:"extensionRefs,omitempty" yaml:"extensionRefs,omitempty"`
// Circuit Breaker Settings
CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"`
// Request and connection timeout settings
Timeout *Timeout `json:"timeout,omitempty" yaml:"timeout,omitempty"`
// TcpKeepalive settings associated with the upstream client connection.
TCPKeepalive *TCPKeepalive `json:"tcpKeepalive,omitempty" yaml:"tcpKeepalive,omitempty"`
// Retry settings
Retry *Retry `json:"retry,omitempty" yaml:"retry,omitempty"`
}
// UnstructuredRef holds unstructured data for an arbitrary k8s resource introduced by an extension
// Envoy Gateway does not need to know about the resource types in order to store and pass the data for these objects
// to an extension.
//
// +k8s:deepcopy-gen=true
type UnstructuredRef struct {
Object *unstructured.Unstructured `json:"object,omitempty" yaml:"object,omitempty"`
}
// CORS holds the Cross-Origin Resource Sharing (CORS) policy for the route.
//
// +k8s:deepcopy-gen=true
type CORS struct {
// AllowOrigins defines the origins that are allowed to make requests.
AllowOrigins []*StringMatch `json:"allowOrigins,omitempty" yaml:"allowOrigins,omitempty"`
// AllowMethods defines the methods that are allowed to make requests.
AllowMethods []string `json:"allowMethods,omitempty" yaml:"allowMethods,omitempty"`
// AllowHeaders defines the headers that are allowed to be sent with requests.
AllowHeaders []string `json:"allowHeaders,omitempty" yaml:"allowHeaders,omitempty"`
// ExposeHeaders defines the headers that can be exposed in the responses.
ExposeHeaders []string `json:"exposeHeaders,omitempty" yaml:"exposeHeaders,omitempty"`
// MaxAge defines how long the results of a preflight request can be cached.
MaxAge *metav1.Duration `json:"maxAge,omitempty" yaml:"maxAge,omitempty"`
// AllowCredentials indicates whether a request can include user credentials.
AllowCredentials bool `json:"allowCredentials,omitempty" yaml:"allowCredentials,omitempty"`
}
// JWT defines the schema for authenticating HTTP requests using
// JSON Web Tokens (JWT).
//
// +k8s:deepcopy-gen=true
type JWT struct {
// Providers defines a list of JSON Web Token (JWT) authentication providers.
Providers []egv1a1.JWTProvider `json:"providers,omitempty" yaml:"providers,omitempty"`
}
// OIDC defines the schema for authenticating HTTP requests using
// OpenID Connect (OIDC).
//
// +k8s:deepcopy-gen=true
type OIDC struct {
// The OIDC Provider configuration.
Provider OIDCProvider `json:"provider" yaml:"provider"`
// The OIDC client ID to be used in the
// [Authentication Request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
ClientID string `json:"clientID" yaml:"clientID"`
// The OIDC client secret to be used in the
// [Authentication Request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
//
// This is an Opaque secret. The client secret should be stored in the key "client-secret".
ClientSecret []byte `json:"clientSecret,omitempty" yaml:"clientSecret,omitempty"`
// HMACSecret is the secret used to sign the HMAC of the OAuth2 filter cookies.
HMACSecret []byte `json:"hmacSecret,omitempty" yaml:"hmacSecret,omitempty"`
// The OIDC scopes to be used in the
// [Authentication Request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
Scopes []string `json:"scopes,omitempty" yaml:"scopes,omitempty"`
// The redirect URL to be used in the OIDC
// [Authentication Request](https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest).
RedirectURL string `json:"redirectURL,omitempty"`
// The path part of the redirect URL
RedirectPath string `json:"redirectPath,omitempty"`
// The path to log a user out, clearing their credential cookies.
LogoutPath string `json:"logoutPath,omitempty"`
// CookieSuffix will be added to the name of the cookies set by the oauth filter.
// Adding a suffix avoids multiple oauth filters from overwriting each other's cookies.
// These cookies are set by the oauth filter, including: BearerToken,
// OauthHMAC, OauthExpires, IdToken, and RefreshToken.
CookieSuffix string `json:"cookieSuffix,omitempty"`
}
type OIDCProvider struct {
// The OIDC Provider's [authorization endpoint](https://openid.net/specs/openid-connect-core-1_0.html#AuthorizationEndpoint).
AuthorizationEndpoint string `json:"authorizationEndpoint,omitempty"`
// The OIDC Provider's [token endpoint](https://openid.net/specs/openid-connect-core-1_0.html#TokenEndpoint).
TokenEndpoint string `json:"tokenEndpoint,omitempty"`
}
// BasicAuth defines the schema for the HTTP Basic Authentication.
//
// +k8s:deepcopy-gen=true
type BasicAuth struct {
// The username-password pairs in htpasswd format.
Users []byte `json:"users,omitempty" yaml:"users,omitempty"`
}
// ExtAuth defines the schema for the external authorization.
//
// +k8s:deepcopy-gen=true
type ExtAuth struct {
// Name is a unique name for an ExtAuth configuration.
// The xds translator only generates one external authorization filter for each unique name.
Name string `json:"name" yaml:"name"`
// GRPC defines the gRPC External Authorization service.
// Only one of GRPCService or HTTPService may be specified.
GRPC *GRPCExtAuthService `json:"grpc,omitempty"`
// HTTP defines the HTTP External Authorization service.
// Only one of GRPCService or HTTPService may be specified.
HTTP *HTTPExtAuthService `json:"http,omitempty"`
// HeadersToExtAuth defines the client request headers that will be included
// in the request to the external authorization service.
// Note: If not specified, the default behavior for gRPC and HTTP external
// authorization services is different due to backward compatibility reasons.
// All headers will be included in the check request to a gRPC authorization server.
// Only the following headers will be included in the check request to an HTTP
// authorization server: Host, Method, Path, Content-Length, and Authorization.
// And these headers will always be included to the check request to an HTTP
// authorization server by default, no matter whether they are specified
// in HeadersToExtAuth or not.
// +optional
HeadersToExtAuth []string `json:"headersToExtAuth,omitempty"`
}
// HTTPExtAuthService defines the HTTP External Authorization service
// +k8s:deepcopy-gen=true
type HTTPExtAuthService struct {
// Destination defines the destination for the HTTP External Authorization service.
Destination RouteDestination `json:"destination"`
// Authority is the hostname:port of the HTTP External Authorization service.
Authority string `json:"authority"`
// Path is the path of the HTTP External Authorization service.
// If path is not empty, the authorization request will be sent to that path,
// or else the authorization request will be sent to the root path.
Path string `json:"path"`
// HeadersToBackend are the authorization response headers that will be added
// to the original client request before sending it to the backend server.
// Note that coexisting headers will be overridden.
// If not specified, no authorization response headers will be added to the
// original client request.
// +optional
HeadersToBackend []string `json:"headersToBackend,omitempty"`
}
// GRPCExtAuthService defines the gRPC External Authorization service
// The authorization request message is defined in
// https://www.envoyproxy.io/docs/envoy/latest/api-v3/service/auth/v3/external_auth.proto
// +k8s:deepcopy-gen=true
type GRPCExtAuthService struct {
// Destination defines the destination for the gRPC External Authorization service.
Destination RouteDestination `json:"destination"`
// Authority is the hostname:port of the gRPC External Authorization service.
Authority string `json:"authority"`
}
// FaultInjection defines the schema for injecting faults into requests.
//
// +k8s:deepcopy-gen=true
type FaultInjection struct {
// Delay defines the fault injection delay.
Delay *FaultInjectionDelay `json:"delay,omitempty" yaml:"delay,omitempty"`
// Abort defines the fault injection abort.
Abort *FaultInjectionAbort `json:"abort,omitempty" yaml:"abort,omitempty"`
}
// FaultInjectionDelay defines the schema for injecting delay into requests.
//
// +k8s:deepcopy-gen=true
type FaultInjectionDelay struct {
// FixedDelay defines the fixed delay duration.
FixedDelay *metav1.Duration `json:"fixedDelay,omitempty" yaml:"fixedDelay,omitempty"`
// Percentage defines the percentage of requests to be delayed.
Percentage *float32 `json:"percentage,omitempty" yaml:"percentage,omitempty"`
}
// FaultInjectionAbort defines the schema for injecting abort into requests.
//
// +k8s:deepcopy-gen=true
type FaultInjectionAbort struct {
// HTTPStatus defines the HTTP status code to be returned.
HTTPStatus *int32 `json:"httpStatus,omitempty" yaml:"httpStatus,omitempty"`
// GrpcStatus defines the gRPC status code to be returned.
GrpcStatus *int32 `json:"grpcStatus,omitempty" yaml:"grpcStatus,omitempty"`
// Percentage defines the percentage of requests to be aborted.
Percentage *float32 `json:"percentage,omitempty" yaml:"percentage,omitempty"`
}
// Validate the fields within the HTTPRoute structure
func (h HTTPRoute) Validate() error {
var errs error
if h.Name == "" {
errs = errors.Join(errs, ErrHTTPRouteNameEmpty)
}
if h.Hostname == "" {
errs = errors.Join(errs, ErrHTTPRouteHostnameEmpty)
}
if h.PathMatch != nil {
if err := h.PathMatch.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
for _, hMatch := range h.HeaderMatches {
if err := hMatch.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
for _, qMatch := range h.QueryParamMatches {
if err := qMatch.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.Destination != nil {
if err := h.Destination.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.Redirect != nil {
if err := h.Redirect.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.DirectResponse != nil {
if err := h.DirectResponse.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.URLRewrite != nil {
if err := h.URLRewrite.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.Mirrors != nil {
for _, mirror := range h.Mirrors {
if err := mirror.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
}
if len(h.AddRequestHeaders) > 0 {
occurred := sets.NewString()
for _, header := range h.AddRequestHeaders {
if err := header.Validate(); err != nil {
errs = errors.Join(errs, err)
}
if occurred.Has(header.Name) {
errs = errors.Join(errs, ErrAddHeaderDuplicate)
break
}
occurred.Insert(header.Name)
}
}
if len(h.RemoveRequestHeaders) > 0 {
occurred := sets.NewString()
for _, header := range h.RemoveRequestHeaders {
if occurred.Has(header) {
errs = errors.Join(errs, ErrRemoveHeaderDuplicate)
break
}
occurred.Insert(header)
}
}
if len(h.AddResponseHeaders) > 0 {
occurred := sets.NewString()
for _, header := range h.AddResponseHeaders {
if err := header.Validate(); err != nil {
errs = errors.Join(errs, err)
}
if occurred.Has(header.Name) {
errs = errors.Join(errs, ErrAddHeaderDuplicate)
break
}
occurred.Insert(header.Name)
}
}
if len(h.RemoveResponseHeaders) > 0 {
occurred := sets.NewString()
for _, header := range h.RemoveResponseHeaders {
if occurred.Has(header) {
errs = errors.Join(errs, ErrRemoveHeaderDuplicate)
break
}
occurred.Insert(header)
}
}
if h.LoadBalancer != nil {
if err := h.LoadBalancer.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.JWT != nil {
if err := h.JWT.validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if h.HealthCheck != nil {
if err := h.HealthCheck.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
func (j *JWT) validate() error {
var errs error
if err := egv1a1validation.ValidateJWTProvider(j.Providers); err != nil {
errs = errors.Join(errs, err)
}
return errs
}
// RouteDestination holds the destination details associated with the route
// +kubebuilder:object:generate=true
type RouteDestination struct {
// Name of the destination. This field allows the xds layer
// to check if this route destination already exists and can be
// reused
Name string `json:"name" yaml:"name"`
Settings []*DestinationSetting `json:"settings,omitempty" yaml:"settings,omitempty"`
}
// Validate the fields within the RouteDestination structure
func (r RouteDestination) Validate() error {
var errs error
if len(r.Name) == 0 {
errs = errors.Join(errs, ErrDestinationNameEmpty)
}
for _, s := range r.Settings {
if err := s.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
// DestinationSetting holds the settings associated with the destination
// +kubebuilder:object:generate=true
type DestinationSetting struct {
// Weight associated with this destination.
// Note: Weight is not used in TCP/UDP route.
Weight *uint32 `json:"weight,omitempty" yaml:"weight,omitempty"`
// Protocol associated with this destination/port.
Protocol AppProtocol `json:"protocol" yaml:"protocol"`
Endpoints []*DestinationEndpoint `json:"endpoints,omitempty" yaml:"endpoints,omitempty"`
// AddressTypeState specifies the state of DestinationEndpoint address type.
AddressType *DestinationAddressType `json:"addressType,omitempty" yaml:"addressType,omitempty"`
TLS *TLSUpstreamConfig `json:"tls,omitempty" yaml:"tls,omitempty"`
}
// Validate the fields within the RouteDestination structure
func (d DestinationSetting) Validate() error {
var errs error
for _, ep := range d.Endpoints {
if err := ep.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
// DestinationAddressType describes the address type state for a group of DestinationEndpoint
type DestinationAddressType string
const (
IP DestinationAddressType = "IP"
FQDN DestinationAddressType = "FQDN"
MIXED DestinationAddressType = "Mixed"
)
// DestinationEndpoint holds the endpoint details associated with the destination
// +kubebuilder:object:generate=true
type DestinationEndpoint struct {
// Host refers to the FQDN or IP address of the backend service.
Host string `json:"host" yaml:"host"`
// Port on the service to forward the request to.
Port uint32 `json:"port" yaml:"port"`
}
// Validate the fields within the DestinationEndpoint structure
func (d DestinationEndpoint) Validate() error {
var errs error
err := validation.IsDNS1123Subdomain(d.Host)
_, pErr := netip.ParseAddr(d.Host)
if err != nil && pErr != nil {
errs = errors.Join(errs, ErrDestEndpointHostInvalid)
}
if d.Port == 0 {
errs = errors.Join(errs, ErrDestEndpointPortInvalid)
}
return errs
}
// NewDestEndpoint creates a new DestinationEndpoint.
func NewDestEndpoint(host string, port uint32) *DestinationEndpoint {
return &DestinationEndpoint{
Host: host,
Port: port,
}
}
// AddHeader configures a header to be added to a request or response.
// +k8s:deepcopy-gen=true
type AddHeader struct {
Name string `json:"name" yaml:"name"`
Value string `json:"value" yaml:"value"`
Append bool `json:"append" yaml:"append"`
}
// Validate the fields within the AddHeader structure
func (h AddHeader) Validate() error {
var errs error
if h.Name == "" {
errs = errors.Join(errs, ErrAddHeaderEmptyName)
}
return errs
}
// DirectResponse holds the details for returning a body and status code for a route.
// +k8s:deepcopy-gen=true
type DirectResponse struct {
// Body configures the body of the direct response. Currently only a string response
// is supported, but in the future a config.core.v3.DataSource may replace it.
Body *string `json:"body,omitempty" yaml:"body,omitempty"`
// StatusCode will be used for the direct response's status code.
StatusCode uint32 `json:"statusCode" yaml:"statusCode"`
}
// Validate the fields within the DirectResponse structure
func (r DirectResponse) Validate() error {
var errs error
if status := r.StatusCode; status > 599 || status < 100 {
errs = errors.Join(errs, ErrDirectResponseStatusInvalid)
}
return errs
}
// URLRewrite holds the details for how to rewrite a request
// +k8s:deepcopy-gen=true
type URLRewrite struct {
// Path contains config for rewriting the path of the request.
Path *HTTPPathModifier `json:"path,omitempty" yaml:"path,omitempty"`
// Hostname configures the replacement of the request's hostname.
Hostname *string `json:"hostname,omitempty" yaml:"hostname,omitempty"`
}
// Validate the fields within the URLRewrite structure
func (r URLRewrite) Validate() error {
var errs error
if r.Path != nil {
if err := r.Path.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
return errs
}
// Redirect holds the details for how and where to redirect a request
// +k8s:deepcopy-gen=true
type Redirect struct {
// Scheme configures the replacement of the request's scheme.
Scheme *string `json:"scheme" yaml:"scheme"`
// Hostname configures the replacement of the request's hostname.
Hostname *string `json:"hostname" yaml:"hostname"`
// Path contains config for rewriting the path of the request.
Path *HTTPPathModifier `json:"path" yaml:"path"`
// Port configures the replacement of the request's port.
Port *uint32 `json:"port" yaml:"port"`
// Status code configures the redirection response's status code.
StatusCode *int32 `json:"statusCode" yaml:"statusCode"`
}
// Validate the fields within the Redirect structure
func (r Redirect) Validate() error {
var errs error
if r.Scheme != nil {
if *r.Scheme != "http" && *r.Scheme != "https" {
errs = errors.Join(errs, ErrRedirectUnsupportedScheme)
}
}
if r.Path != nil {
if err := r.Path.Validate(); err != nil {
errs = errors.Join(errs, err)
}
}
if r.StatusCode != nil {
if *r.StatusCode != 301 && *r.StatusCode != 302 {
errs = errors.Join(errs, ErrRedirectUnsupportedStatus)
}
}
return errs
}
// HTTPPathModifier holds instructions for how to modify the path of a request on a redirect response
// +k8s:deepcopy-gen=true
type HTTPPathModifier struct {
// FullReplace provides a string to replace the full path of the request.
FullReplace *string `json:"fullReplace" yaml:"fullReplace"`