-
Notifications
You must be signed in to change notification settings - Fork 668
/
ingress_processor.go
391 lines (343 loc) · 13.2 KB
/
ingress_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
// 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 (
"strconv"
"strings"
"time"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/projectcontour/contour/internal/annotation"
"github.com/projectcontour/contour/internal/k8s"
"github.com/projectcontour/contour/internal/ref"
"github.com/sirupsen/logrus"
networking_v1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/types"
)
// IngressProcessor translates Ingresses into DAG
// objects and adds them to the DAG.
type IngressProcessor struct {
logrus.FieldLogger
dag *DAG
source *KubernetesCache
// 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
// 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
// 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
// MaxRequestsPerConnection defines the maximum number of requests per connection to the upstream before it is closed.
MaxRequestsPerConnection *uint32
// PerConnectionBufferLimitBytes defines the soft limit on size of the cluster’s new connection read and write buffers.
PerConnectionBufferLimitBytes *uint32
// SetSourceMetadataOnRoutes defines whether to set the Kind,
// Namespace and Name fields on generated DAG routes. This is
// configurable and off by default in order to support the feature
// without requiring all existing test cases to change.
SetSourceMetadataOnRoutes bool
}
// Run translates Ingresses into DAG objects and
// adds them to the DAG.
func (p *IngressProcessor) 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
}()
// setup secure vhosts if there is a matching secret
// we do this first so that the set of active secure vhosts is stable
// during computeIngresses.
p.computeSecureVirtualhosts()
p.computeIngresses()
}
// computeSecureVirtualhosts populates tls parameters of
// secure virtual hosts.
func (p *IngressProcessor) computeSecureVirtualhosts() {
for _, ing := range p.source.ingresses {
for _, tls := range ing.Spec.TLS {
secretName := k8s.NamespacedNameFrom(tls.SecretName, k8s.TLSCertAnnotationNamespace(ing), k8s.DefaultNamespace(ing.GetNamespace()))
sec, err := p.source.LookupTLSSecret(secretName, ing.GetNamespace())
if err != nil {
if _, ok := err.(DelegationNotPermittedError); ok {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("secret", secretName).
Error("certificate delegation not permitted")
} else {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("secret", secretName).
Error("unresolved secret reference")
}
continue
}
// We have validated the TLS secrets, so we can go
// ahead and create the SecureVirtualHost for this
// Ingress.
for _, host := range tls.Hosts {
listener, err := p.dag.GetSingleListener("https")
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
Errorf("error identifying listener")
return
}
// default to a minimum TLS version of 1.2 if it's not specified
minTLSVer := annotation.TLSVersion(annotation.ContourAnnotation(ing, "tls-minimum-protocol-version"), "1.2")
// default to a maximum TLS version of 1.3 if it's not specified
maxTLSVer := annotation.TLSVersion(annotation.ContourAnnotation(ing, "tls-maximum-protocol-version"), "1.3")
if maxTLSVer < minTLSVer {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("minTLSVersion", minTLSVer).
WithField("maxTLSVersion", maxTLSVer).
Errorf("error TLS protocol version, the minimum protocol version is greater than the maximum protocol version")
return
}
svhost := p.dag.EnsureSecureVirtualHost(listener.Name, host)
svhost.Secret = sec
svhost.MinTLSVersion = minTLSVer
svhost.MaxTLSVersion = maxTLSVer
}
}
}
}
func (p *IngressProcessor) computeIngresses() {
// deconstruct each ingress into routes and virtualhost entries
for _, ing := range p.source.ingresses {
// rewrite the default ingress to a stock ingress rule.
rules := rulesFromSpec(ing.Spec)
for _, rule := range rules {
p.computeIngressRule(ing, rule)
}
}
}
func (p *IngressProcessor) computeIngressRule(ing *networking_v1.Ingress, rule networking_v1.IngressRule) {
host := rule.Host
// If host name is blank, rewrite to Envoy's * default host.
if host == "" {
host = "*"
}
var clientCertSecret *Secret
var err error
if p.ClientCertificate != nil {
// Since the client certificate is configured by admin, explicit delegation is not required.
clientCertSecret, err = p.source.LookupTLSSecretInsecure(*p.ClientCertificate)
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("secret", p.ClientCertificate).
Error("tls.envoy-client-certificate contains unresolved secret reference")
return
}
}
for _, httppath := range httppaths(rule) {
path := stringOrDefault(httppath.Path, "/")
// Default to implementation specific path matching if not set.
pathType := ref.Val(httppath.PathType, networking_v1.PathTypeImplementationSpecific)
be := httppath.Backend
m := types.NamespacedName{Name: be.Service.Name, Namespace: ing.Namespace}
port := int(be.Service.Port.Number)
if len(be.Service.Port.Name) > 0 {
_, svcPort, err2 := p.source.LookupService(m, intstr.FromString(be.Service.Port.Name))
if err2 != nil {
p.WithError(err2).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("service", be.Service.Name).
Error("service is not found")
continue
}
port = int(svcPort.Port)
}
s, err := p.dag.EnsureService(m, port, port, p.source, p.EnableExternalNameService)
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("service", be.Service.Name).
Error("unresolved service reference")
continue
}
r, err := p.route(ing, rule.Host, path, pathType, s, clientCertSecret, be.Service.Name, be.Service.Port.Number, p.FieldLogger)
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("regex", path).
Errorf("path regex is not valid")
return
}
// should we create port 80 routes for this ingress
if annotation.TLSRequired(ing) || annotation.HTTPAllowed(ing) {
listener, err := p.dag.GetSingleListener("http")
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
Errorf("error identifying listener")
return
}
vhost := p.dag.EnsureVirtualHost(listener.Name, host)
vhost.AddRoute(r)
}
listener, err := p.dag.GetSingleListener("https")
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
Errorf("error identifying listener")
return
}
// computeSecureVirtualhosts will have populated b.securevirtualhosts
// with the names of tls enabled ingress objects. If host exists then
// it is correctly configured for TLS.
if svh := p.dag.GetSecureVirtualHost(listener.Name, host); svh != nil && host != "*" {
svh.AddRoute(r)
}
}
}
// route builds a dag.Route for the supplied Ingress.
func (p *IngressProcessor) route(ingress *networking_v1.Ingress, host string, path string, pathType networking_v1.PathType, service *Service, clientCertSecret *Secret, serviceName string, servicePort int32, log logrus.FieldLogger) (*Route, error) {
log = log.WithFields(logrus.Fields{
"name": ingress.Name,
"namespace": ingress.Namespace,
})
dynamicHeaders := map[string]string{
"CONTOUR_NAMESPACE": ingress.Namespace,
}
dynamicHeaders["CONTOUR_SERVICE_NAME"] = serviceName
dynamicHeaders["CONTOUR_SERVICE_PORT"] = strconv.Itoa(int(servicePort))
// Get default headersPolicies
reqHP, err := headersPolicyService(p.RequestHeadersPolicy, nil, true, dynamicHeaders)
if err != nil {
return nil, err
}
respHP, err := headersPolicyService(p.ResponseHeadersPolicy, nil, false, dynamicHeaders)
if err != nil {
return nil, err
}
r := &Route{
HTTPSUpgrade: annotation.TLSRequired(ingress),
Websocket: annotation.WebsocketRoutes(ingress)[path],
TimeoutPolicy: ingressTimeoutPolicy(ingress, log),
RetryPolicy: ingressRetryPolicy(ingress, log),
Clusters: []*Cluster{{
Upstream: service,
Protocol: service.Protocol,
ClientCertificate: clientCertSecret,
RequestHeadersPolicy: reqHP,
ResponseHeadersPolicy: respHP,
TimeoutPolicy: ClusterTimeoutPolicy{ConnectTimeout: p.ConnectTimeout},
MaxRequestsPerConnection: p.MaxRequestsPerConnection,
PerConnectionBufferLimitBytes: p.PerConnectionBufferLimitBytes,
}},
}
if p.SetSourceMetadataOnRoutes {
r.Kind = "Ingress"
r.Namespace = ingress.Namespace
r.Name = ingress.Name
}
switch pathType {
case networking_v1.PathTypePrefix:
prefixMatchType := PrefixMatchSegment
// An "all paths" prefix should be treated as a generic string prefix
// match.
if path == "/" {
prefixMatchType = PrefixMatchString
} else {
// Strip trailing slashes. Ensures /foo matches prefix /foo/
path = strings.TrimRight(path, "/")
}
r.PathMatchCondition = &PrefixMatchCondition{Prefix: path, PrefixMatchType: prefixMatchType}
case networking_v1.PathTypeExact:
r.PathMatchCondition = &ExactMatchCondition{Path: path}
case networking_v1.PathTypeImplementationSpecific:
// If a path "looks like" a regex we give a regex path match.
// Otherwise you get a string prefix match.
if strings.ContainsAny(path, "^+*[]%") {
// validate the regex
if err := ValidateRegex(path); err != nil {
return nil, err
}
r.PathMatchCondition = &RegexMatchCondition{Regex: path}
} else {
r.PathMatchCondition = &PrefixMatchCondition{Prefix: path, PrefixMatchType: PrefixMatchString}
}
}
// 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(host, "*.") {
r.HeaderMatchConditions = append(r.HeaderMatchConditions, wildcardDomainHeaderMatch(host))
}
return r, nil
}
// rulesFromSpec merges the IngressSpec's Rules with a synthetic
// rule representing the default backend.
// Prepend the default backend so it can be overridden by later rules.
func rulesFromSpec(spec networking_v1.IngressSpec) []networking_v1.IngressRule {
rules := spec.Rules
if backend := spec.DefaultBackend; backend != nil {
rule := defaultBackendRule(backend)
rules = append([]networking_v1.IngressRule{rule}, rules...)
}
return rules
}
// defaultBackendRule returns an IngressRule that represents the IngressBackend.
func defaultBackendRule(be *networking_v1.IngressBackend) networking_v1.IngressRule {
return networking_v1.IngressRule{
IngressRuleValue: networking_v1.IngressRuleValue{
HTTP: &networking_v1.HTTPIngressRuleValue{
Paths: []networking_v1.HTTPIngressPath{{
Backend: networking_v1.IngressBackend{
Service: &networking_v1.IngressServiceBackend{
Name: be.Service.Name,
Port: be.Service.Port,
},
},
}},
},
},
}
}
func stringOrDefault(s, def string) string {
if s == "" {
return def
}
return s
}
// httppaths returns a slice of HTTPIngressPath values for a given IngressRule.
// In the case that the IngressRule contains no valid HTTPIngressPaths, a
// nil slice is returned.
func httppaths(rule networking_v1.IngressRule) []networking_v1.HTTPIngressPath {
if rule.IngressRuleValue.HTTP == nil {
// rule.IngressRuleValue.HTTP value is optional.
return nil
}
return rule.IngressRuleValue.HTTP.Paths
}