-
Notifications
You must be signed in to change notification settings - Fork 665
/
httpproxy_processor.go
1589 lines (1373 loc) · 56.2 KB
/
httpproxy_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 (
"errors"
"fmt"
"net/http"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
contour_api_v1 "github.com/projectcontour/contour/apis/projectcontour/v1"
contour_api_v1alpha1 "github.com/projectcontour/contour/apis/projectcontour/v1alpha1"
"github.com/projectcontour/contour/internal/annotation"
"github.com/projectcontour/contour/internal/k8s"
"github.com/projectcontour/contour/internal/status"
"github.com/projectcontour/contour/internal/timeout"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/apimachinery/pkg/util/sets"
)
// defaultMaxRequestBytes specifies default value maxRequestBytes for AuthorizationServer
const defaultMaxRequestBytes uint32 = 1024
// defaultExtensionRef populates the unset fields in ref with default values.
func defaultExtensionRef(ref contour_api_v1.ExtensionServiceReference) contour_api_v1.ExtensionServiceReference {
if ref.APIVersion == "" {
ref.APIVersion = contour_api_v1alpha1.GroupVersion.String()
}
return ref
}
// HTTPProxyProcessor translates HTTPProxies into DAG
// objects and adds them to the DAG.
type HTTPProxyProcessor struct {
dag *DAG
source *KubernetesCache
orphaned map[types.NamespacedName]bool
// DisablePermitInsecure disables the use of the
// permitInsecure field in HTTPProxy.
DisablePermitInsecure bool
// FallbackCertificate is the optional identifier of the
// TLS secret to use by default when SNI is not set on a
// request.
FallbackCertificate *types.NamespacedName
// 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
// DNSLookupFamily defines how external names are looked up
// When configured as V4, the DNS resolver will only perform a lookup
// for addresses in the IPv4 family. If V6 is configured, the DNS resolver
// will only perform a lookup for addresses in the IPv6 family.
// If AUTO is configured, the DNS resolver will first perform a lookup
// for addresses in the IPv6 family and fallback to a lookup for addresses
// in the IPv4 family. If ALL is specified, the DNS resolver will perform a lookup for
// both IPv4 and IPv6 families, and return all resolved addresses.
// When this is used, Happy Eyeballs will be enabled for upstream connections.
// Refer to Happy Eyeballs Support for more information.
// Note: This only applies to externalName clusters.
DNSLookupFamily contour_api_v1alpha1.ClusterDNSFamilyType
// ClientCertificate is the optional identifier of the TLS secret containing client certificate and
// private key to be used when establishing TLS connection to upstream cluster.
ClientCertificate *types.NamespacedName
// Request headers that will be set on all routes (optional).
RequestHeadersPolicy *HeadersPolicy
// Response headers that will be set on all routes (optional).
ResponseHeadersPolicy *HeadersPolicy
// ConnectTimeout defines how long the proxy should wait when establishing connection to upstream service.
ConnectTimeout time.Duration
}
// Run translates HTTPProxies into DAG objects and
// adds them to the DAG.
func (p *HTTPProxyProcessor) Run(dag *DAG, source *KubernetesCache) {
p.dag = dag
p.source = source
p.orphaned = make(map[types.NamespacedName]bool, len(p.orphaned))
// reset the processor when we're done
defer func() {
p.dag = nil
p.source = nil
p.orphaned = nil
}()
for _, proxy := range p.validHTTPProxies() {
p.computeHTTPProxy(proxy)
}
for meta := range p.orphaned {
proxy, ok := p.source.httpproxies[meta]
if ok {
pa, commit := p.dag.StatusCache.ProxyAccessor(proxy)
pa.ConditionFor(status.ValidCondition).AddError(contour_api_v1.ConditionTypeOrphanedError,
"Orphaned",
"this HTTPProxy is not part of a delegation chain from a root HTTPProxy")
commit()
}
}
}
func (p *HTTPProxyProcessor) computeHTTPProxy(proxy *contour_api_v1.HTTPProxy) {
pa, commit := p.dag.StatusCache.ProxyAccessor(proxy)
validCond := pa.ConditionFor(status.ValidCondition)
defer commit()
var defaultJWTProvider string
if proxy.Spec.VirtualHost == nil {
// mark HTTPProxy as orphaned.
p.orphaned[k8s.NamespacedNameOf(proxy)] = true
return
}
host := proxy.Spec.VirtualHost.Fqdn
if isBlank(host) {
validCond.AddError(contour_api_v1.ConditionTypeVirtualHostError, "FQDNNotSpecified",
"Spec.VirtualHost.Fqdn must be specified")
return
}
pa.Vhost = host
// Ensure root httpproxy lives in allowed namespace.
// This check must be after we can determine the vhost in order to be able to calculate metrics correctly.
if !p.rootAllowed(proxy.Namespace) {
validCond.AddError(contour_api_v1.ConditionTypeRootNamespaceError, "RootProxyNotAllowedInNamespace",
"root HTTPProxy cannot be defined in this namespace")
return
}
if len(proxy.Spec.Routes) == 0 && len(proxy.Spec.Includes) == 0 && proxy.Spec.TCPProxy == nil {
validCond.AddError(contour_api_v1.ConditionTypeSpecError, "NothingDefined",
"HTTPProxy.Spec must have at least one Route, Include, or a TCPProxy")
return
}
if len(proxy.Spec.VirtualHost.JWTProviders) > 0 {
if proxy.Spec.VirtualHost.TLS == nil || len(proxy.Spec.VirtualHost.TLS.SecretName) == 0 {
validCond.AddError(contour_api_v1.ConditionTypeJWTVerificationError, "JWTVerificationNotPermitted",
"Spec.VirtualHost.JWTProviders can only be defined for root HTTPProxies that terminate TLS")
return
}
}
var tlsEnabled bool
if tls := proxy.Spec.VirtualHost.TLS; tls != nil {
if tls.Passthrough && tls.EnableFallbackCertificate {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSIncompatibleFeatures",
"Spec.VirtualHost.TLS: both Passthrough and enableFallbackCertificate were specified")
}
if !isBlank(tls.SecretName) && tls.Passthrough {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSConfigNotValid",
"Spec.VirtualHost.TLS: both Passthrough and SecretName were specified")
return
}
if isBlank(tls.SecretName) && !tls.Passthrough {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSConfigNotValid",
"Spec.VirtualHost.TLS: neither Passthrough nor SecretName were specified")
return
}
if tls.Passthrough && tls.ClientValidation != nil {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSIncompatibleFeatures",
"Spec.VirtualHost.TLS passthrough cannot be combined with tls.clientValidation")
return
}
tlsEnabled = true
// Attach secrets to TLS enabled vhosts.
if !tls.Passthrough {
secretName := k8s.NamespacedNameFrom(tls.SecretName, k8s.DefaultNamespace(proxy.Namespace))
sec, err := p.source.LookupTLSSecret(secretName)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "SecretNotValid",
"Spec.VirtualHost.TLS Secret %q is invalid: %s", tls.SecretName, err)
return
}
if !p.source.DelegationPermitted(secretName, proxy.Namespace) {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "DelegationNotPermitted",
"Spec.VirtualHost.TLS Secret %q certificate delegation not permitted", tls.SecretName)
return
}
svhost := p.dag.EnsureSecureVirtualHost(host)
svhost.Secret = sec
// default to a minimum TLS version of 1.2 if it's not specified
svhost.MinTLSVersion = annotation.MinTLSVersion(tls.MinimumProtocolVersion, "1.2")
// Check if FallbackCertificate && ClientValidation are both enabled in the same vhost
if tls.EnableFallbackCertificate && tls.ClientValidation != nil {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSIncompatibleFeatures",
"Spec.Virtualhost.TLS fallback & client validation are incompatible")
return
}
// Fallback certificates and authorization are
// incompatible because fallback installs the routes on
// a separate HTTPConnectionManager. We can't have the
// same routes installed on multiple managers with
// inconsistent authorization settings.
if tls.EnableFallbackCertificate && proxy.Spec.VirtualHost.AuthorizationConfigured() {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "TLSIncompatibleFeatures",
"Spec.Virtualhost.TLS fallback & client authorization are incompatible")
return
}
// If FallbackCertificate is enabled, but no cert passed, set error
if tls.EnableFallbackCertificate {
if p.FallbackCertificate == nil {
validCond.AddError(contour_api_v1.ConditionTypeTLSError, "FallbackNotPresent",
"Spec.Virtualhost.TLS enabled fallback but the fallback Certificate Secret is not configured in Contour configuration file")
return
}
sec, err = p.source.LookupTLSSecret(*p.FallbackCertificate)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "FallbackNotValid",
"Spec.Virtualhost.TLS Secret %q fallback certificate is invalid: %s", p.FallbackCertificate, err)
return
}
if !p.source.DelegationPermitted(*p.FallbackCertificate, proxy.Namespace) {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "FallbackNotDelegated",
"Spec.VirtualHost.TLS fallback Secret %q is not configured for certificate delegation", p.FallbackCertificate)
return
}
svhost.FallbackCertificate = sec
}
// Fill in DownstreamValidation when external client validation is enabled.
if tls.ClientValidation != nil {
dv := &PeerValidationContext{
SkipClientCertValidation: tls.ClientValidation.SkipClientCertValidation,
OptionalClientCertificate: tls.ClientValidation.OptionalClientCertificate,
}
if tls.ClientValidation.ForwardClientCertificate != nil {
dv.ForwardClientCertificate = &ClientCertificateDetails{
Subject: tls.ClientValidation.ForwardClientCertificate.Subject,
Cert: tls.ClientValidation.ForwardClientCertificate.Cert,
Chain: tls.ClientValidation.ForwardClientCertificate.Chain,
DNS: tls.ClientValidation.ForwardClientCertificate.DNS,
URI: tls.ClientValidation.ForwardClientCertificate.URI,
}
}
if tls.ClientValidation.CACertificate != "" {
secretName := k8s.NamespacedNameFrom(tls.ClientValidation.CACertificate, k8s.DefaultNamespace(proxy.Namespace))
cacert, err := p.source.LookupCASecret(secretName)
if err != nil {
// PeerValidationContext is requested, but cert is missing or not configured.
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "ClientValidationInvalid",
"Spec.VirtualHost.TLS client validation is invalid: invalid CA Secret %q: %s", secretName, err)
return
}
dv.CACertificate = cacert
} else if !tls.ClientValidation.SkipClientCertValidation {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "ClientValidationInvalid",
"Spec.VirtualHost.TLS client validation is invalid: CA Secret must be specified")
}
if tls.ClientValidation.CertificateRevocationList != "" {
secretName := k8s.NamespacedNameFrom(tls.ClientValidation.CertificateRevocationList, k8s.DefaultNamespace(proxy.Namespace))
crl, err := p.source.LookupCRLSecret(secretName)
if err != nil {
// CRL is missing or not configured.
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "ClientValidationInvalid",
"Spec.VirtualHost.TLS client validation is invalid: invalid CRL Secret %q: %s", secretName, err)
}
dv.CRL = crl
dv.OnlyVerifyLeafCertCrl = tls.ClientValidation.OnlyVerifyLeafCertCrl
}
svhost.DownstreamValidation = dv
}
if proxy.Spec.VirtualHost.AuthorizationConfigured() {
auth := proxy.Spec.VirtualHost.Authorization
ref := defaultExtensionRef(auth.ExtensionServiceRef)
if ref.APIVersion != contour_api_v1alpha1.GroupVersion.String() {
validCond.AddErrorf(contour_api_v1.ConditionTypeAuthError, "AuthBadResourceVersion",
"Spec.Virtualhost.Authorization.extensionRef specifies an unsupported resource version %q", auth.ExtensionServiceRef.APIVersion)
return
}
// Lookup the extension service reference.
extensionName := types.NamespacedName{
Name: ref.Name,
Namespace: stringOrDefault(ref.Namespace, proxy.Namespace),
}
ext := p.dag.GetExtensionCluster(ExtensionClusterName(extensionName))
if ext == nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeAuthError, "ExtensionServiceNotFound",
"Spec.Virtualhost.Authorization.ServiceRef extension service %q not found", extensionName)
return
}
svhost.AuthorizationService = ext
svhost.AuthorizationFailOpen = auth.FailOpen
timeout, err := timeout.Parse(auth.ResponseTimeout)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeAuthError, "AuthResponseTimeoutInvalid",
"Spec.Virtualhost.Authorization.ResponseTimeout is invalid: %s", err)
return
}
if timeout.UseDefault() {
svhost.AuthorizationResponseTimeout = ext.RouteTimeoutPolicy.ResponseTimeout
} else {
svhost.AuthorizationResponseTimeout = timeout
}
if auth.WithRequestBody != nil {
var maxRequestBytes = defaultMaxRequestBytes
if auth.WithRequestBody.MaxRequestBytes != 0 {
maxRequestBytes = auth.WithRequestBody.MaxRequestBytes
}
svhost.AuthorizationServerWithRequestBody = &AuthorizationServerBufferSettings{
MaxRequestBytes: maxRequestBytes,
AllowPartialMessage: auth.WithRequestBody.AllowPartialMessage,
PackAsBytes: auth.WithRequestBody.PackAsBytes,
}
}
}
providerNames := sets.NewString()
for _, jwtProvider := range proxy.Spec.VirtualHost.JWTProviders {
if providerNames.Has(jwtProvider.Name) {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "DuplicateProviderName",
"Spec.VirtualHost.JWTProviders is invalid: duplicate name %s", jwtProvider.Name)
return
}
providerNames.Insert(jwtProvider.Name)
if jwtProvider.Default {
if len(defaultJWTProvider) > 0 {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "MultipleDefaultProvidersSpecified",
"Spec.VirtualHost.JWTProviders is invalid: at most one provider can be set as the default")
return
}
defaultJWTProvider = jwtProvider.Name
}
jwksURL, err := url.Parse(jwtProvider.RemoteJWKS.URI)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSURIInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.URI is invalid: %s", err)
return
}
if jwksURL.Scheme != "http" && jwksURL.Scheme != "https" {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSSchemeInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.URI has invalid scheme %q, must be http or https", jwksURL.Scheme)
return
}
var uv *PeerValidationContext
if jwtProvider.RemoteJWKS.UpstreamValidation != nil {
if jwksURL.Scheme == "http" {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSUpstreamValidationInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.UpstreamValidation must not be specified when URI scheme is http.")
return
}
// If the CACertificate name in the UpstreamValidation is namespaced and the namespace
// is not the proxy's namespace, check if the referenced secret is permitted to be
// delegated to the proxy's namespace.
// By default, a non-namespaced CACertificate is expected to reside in the proxy's namespace.
caCertNamespacedName := k8s.NamespacedNameFrom(jwtProvider.RemoteJWKS.UpstreamValidation.CACertificate, k8s.DefaultNamespace(proxy.Namespace))
if !p.source.DelegationPermitted(caCertNamespacedName, proxy.Namespace) {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSCACertificateNotDelegated",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.UpstreamValidation.CACertificate Secret %q is not configured for certificate delegation", caCertNamespacedName)
return
}
uv, err = p.source.LookupUpstreamValidation(jwtProvider.RemoteJWKS.UpstreamValidation, caCertNamespacedName)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSUpstreamValidationInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.UpstreamValidation is invalid: %s", err)
return
}
}
jwksTimeout := time.Second
if len(jwtProvider.RemoteJWKS.Timeout) > 0 {
res, err := time.ParseDuration(jwtProvider.RemoteJWKS.Timeout)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSTimeoutInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.Timeout is invalid: %s", err)
return
}
jwksTimeout = res
}
var cacheDuration *time.Duration
if len(jwtProvider.RemoteJWKS.CacheDuration) > 0 {
res, err := time.ParseDuration(jwtProvider.RemoteJWKS.CacheDuration)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSCacheDurationInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.CacheDuration is invalid: %s", err)
return
}
cacheDuration = &res
}
// Check for a specified port and use it, else use the
// standard ports by scheme.
var port int
switch {
case len(jwksURL.Port()) > 0:
p, err := strconv.Atoi(jwksURL.Port())
if err != nil {
// This theoretically shouldn't be possible as jwksURL.Port() will
// only return a value if it's numeric, but we need to convert to
// int anyway so handle the error.
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSPortInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.URI has an invalid port: %s", err)
return
}
port = p
case jwksURL.Scheme == "http":
port = 80
case jwksURL.Scheme == "https":
port = 443
}
// Get the DNS lookup family if specified, otherwise
// default to to the Contour-wide setting.
dnsLookupFamily := ""
switch jwtProvider.RemoteJWKS.DNSLookupFamily {
case "auto", "v4", "v6", "all":
dnsLookupFamily = jwtProvider.RemoteJWKS.DNSLookupFamily
case "":
dnsLookupFamily = string(p.DNSLookupFamily)
default:
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "RemoteJWKSDNSLookupFamilyInvalid",
"Spec.VirtualHost.JWTProviders.RemoteJWKS.DNSLookupFamily has an invalid value %q, must be auto, all, v4 or v6", jwtProvider.RemoteJWKS.DNSLookupFamily)
return
}
svhost.JWTProviders = append(svhost.JWTProviders, JWTProvider{
Name: jwtProvider.Name,
Issuer: jwtProvider.Issuer,
Audiences: jwtProvider.Audiences,
RemoteJWKS: RemoteJWKS{
URI: jwtProvider.RemoteJWKS.URI,
Timeout: jwksTimeout,
Cluster: DNSNameCluster{
Address: jwksURL.Hostname(),
Scheme: jwksURL.Scheme,
Port: port,
DNSLookupFamily: dnsLookupFamily,
UpstreamValidation: uv,
},
CacheDuration: cacheDuration,
},
ForwardJWT: jwtProvider.ForwardJWT,
})
}
}
}
if proxy.Spec.TCPProxy != nil {
if !tlsEnabled {
validCond.AddError(contour_api_v1.ConditionTypeTCPProxyError, "TLSMustBeConfigured",
"Spec.TCPProxy requires that either Spec.TLS.Passthrough or Spec.TLS.SecretName be set")
return
}
if !p.processHTTPProxyTCPProxy(validCond, proxy, nil, host) {
return
}
}
routes := p.computeRoutes(validCond, proxy, proxy, nil, nil, tlsEnabled, defaultJWTProvider)
insecure := p.dag.EnsureVirtualHost(host)
cp, err := toCORSPolicy(proxy.Spec.VirtualHost.CORSPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeCORSError, "PolicyDidNotParse",
"Spec.VirtualHost.CORSPolicy: %s", err)
return
}
insecure.CORSPolicy = cp
rlp, err := rateLimitPolicy(proxy.Spec.VirtualHost.RateLimitPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "RateLimitPolicyNotValid",
"Spec.VirtualHost.RateLimitPolicy is invalid: %s", err)
return
}
insecure.RateLimitPolicy = rlp
addRoutes(insecure, routes)
// if TLS is enabled for this virtual host and there is no tcp proxy defined,
// then add routes to the secure virtualhost definition.
if tlsEnabled && proxy.Spec.TCPProxy == nil {
secure := p.dag.EnsureSecureVirtualHost(host)
secure.CORSPolicy = cp
rlp, err := rateLimitPolicy(proxy.Spec.VirtualHost.RateLimitPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "RateLimitPolicyNotValid",
"Spec.VirtualHost.RateLimitPolicy is invalid: %s", err)
return
}
secure.RateLimitPolicy = rlp
addRoutes(secure, routes)
// Process JWT verification requirements.
for _, route := range routes {
// JWT verification not enabled for the vhost: error if the route
// specifies a JWT provider.
if len(secure.JWTProviders) == 0 {
if len(route.JWTProvider) == 0 {
continue
}
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "JWTProviderNotDefined",
"Route references an undefined JWT provider %q", route.JWTProvider)
return
}
// JWT verification enabled for the vhost: error if the route
// specifies a JWT provider that does not exist.
if len(route.JWTProvider) > 0 {
var found bool
for _, provider := range secure.JWTProviders {
if provider.Name == route.JWTProvider {
found = true
break
}
}
if !found {
validCond.AddErrorf(contour_api_v1.ConditionTypeJWTVerificationError, "JWTProviderNotDefined",
"Route references an undefined JWT provider %q", route.JWTProvider)
return
}
}
}
}
}
type vhost interface {
AddRoute(*Route)
}
// addRoutes adds all routes to the vhost supplied.
func addRoutes(vhost vhost, routes []*Route) {
for _, route := range routes {
vhost.AddRoute(route)
}
}
func (p *HTTPProxyProcessor) computeRoutes(
validCond *contour_api_v1.DetailedCondition,
rootProxy *contour_api_v1.HTTPProxy,
proxy *contour_api_v1.HTTPProxy,
conditions []contour_api_v1.MatchCondition,
visited []*contour_api_v1.HTTPProxy,
enforceTLS bool,
defaultJWTProvider string,
) []*Route {
for _, v := range visited {
// ensure we are not following an edge that produces a cycle
var path []string
for _, vir := range visited {
path = append(path, fmt.Sprintf("%s/%s", vir.Namespace, vir.Name))
}
if v.Name == proxy.Name && v.Namespace == proxy.Namespace {
path = append(path, fmt.Sprintf("%s/%s", proxy.Namespace, proxy.Name))
validCond.AddErrorf(contour_api_v1.ConditionTypeIncludeError, "IncludeCreatesCycle",
"include creates an include cycle: %s", strings.Join(path, " -> "))
return nil
}
}
visited = append(visited, proxy)
var routes []*Route
// Loop over and process all includes, including checking for duplicate conditions.
seenConds := map[string][]matchConditionAggregate{}
for _, include := range proxy.Spec.Includes {
namespace := include.Namespace
if namespace == "" {
namespace = proxy.Namespace
}
if err := pathMatchConditionsValid(include.Conditions); err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeIncludeError, "PathMatchConditionsNotValid",
"include: %s", err)
continue
}
if err := headerMatchConditionsValid(include.Conditions); err != nil {
validCond.AddError(contour_api_v1.ConditionTypeRouteError, "HeaderMatchConditionsNotValid",
err.Error())
continue
}
// Check to see if we have any duplicate include conditions.
if includeMatchConditionsIdentical(include, seenConds) {
validCond.AddError(contour_api_v1.ConditionTypeIncludeError, "DuplicateMatchConditions",
"duplicate conditions defined on an include")
continue
}
includedProxy, ok := p.source.httpproxies[types.NamespacedName{Name: include.Name, Namespace: namespace}]
if !ok {
validCond.AddErrorf(contour_api_v1.ConditionTypeIncludeError, "IncludeNotFound",
"include %s/%s not found", namespace, include.Name)
// Set 502 response when include was not found but include condition was valid.
if len(include.Conditions) > 0 {
routes = append(routes, &Route{
PathMatchCondition: mergePathMatchConditions(include.Conditions),
HeaderMatchConditions: mergeHeaderMatchConditions(include.Conditions),
DirectResponse: directResponse(http.StatusBadGateway, ""),
})
}
continue
}
if includedProxy.Spec.VirtualHost != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeIncludeError, "RootIncludesRoot",
"root httpproxy cannot include another root httpproxy")
continue
}
inc, incCommit := p.dag.StatusCache.ProxyAccessor(includedProxy)
incValidCond := inc.ConditionFor(status.ValidCondition)
routes = append(routes, p.computeRoutes(incValidCond, rootProxy, includedProxy, append(conditions, include.Conditions...), visited, enforceTLS, defaultJWTProvider)...)
incCommit()
// dest is not an orphaned httpproxy, as there is an httpproxy that points to it
delete(p.orphaned, types.NamespacedName{Name: includedProxy.Name, Namespace: includedProxy.Namespace})
}
dynamicHeaders := map[string]string{
"CONTOUR_NAMESPACE": proxy.Namespace,
}
for _, route := range proxy.Spec.Routes {
if err := routeActionCountValid(route); err != nil {
validCond.AddError(contour_api_v1.ConditionTypeRouteError, "RouteActionCountNotValid", err.Error())
return nil
}
if err := pathMatchConditionsValid(route.Conditions); err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "PathMatchConditionsNotValid",
"route: %s", err)
return nil
}
routeConditions := conditions
routeConditions = append(routeConditions, route.Conditions...)
// Look for invalid header conditions on this route
if err := headerMatchConditionsValid(routeConditions); err != nil {
validCond.AddError(contour_api_v1.ConditionTypeRouteError, "HeaderMatchConditionsNotValid",
err.Error())
return nil
}
reqHP, err := headersPolicyRoute(route.RequestHeadersPolicy, true /* allow Host */, dynamicHeaders)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "RequestHeadersPolicyInvalid",
"%s on request headers", err)
return nil
}
respHP, err := headersPolicyRoute(route.ResponseHeadersPolicy, false /* disallow Host */, dynamicHeaders)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "ResponseHeaderPolicyInvalid",
"%s on response headers", err)
return nil
}
cookieRP, err := cookieRewritePolicies(route.CookieRewritePolicies)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "CookieRewritePoliciesInvalid",
"%s on route cookie rewrite rules", err)
return nil
}
rtp, ctp, err := timeoutPolicy(route.TimeoutPolicy, p.ConnectTimeout)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "TimeoutPolicyNotValid",
"route.timeoutPolicy failed to parse: %s", err)
return nil
}
rlp, err := rateLimitPolicy(route.RateLimitPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "RateLimitPolicyNotValid",
"route.rateLimitPolicy is invalid: %s", err)
return nil
}
requestHashPolicies, lbPolicy := loadBalancerRequestHashPolicies(route.LoadBalancerPolicy, validCond)
redirectPolicy, err := redirectRoutePolicy(route.RequestRedirectPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "RequestRedirectPolicy",
"route.requestRedirectPolicy is invalid: %s", err)
return nil
}
directPolicy := directResponsePolicy(route.DirectResponsePolicy)
r := &Route{
PathMatchCondition: mergePathMatchConditions(routeConditions),
HeaderMatchConditions: mergeHeaderMatchConditions(routeConditions),
Websocket: route.EnableWebsockets,
HTTPSUpgrade: routeEnforceTLS(enforceTLS, route.PermitInsecure && !p.DisablePermitInsecure),
TimeoutPolicy: rtp,
RetryPolicy: retryPolicy(route.RetryPolicy),
RequestHeadersPolicy: reqHP,
ResponseHeadersPolicy: respHP,
CookieRewritePolicies: cookieRP,
RateLimitPolicy: rlp,
RequestHashPolicies: requestHashPolicies,
Redirect: redirectPolicy,
DirectResponse: directPolicy,
}
// If the enclosing root proxy enabled authorization,
// enable it on the route and propagate defaults
// downwards.
if rootProxy.Spec.VirtualHost.AuthorizationConfigured() {
// When the ext_authz filter is added to a
// vhost, it is in enabled state, but we can
// disable it per route. We emulate disabling
// it at the vhost layer by defaulting the state
// from the root proxy.
disabled := rootProxy.Spec.VirtualHost.DisableAuthorization()
// Take the default for enabling authorization
// from the virtual host. If this route has a
// policy, let that override.
if route.AuthPolicy != nil {
disabled = route.AuthPolicy.Disabled
}
r.AuthDisabled = disabled
r.AuthContext = route.AuthorizationContext(rootProxy.Spec.VirtualHost.AuthorizationContext())
}
if len(route.GetPrefixReplacements()) > 0 {
if !r.HasPathPrefix() {
validCond.AddError(contour_api_v1.ConditionTypePrefixReplaceError, "MustHavePrefix",
"cannot specify prefix replacements without a prefix condition")
return nil
}
if reason, err := prefixReplacementsAreValid(route.GetPrefixReplacements()); err != nil {
validCond.AddError(contour_api_v1.ConditionTypePrefixReplaceError, reason, err.Error())
return nil
}
// Note that we are guaranteed to always have a prefix
// condition. Even if the CRD user didn't specify a
// prefix condition, mergePathConditions() guarantees
// a prefix of '/'.
routingPrefix := r.PathMatchCondition.(*PrefixMatchCondition).Prefix
// First, try to apply an exact prefix match.
for _, prefix := range route.GetPrefixReplacements() {
if len(prefix.Prefix) > 0 && routingPrefix == prefix.Prefix {
r.PathRewritePolicy = &PathRewritePolicy{
PrefixRewrite: prefix.Replacement,
}
break
}
}
// If there wasn't a match, we can apply the default replacement.
if r.PathRewritePolicy == nil {
for _, prefix := range route.GetPrefixReplacements() {
if len(prefix.Prefix) == 0 {
r.PathRewritePolicy = &PathRewritePolicy{
PrefixRewrite: prefix.Replacement,
}
break
}
}
}
}
for _, service := range route.Services {
if service.Port < 1 || service.Port > 65535 {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "ServicePortInvalid",
"service %q: port must be in the range 1-65535", service.Name)
return nil
}
var healthPort int
healthPolicy := httpHealthCheckPolicy(route.HealthCheckPolicy)
if healthPolicy != nil && service.HealthPort > 0 {
healthPort = service.HealthPort
} else {
healthPort = service.Port
}
m := types.NamespacedName{Name: service.Name, Namespace: proxy.Namespace}
s, err := p.dag.EnsureService(m, intstr.FromInt(service.Port), intstr.FromInt(healthPort), p.source, p.EnableExternalNameService)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "ServiceUnresolvedReference",
"Spec.Routes unresolved service reference: %s", err)
continue
}
// Determine the protocol to use to speak to this Cluster.
protocol, err := getProtocol(service, s)
if err != nil {
validCond.AddError(contour_api_v1.ConditionTypeServiceError, "UnsupportedProtocol", err.Error())
return nil
}
var uv *PeerValidationContext
if (protocol == "tls" || protocol == "h2") && service.UpstreamValidation != nil {
// If the CACertificate name in the UpstreamValidation is namespaced and the namespace
// is not the proxy's namespace, check if the referenced secret is permitted to be
// delegated to the proxy's namespace.
// By default, a non-namespaced CACertificate is expected to reside in the proxy's namespace.
caCertNamespacedName := k8s.NamespacedNameFrom(service.UpstreamValidation.CACertificate, k8s.DefaultNamespace(proxy.Namespace))
if !p.source.DelegationPermitted(caCertNamespacedName, proxy.Namespace) {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "CACertificateNotDelegated",
"service.UpstreamValidation.CACertificate Secret %q is not configured for certificate delegation", caCertNamespacedName)
return nil
}
// we can only validate TLS connections to services that talk TLS
uv, err = p.source.LookupUpstreamValidation(service.UpstreamValidation, caCertNamespacedName)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "TLSUpstreamValidation",
"Service [%s:%d] TLS upstream validation policy error: %s", service.Name, service.Port, err)
return nil
}
}
dynamicHeaders["CONTOUR_SERVICE_NAME"] = service.Name
dynamicHeaders["CONTOUR_SERVICE_PORT"] = strconv.Itoa(service.Port)
reqHP, err := headersPolicyService(p.RequestHeadersPolicy, service.RequestHeadersPolicy, dynamicHeaders)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "RequestHeadersPolicyInvalid",
"%s on request headers", err)
return nil
}
respHP, err := headersPolicyService(p.ResponseHeadersPolicy, service.ResponseHeadersPolicy, dynamicHeaders)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "ResponseHeadersPolicyInvalid",
"%s on response headers", err)
return nil
}
cookieRP, err := cookieRewritePolicies(service.CookieRewritePolicies)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeRouteError, "CookieRewritePoliciesInvalid",
"%s on service cookie rewrite rules", err)
return nil
}
var clientCertSecret *Secret
if p.ClientCertificate != nil {
clientCertSecret, err = p.source.LookupTLSSecret(*p.ClientCertificate)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeTLSError, "SecretNotValid",
"tls.envoy-client-certificate Secret %q is invalid: %s", p.ClientCertificate, err)
return nil
}
}
var slowStart *SlowStartConfig
if service.SlowStartPolicy != nil {
// Currently Envoy implements slow start only for RoundRobin and WeightedLeastRequest LB strategies.
if lbPolicy != "" && lbPolicy != LoadBalancerPolicyRoundRobin && lbPolicy != LoadBalancerPolicyWeightedLeastRequest {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "SlowStartInvalid",
"slow start is only supported with RoundRobin or WeightedLeastRequest load balancer strategy")
return nil
}
slowStart, err = slowStartConfig(service.SlowStartPolicy)
if err != nil {
validCond.AddErrorf(contour_api_v1.ConditionTypeServiceError, "SlowStartInvalid",
"%s on slow start", err)
return nil
}
}
c := &Cluster{
Upstream: s,
LoadBalancerPolicy: lbPolicy,
Weight: uint32(service.Weight),
HTTPHealthCheckPolicy: healthPolicy,
UpstreamValidation: uv,
RequestHeadersPolicy: reqHP,
ResponseHeadersPolicy: respHP,
CookieRewritePolicies: cookieRP,
Protocol: protocol,
SNI: determineSNI(r.RequestHeadersPolicy, reqHP, s),
DNSLookupFamily: string(p.DNSLookupFamily),
ClientCertificate: clientCertSecret,
TimeoutPolicy: ctp,
SlowStartConfig: slowStart,
}
if service.Mirror && r.MirrorPolicy != nil {
validCond.AddError(contour_api_v1.ConditionTypeServiceError, "OnlyOneMirror",
"only one service per route may be nominated as mirror")
return nil
}
if service.Mirror {
r.MirrorPolicy = &MirrorPolicy{
Cluster: c,
}
} else {
r.Clusters = append(r.Clusters, c)
}
}
if len(r.Clusters) == 0 && route.RequestRedirectPolicy == nil && route.DirectResponsePolicy == nil {
r.DirectResponse = directResponse(http.StatusServiceUnavailable, "")
}
// If we have a wildcard match, add a header match regex rule to match the
// hostname so we can be sure to only match one DNS label. This is required
// as Envoy's virtualhost hostname wildcard matching can match multiple
// labels. This match ignores a port in the hostname in case it is present.
if strings.HasPrefix(rootProxy.Spec.VirtualHost.Fqdn, "*.") {
r.HeaderMatchConditions = append(r.HeaderMatchConditions, wildcardDomainHeaderMatch(rootProxy.Spec.VirtualHost.Fqdn))
}
jwt := route.JWTVerificationPolicy
switch {
case jwt != nil && len(route.JWTVerificationPolicy.Require) > 0 && route.JWTVerificationPolicy.Disabled:
validCond.AddError(contour_api_v1.ConditionTypeJWTVerificationError, "InvalidJWTVerificationPolicy",
"route's JWT verification policy cannot specify both require and disabled")
return nil
case jwt != nil && len(route.JWTVerificationPolicy.Require) > 0:
r.JWTProvider = jwt.Require
case jwt != nil && jwt.Disabled:
r.JWTProvider = ""
default:
r.JWTProvider = defaultJWTProvider
}
routes = append(routes, r)
}
routes = expandPrefixMatches(routes)
return routes
}
// processHTTPProxyTCPProxy processes the spec.tcpproxy stanza in a HTTPProxy document
// following the chain of spec.tcpproxy.include references. It returns true if processing
// was successful, otherwise false if an error was encountered. The details of the error
// will be recorded on the status of the relevant HTTPProxy object,
func (p *HTTPProxyProcessor) processHTTPProxyTCPProxy(validCond *contour_api_v1.DetailedCondition, httpproxy *contour_api_v1.HTTPProxy, visited []*contour_api_v1.HTTPProxy, host string) bool {
tcpproxy := httpproxy.Spec.TCPProxy
if tcpproxy == nil {