-
Notifications
You must be signed in to change notification settings - Fork 79
/
ingress_translator.go
543 lines (485 loc) · 19.9 KB
/
ingress_translator.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
/*
Copyright 2020 The Knative 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 generator
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
"strings"
"time"
v3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3"
envoycorev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3"
endpoint "github.com/envoyproxy/go-control-plane/envoy/config/endpoint/v3"
route "github.com/envoyproxy/go-control-plane/envoy/config/route/v3"
tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3"
envoymatcherv3 "github.com/envoyproxy/go-control-plane/envoy/type/matcher/v3"
"github.com/envoyproxy/go-control-plane/pkg/wellknown"
"go.uber.org/zap"
"google.golang.org/protobuf/types/known/anypb"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
pkgconfig "knative.dev/net-kourier/pkg/config"
envoy "knative.dev/net-kourier/pkg/envoy/api"
"knative.dev/net-kourier/pkg/reconciler/ingress/config"
"knative.dev/networking/pkg/apis/networking"
"knative.dev/networking/pkg/apis/networking/v1alpha1"
"knative.dev/networking/pkg/certificates"
netconfig "knative.dev/networking/pkg/config"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/logging"
"knative.dev/pkg/system"
"knative.dev/pkg/tracker"
)
type translatedIngress struct {
name types.NamespacedName
localSNIMatches []*envoy.SNIMatch
externalSNIMatches []*envoy.SNIMatch
clusters []*v3.Cluster
externalVirtualHosts []*route.VirtualHost
externalTLSVirtualHosts []*route.VirtualHost
localVirtualHosts []*route.VirtualHost
localTLSVirtualHosts []*route.VirtualHost
}
type IngressTranslator struct {
secretGetter func(ns, name string) (*corev1.Secret, error)
nsConfigmapGetter func(label string) ([]*corev1.ConfigMap, error)
endpointsGetter func(ns, name string) (*corev1.Endpoints, error)
serviceGetter func(ns, name string) (*corev1.Service, error)
tracker tracker.Interface
}
func NewIngressTranslator(
secretGetter func(ns, name string) (*corev1.Secret, error),
nsConfigmapGetter func(label string) ([]*corev1.ConfigMap, error),
endpointsGetter func(ns, name string) (*corev1.Endpoints, error),
serviceGetter func(ns, name string) (*corev1.Service, error),
tracker tracker.Interface) IngressTranslator {
return IngressTranslator{
secretGetter: secretGetter,
nsConfigmapGetter: nsConfigmapGetter,
endpointsGetter: endpointsGetter,
serviceGetter: serviceGetter,
tracker: tracker,
}
}
func (translator *IngressTranslator) translateIngress(ctx context.Context, ingress *v1alpha1.Ingress, extAuthzEnabled bool) (*translatedIngress, error) {
logger := logging.FromContext(ctx)
localIngressTLS := ingress.GetIngressTLSForVisibility(v1alpha1.IngressVisibilityClusterLocal)
externalIngressTLS := ingress.GetIngressTLSForVisibility(v1alpha1.IngressVisibilityExternalIP)
externalSNIMatches := make([]*envoy.SNIMatch, 0, len(externalIngressTLS))
for _, t := range externalIngressTLS {
sniMatch, err := translator.translateIngressTLS(t, ingress)
if err != nil {
return nil, fmt.Errorf("failed to translate ingressTLS: %w", err)
}
externalSNIMatches = append(externalSNIMatches, sniMatch)
}
localSNIMatches := make([]*envoy.SNIMatch, 0, len(localIngressTLS))
for _, t := range localIngressTLS {
sniMatch, err := translator.translateIngressTLS(t, ingress)
if err != nil {
return nil, fmt.Errorf("failed to translate ingressTLS: %w", err)
}
localSNIMatches = append(localSNIMatches, sniMatch)
}
localHosts := make([]*route.VirtualHost, 0, len(ingress.Spec.Rules))
localTLSHosts := make([]*route.VirtualHost, 0, len(ingress.Spec.Rules))
externalHosts := make([]*route.VirtualHost, 0, len(ingress.Spec.Rules))
externalTLSHosts := make([]*route.VirtualHost, 0, len(ingress.Spec.Rules))
clusters := make([]*v3.Cluster, 0, len(ingress.Spec.Rules))
cfg := config.FromContext(ctx)
var err error
var trustChain []byte
if cfg.Network.SystemInternalTLSEnabled() {
trustChain, err = translator.buildTrustChain(logger)
if err != nil {
return nil, err
}
if trustChain == nil {
return nil, fmt.Errorf("failed to build trust-chain, as no valid CA certificate was provided. Please make sure to provide a valid trust-bundle before enabling `system-internal-tls`")
}
}
for i, rule := range ingress.Spec.Rules {
ruleName := fmt.Sprintf("(%s/%s).Rules[%d]", ingress.Namespace, ingress.Name, i)
routes := make([]*route.Route, 0, len(rule.HTTP.Paths))
tlsRoutes := make([]*route.Route, 0, len(rule.HTTP.Paths))
for _, httpPath := range rule.HTTP.Paths {
// Default the path to "/" if none is passed.
path := httpPath.Path
if path == "" {
path = "/"
}
pathName := fmt.Sprintf("%s.Paths[%s]", ruleName, path)
wrs := make([]*route.WeightedCluster_ClusterWeight, 0, len(httpPath.Splits))
for _, split := range httpPath.Splits {
// The FQN of the service is sufficient here, as clusters towards the
// same service are supposed to be deduplicated anyway.
splitName := fmt.Sprintf("%s/%s", split.ServiceNamespace, split.ServiceName)
if err := trackService(translator.tracker, split.ServiceNamespace, split.ServiceName, ingress); err != nil {
return nil, err
}
service, err := translator.serviceGetter(split.ServiceNamespace, split.ServiceName)
if apierrors.IsNotFound(err) {
logger.Warnf("Service '%s/%s' not yet created", split.ServiceNamespace, split.ServiceName)
// TODO(markusthoemmes): Find out if we should actually `continue` here.
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("failed to fetch service '%s/%s': %w", split.ServiceNamespace, split.ServiceName, err)
}
// Match the ingress' port with a port on the Service to find the target.
// Also find out if the target supports HTTP2.
var (
externalPort = int32(80)
targetPort = int32(80)
http2 = false
)
for _, port := range service.Spec.Ports {
if port.Port == split.ServicePort.IntVal || port.Name == split.ServicePort.StrVal {
externalPort = port.Port
targetPort = port.TargetPort.IntVal
}
if port.Name == "http2" || port.Name == "h2c" {
http2 = true
}
}
// Disable HTTP2 if the annotation is specified.
if strings.EqualFold(pkgconfig.GetDisableHTTP2(ingress.Annotations), "true") {
http2 = false
}
var (
publicLbEndpoints []*endpoint.LbEndpoint
typ v3.Cluster_DiscoveryType
)
if service.Spec.Type == corev1.ServiceTypeExternalName {
// If the service is of type ExternalName, we add a single endpoint.
typ = v3.Cluster_LOGICAL_DNS
publicLbEndpoints = []*endpoint.LbEndpoint{
envoy.NewLBEndpoint(service.Spec.ExternalName, uint32(externalPort)),
}
} else {
// For all other types, fetch the endpoints object.
endpoints, err := translator.endpointsGetter(split.ServiceNamespace, split.ServiceName)
if apierrors.IsNotFound(err) {
logger.Warnf("Endpoints '%s/%s' not yet created", split.ServiceNamespace, split.ServiceName)
// TODO(markusthoemmes): Find out if we should actually `continue` here.
return nil, nil
} else if err != nil {
return nil, fmt.Errorf("failed to fetch endpoints '%s/%s': %w", split.ServiceNamespace, split.ServiceName, err)
}
typ = v3.Cluster_STATIC
publicLbEndpoints = lbEndpointsForKubeEndpoints(endpoints, targetPort)
}
connectTimeout := 5 * time.Second
var transportSocket *envoycorev3.TransportSocket
// As Ingress with RewriteHost points to ExternalService(kourier-internal), we don't enable upstream TLS.
if (cfg.Network.SystemInternalTLSEnabled()) && httpPath.RewriteHost == "" {
var err error
transportSocket, err = translator.createUpstreamTransportSocket(http2, split.ServiceNamespace, trustChain)
if err != nil {
return nil, err
}
}
cluster := envoy.NewCluster(splitName, connectTimeout, publicLbEndpoints, http2, transportSocket, typ)
logger.Debugf("adding cluster: %v", cluster)
clusters = append(clusters, cluster)
weightedCluster := envoy.NewWeightedCluster(splitName, uint32(split.Percent), split.AppendHeaders)
wrs = append(wrs, weightedCluster)
}
if len(wrs) != 0 {
// disable ext_authz filter for HTTP01 challenge when the feature is enabled
if extAuthzEnabled && strings.HasPrefix(path, "/.well-known/acme-challenge/") {
routes = append(routes, envoy.NewRouteExtAuthzDisabled(
pathName, matchHeadersFromHTTPPath(httpPath), path, wrs, 0, httpPath.AppendHeaders, httpPath.RewriteHost))
} else if _, ok := os.LookupEnv("KOURIER_HTTPOPTION_DISABLED"); !ok && ingress.Spec.HTTPOption == v1alpha1.HTTPOptionRedirected && rule.Visibility == v1alpha1.IngressVisibilityExternalIP {
// Do not create redirect route when KOURIER_HTTPOPTION_DISABLED is set. This option is useful when front end proxy handles the redirection.
// e.g. Kourier on OpenShift handles HTTPOption by OpenShift Route so KOURIER_HTTPOPTION_DISABLED should be set.
routes = append(routes, envoy.NewRedirectRoute(
pathName, matchHeadersFromHTTPPath(httpPath), path))
} else {
routes = append(routes, envoy.NewRoute(
pathName, matchHeadersFromHTTPPath(httpPath), path, wrs, 0, httpPath.AppendHeaders, httpPath.RewriteHost))
}
if len(ingress.Spec.TLS) != 0 || useHTTPSListenerWithOneCert() {
tlsRoutes = append(tlsRoutes, envoy.NewRoute(
pathName, matchHeadersFromHTTPPath(httpPath), path, wrs, 0, httpPath.AppendHeaders, httpPath.RewriteHost))
}
}
}
if len(routes) == 0 {
// Return nothing if there are not routes to generate.
return nil, nil
}
var virtualHost, virtualTLSHost *route.VirtualHost
if extAuthzEnabled {
contextExtensions := kmeta.UnionMaps(map[string]string{
"client": "kourier",
"visibility": string(rule.Visibility),
}, ingress.GetLabels())
virtualHost = envoy.NewVirtualHostWithExtAuthz(ruleName, contextExtensions, domainsForRule(rule), routes)
if len(tlsRoutes) != 0 {
virtualTLSHost = envoy.NewVirtualHostWithExtAuthz(ruleName, contextExtensions, domainsForRule(rule), tlsRoutes)
}
} else {
virtualHost = envoy.NewVirtualHost(ruleName, domainsForRule(rule), routes)
if len(tlsRoutes) != 0 {
virtualTLSHost = envoy.NewVirtualHost(ruleName, domainsForRule(rule), tlsRoutes)
}
}
localHosts = append(localHosts, virtualHost)
if rule.Visibility == v1alpha1.IngressVisibilityClusterLocal && virtualTLSHost != nil {
localTLSHosts = append(localTLSHosts, virtualTLSHost)
} else if rule.Visibility == v1alpha1.IngressVisibilityExternalIP {
externalHosts = append(externalHosts, virtualHost)
if virtualTLSHost != nil {
externalTLSHosts = append(externalTLSHosts, virtualTLSHost)
}
}
}
return &translatedIngress{
name: types.NamespacedName{
Namespace: ingress.Namespace,
Name: ingress.Name,
},
localSNIMatches: localSNIMatches,
externalSNIMatches: externalSNIMatches,
clusters: clusters,
externalVirtualHosts: externalHosts,
externalTLSVirtualHosts: externalTLSHosts,
localVirtualHosts: localHosts,
localTLSVirtualHosts: localTLSHosts,
}, nil
}
func (translator *IngressTranslator) translateIngressTLS(ingressTLS v1alpha1.IngressTLS, ingress *v1alpha1.Ingress) (*envoy.SNIMatch, error) {
if err := trackSecret(translator.tracker, ingressTLS.SecretNamespace, ingressTLS.SecretName, ingress); err != nil {
return nil, err
}
secret, err := translator.secretGetter(ingressTLS.SecretNamespace, ingressTLS.SecretName)
if err != nil {
return nil, fmt.Errorf("failed to fetch secret: %w", err)
}
// Validate certificate here as these are defined by users.
// We should not send Gateway without validation.
_, err = tls.X509KeyPair(
secret.Data[certificates.CertName],
secret.Data[certificates.PrivateKeyName],
)
if err != nil {
return nil, fmt.Errorf("invalid secret is specified: %w", err)
}
secretRef := types.NamespacedName{
Namespace: ingressTLS.SecretNamespace,
Name: ingressTLS.SecretName,
}
sniMatch := &envoy.SNIMatch{
Hosts: ingressTLS.Hosts,
CertSource: secretRef,
CertificateChain: secret.Data[certificates.CertName],
PrivateKey: secret.Data[certificates.PrivateKeyName],
}
return sniMatch, nil
}
func (translator *IngressTranslator) createUpstreamTransportSocket(http2 bool, namespace string, trustChain []byte) (*envoycorev3.TransportSocket, error) {
var alpnProtocols string
if http2 {
alpnProtocols = "h2"
}
tlsAny, err := anypb.New(createUpstreamTLSContext(trustChain, namespace, alpnProtocols))
if err != nil {
return nil, err
}
return &envoycorev3.TransportSocket{
Name: wellknown.TransportSocketTls,
ConfigType: &envoycorev3.TransportSocket_TypedConfig{
TypedConfig: tlsAny,
},
}, nil
}
func createUpstreamTLSContext(trustChain []byte, namespace string, alpnProtocols ...string) *tlsv3.UpstreamTlsContext {
return &tlsv3.UpstreamTlsContext{
CommonTlsContext: &tlsv3.CommonTlsContext{
AlpnProtocols: alpnProtocols,
TlsParams: &tlsv3.TlsParameters{
TlsMinimumProtocolVersion: tlsv3.TlsParameters_TLSv1_3,
TlsMaximumProtocolVersion: tlsv3.TlsParameters_TLSv1_3,
},
ValidationContextType: &tlsv3.CommonTlsContext_ValidationContext{
ValidationContext: &tlsv3.CertificateValidationContext{
TrustedCa: &envoycorev3.DataSource{
Specifier: &envoycorev3.DataSource_InlineBytes{
InlineBytes: trustChain,
},
},
MatchTypedSubjectAltNames: []*tlsv3.SubjectAltNameMatcher{{
SanType: tlsv3.SubjectAltNameMatcher_DNS,
Matcher: &envoymatcherv3.StringMatcher{
MatchPattern: &envoymatcherv3.StringMatcher_Exact{
// SAN used by Activator
Exact: certificates.DataPlaneRoutingSAN,
},
},
}, {
SanType: tlsv3.SubjectAltNameMatcher_DNS,
Matcher: &envoymatcherv3.StringMatcher{
MatchPattern: &envoymatcherv3.StringMatcher_Exact{
// SAN used by Queue-Proxy in target namespace
Exact: certificates.DataPlaneUserSAN(namespace),
},
},
}},
},
},
},
}
}
// CA can optionally be in `ca.crt` in the `routing-serving-certs` secret
// and/or configured using a trust-bundle via ConfigMap that has the defined label `knative-ca-trust-bundle`.
// Our upstream TLS context needs to trust them all.
func (translator *IngressTranslator) buildTrustChain(logger *zap.SugaredLogger) ([]byte, error) {
var trustChain []byte
routingCA, err := translator.secretGetter(system.Namespace(), netconfig.ServingRoutingCertName)
if err != nil {
return nil, fmt.Errorf("failed to fetch Secret %s/%s: %w", system.Namespace(), netconfig.ServingRoutingCertName, err)
}
routingCABytes := routingCA.Data[certificates.CaCertName]
if len(routingCABytes) > 0 {
if err = checkCertBundle(routingCABytes); err != nil {
logger.Warnf("CA from Secret %s/%s[%s] is invalid and will be ignored: %v",
system.Namespace(), netconfig.ServingRoutingCertName, certificates.CaCertName, err)
} else {
logger.Debugf("Adding CA from Secret %s/%s[%s] to trust chain", system.Namespace(), netconfig.ServingRoutingCertName, certificates.CaCertName)
trustChain = routingCABytes
}
}
cms, err := translator.nsConfigmapGetter(networking.TrustBundleLabelKey)
if err != nil {
return nil, fmt.Errorf("failed to fetch Configmaps with label: %s in namespace: %s: %w", networking.TrustBundleLabelKey, system.Namespace(), err)
}
newline := []byte("\n")
for _, cm := range cms {
for _, bundle := range cm.Data {
if err = checkCertBundle([]byte(bundle)); err != nil {
logger.Warnf("CA bundle from Configmap %s/%s is invalid and will be ignored: %v",
system.Namespace(), cm.Name, err)
} else {
logger.Debugf("Adding CA bundle from Configmap %s/%s to trust chain", system.Namespace(), cm.Name)
if len(trustChain) > 0 {
// Make sure we always have at least one newline between bundles, multiple ones are ok
trustChain = append(trustChain, newline...)
}
trustChain = append(trustChain, []byte(bundle)...)
}
}
}
return trustChain, nil
}
func trackSecret(t tracker.Interface, ns, name string, ingress *v1alpha1.Ingress) error {
return t.TrackReference(tracker.Reference{
Kind: "Secret",
APIVersion: "v1",
Namespace: ns,
Name: name,
}, ingress)
}
func trackService(t tracker.Interface, svcNs, svcName string, ingress *v1alpha1.Ingress) error {
if err := t.TrackReference(tracker.Reference{
Kind: "Service",
APIVersion: "v1",
Namespace: svcNs,
Name: svcName,
}, ingress); err != nil {
return fmt.Errorf("could not track service reference: %w", err)
}
if err := t.TrackReference(tracker.Reference{
Kind: "Endpoints",
APIVersion: "v1",
Namespace: svcNs,
Name: svcName,
}, ingress); err != nil {
return fmt.Errorf("could not track endpoints reference: %w", err)
}
return nil
}
func lbEndpointsForKubeEndpoints(kubeEndpoints *corev1.Endpoints, targetPort int32) []*endpoint.LbEndpoint {
var readyAddressCount int
for _, subset := range kubeEndpoints.Subsets {
readyAddressCount += len(subset.Addresses)
}
if readyAddressCount == 0 {
return nil
}
eps := make([]*endpoint.LbEndpoint, 0, readyAddressCount)
for _, subset := range kubeEndpoints.Subsets {
for _, address := range subset.Addresses {
eps = append(eps, envoy.NewLBEndpoint(address.IP, uint32(targetPort)))
}
}
return eps
}
func matchHeadersFromHTTPPath(httpPath v1alpha1.HTTPIngressPath) []*route.HeaderMatcher {
matchHeaders := make([]*route.HeaderMatcher, 0, len(httpPath.Headers))
for header, matchType := range httpPath.Headers {
matchHeader := &route.HeaderMatcher{
Name: header,
}
if matchType.Exact != "" {
matchHeader.HeaderMatchSpecifier = &route.HeaderMatcher_StringMatch{
StringMatch: &envoymatcherv3.StringMatcher{
MatchPattern: &envoymatcherv3.StringMatcher_Exact{
Exact: matchType.Exact,
},
},
}
}
matchHeaders = append(matchHeaders, matchHeader)
}
return matchHeaders
}
// domainsForRule returns all domains for the given rule.
//
// For example, external domains returns domains with the following formats:
// - sub-route_host.namespace.example.com
// - sub-route_host.namespace.example.com:*
//
// Somehow envoy doesn't match properly gRPC authorities with ports.
// The fix is to include ":*" in the domains.
// This applies both for local and external domains.
// More info https://github.com/envoyproxy/envoy/issues/886
func domainsForRule(rule v1alpha1.IngressRule) []string {
domains := make([]string, 0, 2*len(rule.Hosts))
for _, host := range rule.Hosts {
domains = append(domains, host, host+":*")
}
return domains
}
func checkCertBundle(certs []byte) error {
for block, rest := pem.Decode(certs); block != nil || len(rest) > 0; block, rest = pem.Decode(rest) {
if block != nil {
switch block.Type {
case "CERTIFICATE":
_, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to parse certificate. Invalid certificate found: %s, %v", block.Bytes, err.Error())
}
default:
return fmt.Errorf("failed to parse bundle. Bundle contains something other than a certificate. Type: %s, block: %s", block.Type, block.Bytes)
}
} else {
// if the last certificate is parsed, and we still have rest, there are additional unwanted things in the CM
return fmt.Errorf("failed to parse bundle. Bundle contains something other than a certificate: %s", rest)
}
}
return nil
}