-
Notifications
You must be signed in to change notification settings - Fork 668
/
ingress_processor.go
332 lines (290 loc) · 10.8 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
// 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 (
"regexp"
"strconv"
"strings"
"time"
"k8s.io/apimachinery/pkg/util/intstr"
"github.com/projectcontour/contour/internal/annotation"
"github.com/projectcontour/contour/internal/k8s"
"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
}
// 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.LookupSecret(secretName, validTLSSecret)
if err != nil {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("secret", secretName).
Error("unresolved secret reference")
continue
}
if !p.source.DelegationPermitted(secretName, ing.GetNamespace()) {
p.WithError(err).
WithField("name", ing.GetName()).
WithField("namespace", ing.GetNamespace()).
WithField("secret", secretName).
Error("certificate delegation not permitted")
continue
}
// We have validated the TLS secrets, so we can go
// ahead and create the SecureVirtualHost for this
// Ingress.
for _, host := range tls.Hosts {
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(annotation.ContourAnnotation(ing, "tls-minimum-protocol-version"), "1.2")
}
}
}
}
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 {
clientCertSecret, err = p.source.LookupSecret(*p.ClientCertificate, validTLSSecret)
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 := derefPathTypeOr(httppath.PathType, networking_v1.PathTypeImplementationSpecific)
be := httppath.Backend
m := types.NamespacedName{Name: be.Service.Name, Namespace: ing.Namespace}
var port intstr.IntOrString
if len(be.Service.Port.Name) > 0 {
port = intstr.FromString(be.Service.Port.Name)
} else {
port = intstr.FromInt(int(be.Service.Port.Number))
}
s, err := p.dag.EnsureService(m, 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) {
vhost := p.dag.EnsureVirtualHost(host)
vhost.AddRoute(r)
}
// 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(host); svh != nil && host != "*" {
svh.AddRoute(r)
}
}
}
const singleDNSLabelWildcardRegex = "^[a-z0-9]([-a-z0-9]*[a-z0-9])?"
var _ = regexp.MustCompile(singleDNSLabelWildcardRegex)
// 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, dynamicHeaders)
if err != nil {
return nil, err
}
respHP, err := headersPolicyService(p.ResponseHeadersPolicy, nil, 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},
}},
}
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
}
func derefPathTypeOr(ptr *networking_v1.PathType, def networking_v1.PathType) networking_v1.PathType {
if ptr != nil {
return *ptr
}
return def
}
// 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
}