-
Notifications
You must be signed in to change notification settings - Fork 668
/
gatewayapi_processor.go
1606 lines (1393 loc) · 58.3 KB
/
gatewayapi_processor.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 Project Contour Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package dag
import (
"fmt"
"net/http"
"regexp"
"strings"
"time"
"github.com/projectcontour/contour/internal/gatewayapi"
"github.com/projectcontour/contour/internal/k8s"
"github.com/projectcontour/contour/internal/ref"
"github.com/projectcontour/contour/internal/status"
"github.com/sirupsen/logrus"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
gatewayapi_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
gatewayapi_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1"
)
const (
KindHTTPRoute = "HTTPRoute"
KindTLSRoute = "TLSRoute"
KindGateway = "Gateway"
)
// GatewayAPIProcessor translates Gateway API types into DAG
// objects and adds them to the DAG.
type GatewayAPIProcessor struct {
logrus.FieldLogger
dag *DAG
source *KubernetesCache
// EnableExternalNameService allows processing of ExternalNameServices
// This is normally disabled for security reasons.
// See https://github.com/projectcontour/contour/security/advisories/GHSA-5ph6-qq5x-7jwc for details.
EnableExternalNameService bool
// ConnectTimeout defines how long the proxy should wait when establishing connection to upstream service.
ConnectTimeout time.Duration
}
// matchConditions holds match rules.
type matchConditions struct {
path MatchCondition
headers []HeaderMatchCondition
queryParams []QueryParamMatchCondition
}
// Run translates Gateway API types into DAG objects and
// adds them to the DAG.
func (p *GatewayAPIProcessor) Run(dag *DAG, source *KubernetesCache) {
p.dag = dag
p.source = source
// reset the processor when we're done
defer func() {
p.dag = nil
p.source = nil
}()
// Gateway and GatewayClass must be defined for resources to be processed.
if p.source.gateway == nil {
p.Info("Gateway not found in cache.")
return
}
if p.source.gatewayclass == nil {
p.Info("GatewayClass not found in cache.")
return
}
gwAccessor, commit := p.dag.StatusCache.GatewayStatusAccessor(
k8s.NamespacedNameOf(p.source.gateway),
p.source.gateway.Generation,
&p.source.gateway.Status,
)
defer commit()
var gatewayNotProgrammedCondition *metav1.Condition
if !isAddressAssigned(p.source.gateway.Spec.Addresses, p.source.gateway.Status.Addresses) {
// TODO(sk) resolve condition type-reason mismatch
gatewayNotProgrammedCondition = &metav1.Condition{
Type: string(gatewayapi_v1beta1.GatewayConditionProgrammed),
Status: metav1.ConditionFalse,
Reason: string(gatewayapi_v1beta1.GatewayReasonAddressNotAssigned),
Message: "None of the addresses in Spec.Addresses have been assigned to the Gateway",
}
}
// Validate listener protocols, ports and hostnames and add conditions
// for all invalid listeners.
validateListenersResult := gatewayapi.ValidateListeners(p.source.gateway.Spec.Listeners)
for name, cond := range validateListenersResult.InvalidListenerConditions {
gwAccessor.AddListenerCondition(
string(name),
gatewayapi_v1beta1.ListenerConditionType(cond.Type),
cond.Status,
gatewayapi_v1beta1.ListenerConditionReason(cond.Reason),
cond.Message,
)
}
// Compute listeners and save a list of the valid/ready ones.
var readyListeners []*listenerInfo
for _, listener := range p.source.gateway.Spec.Listeners {
if ready, listenerInfo := p.computeListener(listener, gwAccessor, validateListenersResult); ready {
readyListeners = append(readyListeners, listenerInfo)
}
}
// Keep track of the number of routes attached
// to each Listener so we can set status properly.
listenerAttachedRoutes := map[string]int{}
for _, httpRoute := range p.source.httproutes {
func() {
routeAccessor, commit := p.dag.StatusCache.RouteConditionsAccessor(
k8s.NamespacedNameOf(httpRoute),
httpRoute.Generation,
&gatewayapi_v1beta1.HTTPRoute{},
)
defer commit()
for _, routeParentRef := range httpRoute.Spec.ParentRefs {
// If this parent ref is to a different Gateway, ignore it.
if !gatewayapi.IsRefToGateway(routeParentRef, k8s.NamespacedNameOf(p.source.gateway)) {
continue
}
routeParentStatusAccessor := routeAccessor.StatusUpdateFor(routeParentRef)
// If the Gateway is invalid, set status on the route and we're done.
if gatewayNotProgrammedCondition != nil {
routeParentStatusAccessor.AddCondition(gatewayapi_v1beta1.RouteConditionAccepted, metav1.ConditionFalse, status.ReasonInvalidGateway, "Invalid Gateway")
continue
}
// Get the list of listeners that are (a) included by this parent ref, and
// (b) allow the route (based on kind, namespace).
allowedListeners := p.getListenersForRouteParentRef(routeParentRef, httpRoute.Namespace, KindHTTPRoute, readyListeners, routeParentStatusAccessor)
if len(allowedListeners) == 0 {
continue
}
// Keep track of the number of intersecting hosts
// between the route and all allowed listeners for
// this parent ref so that we can set the appropriate
// route parent status condition if there were none.
hostCount := 0
for _, listener := range allowedListeners {
attached, hosts := p.computeHTTPRoute(httpRoute, routeParentStatusAccessor, listener)
if attached {
listenerAttachedRoutes[string(listener.listener.Name)]++
}
hostCount += hosts.Len()
}
if hostCount == 0 {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
gatewayapi_v1beta1.RouteReasonNoMatchingListenerHostname,
"No intersecting hostnames were found between the listener and the route.",
)
}
// Check for an existing "Accepted" condition, add one if one does
// not already exist.
hasAccepted := false
for _, cond := range routeParentStatusAccessor.ConditionsForParentRef(routeParentRef) {
if cond.Type == string(gatewayapi_v1beta1.RouteConditionAccepted) {
hasAccepted = true
break
}
}
if !hasAccepted {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionTrue,
gatewayapi_v1beta1.RouteReasonAccepted,
"Accepted HTTPRoute",
)
}
}
}()
}
// Compute each TLSRoute for each Listener that it potentially
// attaches to.
for _, tlsRoute := range p.source.tlsroutes {
func() {
routeAccessor, commit := p.dag.StatusCache.RouteConditionsAccessor(
k8s.NamespacedNameOf(tlsRoute),
tlsRoute.Generation,
&gatewayapi_v1alpha2.TLSRoute{},
)
defer commit()
for _, routeParentRef := range tlsRoute.Spec.ParentRefs {
// If this parent ref is to a different Gateway, ignore it.
if !gatewayapi.IsRefToGateway(routeParentRef, k8s.NamespacedNameOf(p.source.gateway)) {
continue
}
routeParentStatusAccessor := routeAccessor.StatusUpdateFor(routeParentRef)
// If the Gateway is invalid, set status on the route and we're done.
if gatewayNotProgrammedCondition != nil {
routeParentStatusAccessor.AddCondition(gatewayapi_v1beta1.RouteConditionAccepted, metav1.ConditionFalse, status.ReasonInvalidGateway, "Invalid Gateway")
return
}
// Get the list of listeners that are (a) included by this parent ref, and
// (b) allow the route (based on kind, namespace).
allowedListeners := p.getListenersForRouteParentRef(routeParentRef, tlsRoute.Namespace, KindTLSRoute, readyListeners, routeParentStatusAccessor)
if len(allowedListeners) == 0 {
continue
}
// Keep track of the number of intersecting hosts
// between the route and all allowed listeners for
// this parent ref so that we can set the appropriate
// route parent status condition if there were none.
hostCount := 0
for _, listener := range allowedListeners {
attached, hosts := p.computeTLSRoute(tlsRoute, routeParentStatusAccessor, listener)
if attached {
listenerAttachedRoutes[string(listener.listener.Name)]++
}
hostCount += hosts.Len()
}
if hostCount == 0 {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
gatewayapi_v1beta1.RouteReasonNoMatchingListenerHostname,
"No intersecting hostnames were found between the listener and the route.",
)
} else {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionTrue,
gatewayapi_v1beta1.RouteReasonAccepted,
"Accepted TLSRoute",
)
}
}
}()
}
for listenerName, attachedRoutes := range listenerAttachedRoutes {
gwAccessor.SetListenerAttachedRoutes(listenerName, attachedRoutes)
}
p.computeGatewayConditions(gwAccessor, gatewayNotProgrammedCondition)
}
func (p *GatewayAPIProcessor) getListenersForRouteParentRef(
routeParentRef gatewayapi_v1beta1.ParentReference,
routeNamespace string,
routeKind gatewayapi_v1beta1.Kind,
validListeners []*listenerInfo,
routeParentStatusAccessor *status.RouteParentStatusUpdate,
) []*listenerInfo {
// Find the set of valid listeners that are relevant given this
// parent ref (either all of them, if the ref is to the entire
// gateway, or one of them, if the ref is to a specific listener,
// or none of them, if the listener(s) the ref targets are invalid).
var selectedListeners []*listenerInfo
for _, validListener := range validListeners {
// We've already verified the parent ref is for this Gateway,
// now check if it has a listener name and port specified.
// Both need to match the listener if specified.
if (routeParentRef.SectionName == nil || *routeParentRef.SectionName == validListener.listener.Name) &&
(routeParentRef.Port == nil || *routeParentRef.Port == validListener.listener.Port) {
selectedListeners = append(selectedListeners, validListener)
}
}
if len(selectedListeners) == 0 {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
gatewayapi_v1beta1.RouteReasonNoMatchingParent,
"No listeners match this parent ref",
)
return nil
}
// Now find the subset of those listeners that allow this route
// to select them, based on route kind and namespace.
var allowedListeners []*listenerInfo
for _, selectedListener := range selectedListeners {
// Check if the listener allows routes of this kind
if !selectedListener.AllowsKind(routeKind) {
continue
}
// Check if the route is in a namespace that the listener allows.
if !p.namespaceMatches(selectedListener.listener.AllowedRoutes.Namespaces, selectedListener.namespaceSelector, routeNamespace) {
continue
}
allowedListeners = append(allowedListeners, selectedListener)
}
if len(allowedListeners) == 0 {
routeParentStatusAccessor.AddCondition(
gatewayapi_v1beta1.RouteConditionAccepted,
metav1.ConditionFalse,
gatewayapi_v1beta1.RouteReasonNotAllowedByListeners,
"No listeners included by this parent ref allowed this attachment.",
)
return nil
}
return allowedListeners
}
type listenerInfo struct {
listener gatewayapi_v1beta1.Listener
allowedKinds []gatewayapi_v1beta1.Kind
namespaceSelector labels.Selector
tlsSecret *Secret
}
func (l *listenerInfo) AllowsKind(kind gatewayapi_v1beta1.Kind) bool {
for _, allowedKind := range l.allowedKinds {
if allowedKind == kind {
return true
}
}
return false
}
// isAddressAssigned returns true if either there are no addresses requested in specAddresses,
// or if at least one address from specAddresses appears in statusAddresses.
func isAddressAssigned(specAddresses, statusAddresses []gatewayapi_v1beta1.GatewayAddress) bool {
if len(specAddresses) == 0 {
return true
}
for _, specAddress := range specAddresses {
for _, statusAddress := range statusAddresses {
// Types must match
if addressTypeDerefOr(specAddress.Type, gatewayapi_v1beta1.IPAddressType) != addressTypeDerefOr(statusAddress.Type, gatewayapi_v1beta1.IPAddressType) {
continue
}
// Values must match
if specAddress.Value != statusAddress.Value {
continue
}
return true
}
}
// No match found, so no spec address is assigned.
return false
}
func addressTypeDerefOr(addressType *gatewayapi_v1beta1.AddressType, defaultAddressType gatewayapi_v1beta1.AddressType) gatewayapi_v1beta1.AddressType {
if addressType != nil {
return *addressType
}
return defaultAddressType
}
// computeListener processes a Listener's spec, including TLS details,
// allowed routes, etc., and sets the appropriate conditions on it in
// the Gateway's .status.listeners. It returns a listenerInfo struct with
// the allowed route kinds and TLS secret (if any).
func (p *GatewayAPIProcessor) computeListener(
listener gatewayapi_v1beta1.Listener,
gwAccessor *status.GatewayStatusUpdate,
validateListenersResult gatewayapi.ValidateListenersResult,
) (bool, *listenerInfo) {
// set the listener's "Programmed" condition based on whether we've
// added any other conditions for the listener. The assumption
// here is that if another condition is set, the listener is
// invalid/not programmed.
defer func() {
listenerStatus := gwAccessor.ListenerStatus[string(listener.Name)]
if listenerStatus == nil || len(listenerStatus.Conditions) == 0 {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionTrue,
gatewayapi_v1beta1.ListenerReasonProgrammed,
"Valid listener",
)
} else {
programmedConditionExists := false
for _, cond := range listenerStatus.Conditions {
if cond.Type == string(gatewayapi_v1beta1.ListenerConditionProgrammed) {
programmedConditionExists = true
break
}
}
// Only set the Programmed condition if it doesn't already
// exist in the status update, since if it does exist,
// it will contain more specific information about what
// was invalid.
if !programmedConditionExists {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
"Invalid listener, see other listener conditions for details",
)
}
}
}()
// If the listener had an invalid protocol/port/hostname, we don't need to go
// any further.
if _, ok := validateListenersResult.InvalidListenerConditions[listener.Name]; ok {
return false, nil
}
// Get a list of the route kinds that the listener accepts.
listenerRouteKinds := p.getListenerRouteKinds(listener, gwAccessor)
gwAccessor.SetListenerSupportedKinds(string(listener.Name), listenerRouteKinds)
var selector labels.Selector
if listener.AllowedRoutes != nil && listener.AllowedRoutes.Namespaces != nil &&
listener.AllowedRoutes.Namespaces.From != nil && *listener.AllowedRoutes.Namespaces.From == gatewayapi_v1beta1.NamespacesFromSelector {
if listener.AllowedRoutes.Namespaces.Selector == nil {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
"Listener.AllowedRoutes.Namespaces.Selector is required when Listener.AllowedRoutes.Namespaces.From is set to \"Selector\".",
)
return false, nil
}
if len(listener.AllowedRoutes.Namespaces.Selector.MatchExpressions)+len(listener.AllowedRoutes.Namespaces.Selector.MatchLabels) == 0 {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
"Listener.AllowedRoutes.Namespaces.Selector must specify at least one MatchLabel or MatchExpression.",
)
return false, nil
}
var err error
selector, err = metav1.LabelSelectorAsSelector(listener.AllowedRoutes.Namespaces.Selector)
if err != nil {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Error parsing Listener.AllowedRoutes.Namespaces.Selector: %v.", err),
)
return false, nil
}
}
var listenerSecret *Secret
// Validate TLS details for HTTPS/TLS protocol listeners.
switch listener.Protocol {
case gatewayapi_v1beta1.HTTPSProtocolType:
// The HTTPS protocol is used for HTTP traffic encrypted with TLS,
// which is to be TLS-terminated at the proxy and then routed to
// backends using HTTPRoutes.
if listener.TLS == nil {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener.TLS is required when protocol is %q.", listener.Protocol),
)
return false, nil
}
if listener.TLS.Mode != nil && *listener.TLS.Mode != gatewayapi_v1beta1.TLSModeTerminate {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener.TLS.Mode must be %q when protocol is %q.", gatewayapi_v1beta1.TLSModeTerminate, listener.Protocol),
)
return false, nil
}
// Resolve the TLS secret.
if listenerSecret = p.resolveListenerSecret(listener.TLS.CertificateRefs, string(listener.Name), gwAccessor); listenerSecret == nil {
// If TLS was configured on the Listener, but the secret ref is invalid, don't allow any
// routes to be bound to this listener since it can't serve TLS traffic.
return false, nil
}
case gatewayapi_v1beta1.TLSProtocolType:
// The TLS protocol is used for TCP traffic encrypted with TLS.
// Gateway API allows TLS to be either terminated at the proxy
// or passed through to the backend, but the former requires using
// TCPRoute to route traffic since the underlying protocol is TCP
// not HTTP, which Contour doesn't support. Therefore, we only
// support "Passthrough" with the TLS protocol, which requires
// the use of TLSRoute to route to backends since the traffic is
// still encrypted.
if listener.TLS == nil {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener.TLS is required when protocol is %q.", listener.Protocol),
)
return false, nil
}
if listener.TLS.Mode == nil || *listener.TLS.Mode != gatewayapi_v1beta1.TLSModePassthrough {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener.TLS.Mode must be %q when protocol is %q.", gatewayapi_v1beta1.TLSModePassthrough, listener.Protocol),
)
return false, nil
}
if len(listener.TLS.CertificateRefs) != 0 {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
fmt.Sprintf("Listener.TLS.CertificateRefs cannot be defined when Listener.TLS.Mode is %q.", gatewayapi_v1beta1.TLSModePassthrough),
)
return false, nil
}
}
return true, &listenerInfo{
listener: listener,
allowedKinds: listenerRouteKinds,
tlsSecret: listenerSecret,
namespaceSelector: selector,
}
}
// getListenerRouteKinds gets a list of the valid route kinds that
// the listener accepts.
func (p *GatewayAPIProcessor) getListenerRouteKinds(listener gatewayapi_v1beta1.Listener, gwAccessor *status.GatewayStatusUpdate) []gatewayapi_v1beta1.Kind {
// None specified on the listener: return the default based on
// the listener's protocol.
if len(listener.AllowedRoutes.Kinds) == 0 {
switch listener.Protocol {
case gatewayapi_v1beta1.HTTPProtocolType:
return []gatewayapi_v1beta1.Kind{KindHTTPRoute}
case gatewayapi_v1beta1.HTTPSProtocolType:
return []gatewayapi_v1beta1.Kind{KindHTTPRoute}
case gatewayapi_v1beta1.TLSProtocolType:
return []gatewayapi_v1beta1.Kind{KindTLSRoute}
}
}
var routeKinds []gatewayapi_v1beta1.Kind
for _, routeKind := range listener.AllowedRoutes.Kinds {
if routeKind.Group != nil && *routeKind.Group != gatewayapi_v1beta1.GroupName {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalidRouteKinds,
fmt.Sprintf("Group %q is not supported, group must be %q", *routeKind.Group, gatewayapi_v1beta1.GroupName),
)
continue
}
if routeKind.Kind != KindHTTPRoute && routeKind.Kind != KindTLSRoute {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalidRouteKinds,
fmt.Sprintf("Kind %q is not supported, kind must be %q or %q", routeKind.Kind, KindHTTPRoute, KindTLSRoute),
)
continue
}
if routeKind.Kind == KindTLSRoute && listener.Protocol != gatewayapi_v1beta1.TLSProtocolType {
gwAccessor.AddListenerCondition(
string(listener.Name),
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalidRouteKinds,
fmt.Sprintf("TLSRoutes are incompatible with listener protocol %q", listener.Protocol),
)
continue
}
routeKinds = append(routeKinds, routeKind.Kind)
}
return routeKinds
}
// resolveListenerSecret validates and resolves a Listener TLS secret
// from a given list of certificateRefs. There must be exactly one
// certificate ref, to a v1.Secret, that exists, is allowed to be referenced
// based on namespace and ReferenceGrants, and is a valid TLS secret.
// Conditions are set if any of these requirements are not met.
func (p *GatewayAPIProcessor) resolveListenerSecret(certificateRefs []gatewayapi_v1beta1.SecretObjectReference, listenerName string, gwAccessor *status.GatewayStatusUpdate) *Secret {
if len(certificateRefs) != 1 {
gwAccessor.AddListenerCondition(
listenerName,
gatewayapi_v1beta1.ListenerConditionProgrammed,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalid,
"Listener.TLS.CertificateRefs must contain exactly one entry",
)
return nil
}
certificateRef := certificateRefs[0]
// Validate a v1.Secret is referenced which can be kind: secret & group: core.
// ref: https://github.com/kubernetes-sigs/gateway-api/pull/562
if !isSecretRef(certificateRef) {
gwAccessor.AddListenerCondition(
listenerName,
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Spec.VirtualHost.TLS.CertificateRefs %q must contain a reference to a core.Secret", certificateRef.Name),
)
return nil
}
// If the secret is in a different namespace than the gateway, then we need to
// check for a ReferenceGrant that allows the reference.
if certificateRef.Namespace != nil && string(*certificateRef.Namespace) != p.source.gateway.Namespace {
if !p.validCrossNamespaceRef(
crossNamespaceFrom{
group: gatewayapi_v1beta1.GroupName,
kind: KindGateway,
namespace: p.source.gateway.Namespace,
},
crossNamespaceTo{
group: "",
kind: "Secret",
namespace: string(*certificateRef.Namespace),
name: string(certificateRef.Name),
},
) {
gwAccessor.AddListenerCondition(
listenerName,
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonRefNotPermitted,
fmt.Sprintf("Spec.VirtualHost.TLS.CertificateRefs %q namespace must match the Gateway's namespace or be covered by a ReferenceGrant", certificateRef.Name),
)
return nil
}
}
var meta types.NamespacedName
if certificateRef.Namespace != nil {
meta = types.NamespacedName{Name: string(certificateRef.Name), Namespace: string(*certificateRef.Namespace)}
} else {
meta = types.NamespacedName{Name: string(certificateRef.Name), Namespace: p.source.gateway.Namespace}
}
listenerSecret, err := p.source.LookupTLSSecret(meta)
if err != nil {
gwAccessor.AddListenerCondition(
listenerName,
gatewayapi_v1beta1.ListenerConditionResolvedRefs,
metav1.ConditionFalse,
gatewayapi_v1beta1.ListenerReasonInvalidCertificateRef,
fmt.Sprintf("Spec.VirtualHost.TLS.CertificateRefs %q referent is invalid: %s", certificateRef.Name, err),
)
return nil
}
return listenerSecret
}
type crossNamespaceFrom struct {
group string
kind string
namespace string
}
type crossNamespaceTo struct {
group string
kind string
namespace string
name string
}
func (p *GatewayAPIProcessor) validCrossNamespaceRef(from crossNamespaceFrom, to crossNamespaceTo) bool {
for _, referenceGrant := range p.source.referencegrants {
// The ReferenceGrant must be defined in the namespace of
// the "to" (the referent).
if referenceGrant.Namespace != to.namespace {
continue
}
// Check if the ReferenceGrant has a matching "from".
var fromAllowed bool
for _, refGrantFrom := range referenceGrant.Spec.From {
if string(refGrantFrom.Namespace) == from.namespace && string(refGrantFrom.Group) == from.group && string(refGrantFrom.Kind) == from.kind {
fromAllowed = true
break
}
}
if !fromAllowed {
continue
}
// Check if the ReferenceGrant has a matching "to".
var toAllowed bool
for _, refGrantTo := range referenceGrant.Spec.To {
if string(refGrantTo.Group) == to.group && string(refGrantTo.Kind) == to.kind && (refGrantTo.Name == nil || *refGrantTo.Name == "" || string(*refGrantTo.Name) == to.name) {
toAllowed = true
break
}
}
if !toAllowed {
continue
}
// If we got here, both the "from" and the "to" were allowed by this
// reference grant.
return true
}
// If we got here, no reference policy or reference grant allowed both the "from" and "to".
return false
}
func isSecretRef(certificateRef gatewayapi_v1beta1.SecretObjectReference) bool {
return certificateRef.Group != nil && *certificateRef.Group == "" &&
certificateRef.Kind != nil && *certificateRef.Kind == "Secret"
}
// computeHosts returns the set of hostnames to match for a route. Both the result
// and the error slice should be considered:
// - if the set of hostnames is non-empty, it should be used for matching (may be ["*"]).
// - if the set of hostnames is empty, there was no intersection between the listener
// hostname and the route hostnames, and the route should be marked "Accepted: false".
// - if the list of errors is non-empty, one or more hostnames was syntactically
// invalid and some condition should be added to the route. This shouldn't be
// possible because of kubebuilder+admission webhook validation but we're being
// defensive here.
func (p *GatewayAPIProcessor) computeHosts(routeHostnames []gatewayapi_v1beta1.Hostname, listenerHostname string) (sets.Set[string], []error) {
// The listener hostname is assumed to be valid because it's been run
// through the `gatewayapi.ValidateListeners` logic, so we don't need
// to validate it here.
// No route hostnames specified: use the listener hostname if specified,
// or else match all hostnames.
if len(routeHostnames) == 0 {
if len(listenerHostname) > 0 {
return sets.New(listenerHostname), nil
}
return sets.New("*"), nil
}
hostnames := sets.New[string]()
var errs []error
for i := range routeHostnames {
routeHostname := string(routeHostnames[i])
// If the route hostname is not valid, record an error and skip it.
if err := gatewayapi.IsValidHostname(routeHostname); err != nil {
errs = append(errs, err)
continue
}
switch {
// No listener hostname: use the route hostname.
case len(listenerHostname) == 0:
hostnames.Insert(routeHostname)
// Listener hostname matches the route hostname: use it.
case listenerHostname == routeHostname:
hostnames.Insert(routeHostname)
// Listener has a wildcard hostname: check if the route hostname matches.
case strings.HasPrefix(listenerHostname, "*"):
if hostnameMatchesWildcardHostname(routeHostname, listenerHostname) {
hostnames.Insert(routeHostname)
}
// Route has a wildcard hostname: check if the listener hostname matches.
case strings.HasPrefix(routeHostname, "*"):
if hostnameMatchesWildcardHostname(listenerHostname, routeHostname) {
hostnames.Insert(listenerHostname)
}
}
}
if len(hostnames) == 0 {
return nil, errs
}
return hostnames, errs
}
// hostnameMatchesWildcardHostname returns true if hostname has the non-wildcard
// portion of wildcardHostname as a suffix, plus at least one DNS label matching the
// wildcard.
func hostnameMatchesWildcardHostname(hostname, wildcardHostname string) bool {
if !strings.HasSuffix(hostname, strings.TrimPrefix(wildcardHostname, "*")) {
return false
}
wildcardMatch := strings.TrimSuffix(hostname, strings.TrimPrefix(wildcardHostname, "*"))
return len(wildcardMatch) > 0
}
// namespaceMatches returns true if namespaces allows
// the provided route namespace.
func (p *GatewayAPIProcessor) namespaceMatches(namespaces *gatewayapi_v1beta1.RouteNamespaces, namespaceSelector labels.Selector, routeNamespace string) bool {
// From indicates where Routes will be selected for this Gateway.
// Possible values are:
// * All: Routes in all namespaces may be used by this Gateway.
// * Selector: Routes in namespaces selected by the selector may be used by
// this Gateway.
// * Same: Only Routes in the same namespace may be used by this Gateway.
if namespaces == nil || namespaces.From == nil {
return true
}
switch *namespaces.From {
case gatewayapi_v1beta1.NamespacesFromAll:
return true
case gatewayapi_v1beta1.NamespacesFromSame:
return p.source.gateway.Namespace == routeNamespace
case gatewayapi_v1beta1.NamespacesFromSelector:
// Look up the route's namespace in the list of cached namespaces.
if ns := p.source.namespaces[routeNamespace]; ns != nil {
// Check that the route's namespace is included in the Gateway's
// namespace selector.
return namespaceSelector.Matches(labels.Set(ns.Labels))
}
}
return true
}
func (p *GatewayAPIProcessor) computeGatewayConditions(gwAccessor *status.GatewayStatusUpdate, gatewayNotProgrammedCondition *metav1.Condition) {
// If Contour's running, the Gateway is considered accepted.
gwAccessor.AddCondition(
gatewayapi_v1beta1.GatewayConditionAccepted,
metav1.ConditionTrue,
gatewayapi_v1beta1.GatewayReasonAccepted,
"Gateway is accepted",
)
switch {
case gatewayNotProgrammedCondition != nil:
gwAccessor.AddCondition(
gatewayapi_v1beta1.GatewayConditionType(gatewayNotProgrammedCondition.Type),
gatewayNotProgrammedCondition.Status,
gatewayapi_v1beta1.GatewayConditionReason(gatewayNotProgrammedCondition.Reason),
gatewayNotProgrammedCondition.Message,
)
default:
// Check for any listeners with a Programmed: false condition.
allListenersProgrammed := true
for _, ls := range gwAccessor.ListenerStatus {
if ls == nil {
continue
}
for _, cond := range ls.Conditions {
if cond.Type == string(gatewayapi_v1beta1.ListenerConditionProgrammed) && cond.Status == metav1.ConditionFalse {
allListenersProgrammed = false
break
}
}
if !allListenersProgrammed {
break
}
}
if !allListenersProgrammed {
// If we have invalid listeners, set Programmed=false.
// TODO(sk) resolve condition type-reason mismatch
gwAccessor.AddCondition(gatewayapi_v1beta1.GatewayConditionProgrammed, metav1.ConditionFalse, gatewayapi_v1beta1.GatewayReasonListenersNotValid, "Listeners are not valid")
} else {
// Otherwise, Programmed=true.
gwAccessor.AddCondition(gatewayapi_v1beta1.GatewayConditionProgrammed, metav1.ConditionTrue, gatewayapi_v1beta1.GatewayReasonProgrammed, status.MessageValidGateway)
}
}
}
func (p *GatewayAPIProcessor) computeTLSRoute(route *gatewayapi_v1alpha2.TLSRoute, routeAccessor *status.RouteParentStatusUpdate, listener *listenerInfo) (bool, sets.Set[string]) {
hosts, errs := p.computeHosts(route.Spec.Hostnames, gatewayapi.HostnameDeref(listener.listener.Hostname))
for _, err := range errs {
// The Gateway API spec does not indicate what to do if syntactically
// invalid hostnames make it through, we're using our best judgment here.
// Theoretically these should be prevented by the combination of kubebuilder
// and admission webhook validations.
routeAccessor.AddCondition(gatewayapi_v1beta1.RouteConditionResolvedRefs, metav1.ConditionFalse, status.ReasonDegraded, err.Error())
}
// If there were no intersections between the listener hostname and the
// route hostnames, the route is not programmed for this listener.
if len(hosts) == 0 {
return false, nil
}
var programmed bool
for _, rule := range route.Spec.Rules {
if len(rule.BackendRefs) == 0 {
routeAccessor.AddCondition(gatewayapi_v1beta1.RouteConditionResolvedRefs, metav1.ConditionFalse, status.ReasonDegraded, "At least one Spec.Rules.BackendRef must be specified.")
continue
}
var proxy TCPProxy
var totalWeight uint32
for _, backendRef := range rule.BackendRefs {
service, cond := p.validateBackendRef(backendRef, KindTLSRoute, route.Namespace)
if cond != nil {
routeAccessor.AddCondition(gatewayapi_v1beta1.RouteConditionType(cond.Type), cond.Status, gatewayapi_v1beta1.RouteConditionReason(cond.Reason), cond.Message)
continue
}
// Route defaults to a weight of "1" unless otherwise specified.
routeWeight := uint32(1)
if backendRef.Weight != nil {
routeWeight = uint32(*backendRef.Weight)
}
// Keep track of all the weights for this set of backendRefs. This will be
// used later to understand if all the weights are set to zero.
totalWeight += routeWeight
// https://github.com/projectcontour/contour/issues/3593
service.Weighted.Weight = routeWeight
proxy.Clusters = append(proxy.Clusters, &Cluster{
Upstream: service,
SNI: service.ExternalName,
Weight: routeWeight,
TimeoutPolicy: ClusterTimeoutPolicy{ConnectTimeout: p.ConnectTimeout},
})
}
// No clusters added: they were all invalid, so reject
// the route (it already has a relevant condition set).
if len(proxy.Clusters) == 0 {
continue