/
policy.go
722 lines (641 loc) · 21.3 KB
/
policy.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
// 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"
"regexp"
"strings"
"time"
networking_v1 "k8s.io/api/networking/v1"
"k8s.io/utils/pointer"
gatewayapi_v1alpha2 "sigs.k8s.io/gateway-api/apis/v1alpha2"
sesame_api_v1 "github.com/projectsesame/sesame/apis/projectsesame/v1"
"github.com/projectsesame/sesame/internal/annotation"
"github.com/projectsesame/sesame/internal/timeout"
"github.com/sirupsen/logrus"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
)
const (
// LoadBalancerPolicyWeightedLeastRequest specifies the backend with least
// active requests will be chosen by the load balancer.
LoadBalancerPolicyWeightedLeastRequest = "WeightedLeastRequest"
// LoadBalancerPolicyRandom denotes the load balancer will choose a random
// backend when routing a request.
LoadBalancerPolicyRandom = "Random"
// LoadBalancerPolicyRoundRobin denotes the load balancer will route
// requests in a round-robin fashion among backend instances.
LoadBalancerPolicyRoundRobin = "RoundRobin"
// LoadBalancerPolicyCookie denotes load balancing will be performed via a
// Sesame specified cookie.
LoadBalancerPolicyCookie = "Cookie"
// LoadBalancerPolicyRequestHash denotes request attribute hashing is used
// to make load balancing decisions.
LoadBalancerPolicyRequestHash = "RequestHash"
)
// retryOn transforms a slice of retry on values to a comma-separated string.
// CRD validation ensures that all retry on values are valid.
func retryOn(ro []sesame_api_v1.RetryOn) string {
if len(ro) == 0 {
return "5xx"
}
ss := make([]string, len(ro))
for i, value := range ro {
ss[i] = string(value)
}
return strings.Join(ss, ",")
}
func retryPolicy(rp *sesame_api_v1.RetryPolicy) *RetryPolicy {
if rp == nil {
return nil
}
// If PerTryTimeout is not a valid duration string, use the Envoy default
// value, otherwise use the provided value.
// TODO(sk) it might make sense to change the behavior here to be consistent
// with other timeout parsing, meaning use timeout.Parse which would result
// in a disabled per-try timeout if the input was not a valid duration.
perTryTimeout := timeout.DefaultSetting()
if perTryDuration, err := time.ParseDuration(rp.PerTryTimeout); err == nil {
perTryTimeout = timeout.DurationSetting(perTryDuration)
}
numRetries := rp.NumRetries
// If set to -1, then retries set to 0. If set to 0 or
// not supplied, the value is set to the Envoy default of 1.
// Otherwise the value supplied is returned.
switch rp.NumRetries {
case -1:
numRetries = 0
case 1, 0:
numRetries = 1
}
return &RetryPolicy{
RetryOn: retryOn(rp.RetryOn),
RetriableStatusCodes: rp.RetriableStatusCodes,
NumRetries: uint32(numRetries),
PerTryTimeout: perTryTimeout,
}
}
func headersPolicyService(defaultPolicy *HeadersPolicy, policy *sesame_api_v1.HeadersPolicy, dynamicHeaders map[string]string) (*HeadersPolicy, error) {
if defaultPolicy == nil {
return headersPolicyRoute(policy, false, dynamicHeaders)
}
userPolicy, err := headersPolicyRoute(policy, false, dynamicHeaders)
if err != nil {
return nil, err
}
if userPolicy == nil {
userPolicy = &HeadersPolicy{}
}
if userPolicy.Set == nil {
userPolicy.Set = make(map[string]string, len(defaultPolicy.Set))
}
for k, v := range defaultPolicy.Set {
key := http.CanonicalHeaderKey(k)
if key == "Host" {
return nil, fmt.Errorf("rewriting %q header is not supported", key)
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
return nil, fmt.Errorf("invalid set header %q: %v", key, msgs)
}
// if the user policy set on the object does not contain this header then use the default
if _, exists := userPolicy.Set[key]; !exists {
userPolicy.Set[key] = escapeHeaderValue(v, dynamicHeaders)
}
}
// add any default remove header policy if not already set
remove := sets.NewString()
for _, entry := range userPolicy.Remove {
remove.Insert(entry)
}
for _, entry := range defaultPolicy.Remove {
key := http.CanonicalHeaderKey(entry)
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
return nil, fmt.Errorf("invalid set header %q: %v", key, msgs)
}
if !remove.Has(key) {
userPolicy.Remove = append(userPolicy.Remove, key)
}
}
return userPolicy, nil
}
func headersPolicyRoute(policy *sesame_api_v1.HeadersPolicy, allowHostRewrite bool, dynamicHeaders map[string]string) (*HeadersPolicy, error) {
if policy == nil {
return nil, nil
}
set := make(map[string]string, len(policy.Set))
hostRewrite := ""
for _, entry := range policy.Set {
key := http.CanonicalHeaderKey(entry.Name)
if _, ok := set[key]; ok {
return nil, fmt.Errorf("duplicate header addition: %q", key)
}
if key == "Host" {
if !allowHostRewrite {
return nil, fmt.Errorf("rewriting %q header is not supported", key)
}
hostRewrite = entry.Value
continue
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
return nil, fmt.Errorf("invalid set header %q: %v", key, msgs)
}
set[key] = escapeHeaderValue(entry.Value, dynamicHeaders)
}
remove := sets.NewString()
for _, entry := range policy.Remove {
key := http.CanonicalHeaderKey(entry)
if remove.Has(key) {
return nil, fmt.Errorf("duplicate header removal: %q", key)
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
return nil, fmt.Errorf("invalid remove header %q: %v", key, msgs)
}
remove.Insert(key)
}
rl := remove.List()
if len(set) == 0 {
set = nil
}
if len(rl) == 0 {
rl = nil
}
return &HeadersPolicy{
Set: set,
HostRewrite: hostRewrite,
Remove: rl,
}, nil
}
// headersPolicyGatewayAPI builds a *HeaderPolicy for the supplied HTTPRequestHeaderFilter.
// TODO: Take care about the order of operators once https://github.com/kubernetes-sigs/gateway-api/issues/480 was solved.
func headersPolicyGatewayAPI(hf *gatewayapi_v1alpha2.HTTPRequestHeaderFilter) (*HeadersPolicy, error) {
var (
set = make(map[string]string, len(hf.Set))
add = make(map[string]string, len(hf.Add))
remove = sets.NewString()
hostRewrite = ""
errlist = []error{}
)
for _, setHeader := range hf.Set {
key := http.CanonicalHeaderKey(string(setHeader.Name))
if _, ok := set[key]; ok {
errlist = append(errlist, fmt.Errorf("duplicate header addition: %q", key))
continue
}
if key == "Host" {
hostRewrite = setHeader.Value
continue
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
errlist = append(errlist, fmt.Errorf("invalid set header %q: %v", key, msgs))
continue
}
set[key] = escapeHeaderValue(setHeader.Value, nil)
}
for _, addHeader := range hf.Add {
key := http.CanonicalHeaderKey(string(addHeader.Name))
if _, ok := add[key]; ok {
errlist = append(errlist, fmt.Errorf("duplicate header addition: %q", key))
continue
}
if key == "Host" {
hostRewrite = addHeader.Value
continue
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
errlist = append(errlist, fmt.Errorf("invalid add header %q: %v", key, msgs))
continue
}
add[key] = escapeHeaderValue(addHeader.Value, nil)
}
for _, k := range hf.Remove {
key := http.CanonicalHeaderKey(k)
if remove.Has(key) {
errlist = append(errlist, fmt.Errorf("duplicate header removal: %q", key))
continue
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
errlist = append(errlist, fmt.Errorf("invalid remove header %q: %v", key, msgs))
continue
}
remove.Insert(key)
}
rl := remove.List()
if len(set) == 0 {
set = nil
}
if len(rl) == 0 {
rl = nil
}
return &HeadersPolicy{
Add: add,
Set: set,
HostRewrite: hostRewrite,
Remove: rl,
}, utilerrors.NewAggregate(errlist)
}
func escapeHeaderValue(value string, dynamicHeaders map[string]string) string {
// Envoy supports %-encoded variables, so literal %'s in the header's value must be escaped. See:
// https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers#custom-request-response-headers
// Only allow a specific set of known good Envoy dynamic headers to pass through unescaped
if !strings.Contains(value, "%") {
return value
}
escapedValue := strings.ReplaceAll(value, "%", "%%")
for dynamicVar, dynamicVal := range dynamicHeaders {
escapedValue = strings.ReplaceAll(escapedValue, "%%"+dynamicVar+"%%", dynamicVal)
}
for _, envoyVar := range []string{
"DOWNSTREAM_REMOTE_ADDRESS",
"DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT",
"DOWNSTREAM_LOCAL_ADDRESS",
"DOWNSTREAM_LOCAL_ADDRESS_WITHOUT_PORT",
"DOWNSTREAM_LOCAL_PORT",
"DOWNSTREAM_LOCAL_URI_SAN",
"DOWNSTREAM_PEER_URI_SAN",
"DOWNSTREAM_LOCAL_SUBJECT",
"DOWNSTREAM_PEER_SUBJECT",
"DOWNSTREAM_PEER_ISSUER",
"DOWNSTREAM_TLS_SESSION_ID",
"DOWNSTREAM_TLS_CIPHER",
"DOWNSTREAM_TLS_VERSION",
"DOWNSTREAM_PEER_FINGERPRINT_256",
"DOWNSTREAM_PEER_FINGERPRINT_1",
"DOWNSTREAM_PEER_SERIAL",
"DOWNSTREAM_PEER_CERT",
"DOWNSTREAM_PEER_CERT_V_START",
"DOWNSTREAM_PEER_CERT_V_END",
"HOSTNAME",
"PROTOCOL",
"UPSTREAM_REMOTE_ADDRESS",
"RESPONSE_FLAGS",
"RESPONSE_CODE_DETAILS",
} {
escapedValue = strings.ReplaceAll(escapedValue, "%%"+envoyVar+"%%", "%"+envoyVar+"%")
}
// REQ(header-name)
var validReqEnvoyVar = regexp.MustCompile(`%(%REQ\([\w-]+\)%)%`)
escapedValue = validReqEnvoyVar.ReplaceAllString(escapedValue, "$1")
return escapedValue
}
func cookieRewritePolicies(policies []sesame_api_v1.CookieRewritePolicy) ([]CookieRewritePolicy, error) {
validPolicies := make([]CookieRewritePolicy, 0, len(policies))
cookieNames := map[string]struct{}{}
for _, p := range policies {
if _, exists := cookieNames[p.Name]; exists {
return nil, fmt.Errorf("duplicate cookie rewrite rule for cookie %q", p.Name)
}
cookieNames[p.Name] = struct{}{}
policiesSet := 0
var path *string
if p.PathRewrite != nil {
policiesSet++
path = pointer.String(p.PathRewrite.Value)
}
var domain *string
if p.DomainRewrite != nil {
policiesSet++
domain = pointer.String(p.DomainRewrite.Value)
}
// We use a uint here since a pointer to bool cannot be
// distingiuished when unset or false in golang text templates.
// 0 means unset.
secure := uint(0)
if p.Secure != nil {
policiesSet++
// Increment to indicate it has been set.
secure++
if *p.Secure {
// Increment to indicate it is true.
secure++
}
}
if p.SameSite != nil {
policiesSet++
}
if policiesSet == 0 {
return nil, fmt.Errorf("no attributes rewritten for cookie %q", p.Name)
}
validPolicies = append(validPolicies, CookieRewritePolicy{
Name: p.Name,
Path: path,
Domain: domain,
Secure: secure,
SameSite: p.SameSite,
})
}
if len(validPolicies) == 0 {
return nil, nil
}
return validPolicies, nil
}
// ingressRetryPolicy builds a RetryPolicy from ingress annotations.
func ingressRetryPolicy(ingress *networking_v1.Ingress, log logrus.FieldLogger) *RetryPolicy {
retryOn := annotation.SesameAnnotation(ingress, "retry-on")
if len(retryOn) < 1 {
return nil
}
// if there is a non empty retry-on annotation, build a RetryPolicy manually.
rp := &RetryPolicy{
RetryOn: retryOn,
NumRetries: annotation.NumRetries(ingress),
}
perTryTimeout, err := annotation.PerTryTimeout(ingress)
if err != nil {
log.WithError(err).Error("Error parsing per-try-timeout annotation")
return rp
}
rp.PerTryTimeout = perTryTimeout
return rp
}
func ingressTimeoutPolicy(ingress *networking_v1.Ingress, log logrus.FieldLogger) TimeoutPolicy {
response := annotation.SesameAnnotation(ingress, "response-timeout")
if len(response) == 0 {
// Note: due to a misunderstanding the name of the annotation is
// request timeout, but it is actually applied as a timeout on
// the response body.
response = annotation.SesameAnnotation(ingress, "request-timeout")
if len(response) == 0 {
return TimeoutPolicy{
ResponseTimeout: timeout.DefaultSetting(),
IdleTimeout: timeout.DefaultSetting(),
}
}
}
// if the request timeout annotation is present on this ingress
// construct and use the HTTPProxy timeout policy logic.
tp, err := timeoutPolicy(&sesame_api_v1.TimeoutPolicy{
Response: response,
})
if err != nil {
log.WithError(err).Error("Error parsing response-timeout annotation, using the default value")
return TimeoutPolicy{}
}
return tp
}
func timeoutPolicy(tp *sesame_api_v1.TimeoutPolicy) (TimeoutPolicy, error) {
if tp == nil {
return TimeoutPolicy{
ResponseTimeout: timeout.DefaultSetting(),
IdleTimeout: timeout.DefaultSetting(),
}, nil
}
responseTimeout, err := timeout.Parse(tp.Response)
if err != nil {
return TimeoutPolicy{}, fmt.Errorf("error parsing response timeout: %w", err)
}
idleTimeout, err := timeout.Parse(tp.Idle)
if err != nil {
return TimeoutPolicy{}, fmt.Errorf("error parsing idle timeout: %w", err)
}
return TimeoutPolicy{
ResponseTimeout: responseTimeout,
IdleTimeout: idleTimeout,
}, nil
}
func httpHealthCheckPolicy(hc *sesame_api_v1.HTTPHealthCheckPolicy) *HTTPHealthCheckPolicy {
if hc == nil {
return nil
}
return &HTTPHealthCheckPolicy{
Path: hc.Path,
Host: hc.Host,
Interval: time.Duration(hc.IntervalSeconds) * time.Second,
Timeout: time.Duration(hc.TimeoutSeconds) * time.Second,
UnhealthyThreshold: uint32(hc.UnhealthyThresholdCount),
HealthyThreshold: uint32(hc.HealthyThresholdCount),
}
}
func tcpHealthCheckPolicy(hc *sesame_api_v1.TCPHealthCheckPolicy) *TCPHealthCheckPolicy {
if hc == nil {
return nil
}
return &TCPHealthCheckPolicy{
Interval: time.Duration(hc.IntervalSeconds) * time.Second,
Timeout: time.Duration(hc.TimeoutSeconds) * time.Second,
UnhealthyThreshold: hc.UnhealthyThresholdCount,
HealthyThreshold: hc.HealthyThresholdCount,
}
}
// loadBalancerPolicy returns the load balancer strategy or
// blank if no valid strategy is supplied.
func loadBalancerPolicy(lbp *sesame_api_v1.LoadBalancerPolicy) string {
if lbp == nil {
return ""
}
switch lbp.Strategy {
case LoadBalancerPolicyWeightedLeastRequest, LoadBalancerPolicyRandom, LoadBalancerPolicyCookie, LoadBalancerPolicyRequestHash:
return lbp.Strategy
default:
return ""
}
}
func prefixReplacementsAreValid(replacements []sesame_api_v1.ReplacePrefix) (string, error) {
prefixes := map[string]bool{}
for _, r := range replacements {
if prefixes[r.Prefix] {
if len(r.Prefix) > 0 {
// The replacements are not valid if there are duplicates.
return "DuplicateReplacement", fmt.Errorf("duplicate replacement prefix '%s'", r.Prefix)
}
// Can't replace the empty prefix multiple times.
return "AmbiguousReplacement", fmt.Errorf("ambiguous prefix replacement")
}
prefixes[r.Prefix] = true
}
return "", nil
}
func rateLimitPolicy(in *sesame_api_v1.RateLimitPolicy) (*RateLimitPolicy, error) {
if in == nil || (in.Local == nil && in.Global == nil) {
return nil, nil
}
rp := &RateLimitPolicy{}
local, err := localRateLimitPolicy(in.Local)
if err != nil {
return nil, err
}
rp.Local = local
global, err := globalRateLimitPolicy(in.Global)
if err != nil {
return nil, err
}
rp.Global = global
return rp, nil
}
func localRateLimitPolicy(in *sesame_api_v1.LocalRateLimitPolicy) (*LocalRateLimitPolicy, error) {
if in == nil {
return nil, nil
}
if in.Requests <= 0 {
return nil, fmt.Errorf("invalid requests value %d in local rate limit policy", in.Requests)
}
var fillInterval time.Duration
switch in.Unit {
case "second":
fillInterval = time.Second
case "minute":
fillInterval = time.Minute
case "hour":
fillInterval = time.Hour
default:
return nil, fmt.Errorf("invalid unit %q in local rate limit policy", in.Unit)
}
res := &LocalRateLimitPolicy{
MaxTokens: in.Requests + in.Burst,
TokensPerFill: in.Requests,
FillInterval: fillInterval,
ResponseStatusCode: in.ResponseStatusCode,
}
for _, header := range in.ResponseHeadersToAdd {
// initialize map if we haven't yet
if res.ResponseHeadersToAdd == nil {
res.ResponseHeadersToAdd = map[string]string{}
}
key := http.CanonicalHeaderKey(header.Name)
if _, ok := res.ResponseHeadersToAdd[key]; ok {
return nil, fmt.Errorf("duplicate header addition: %q", key)
}
if msgs := validation.IsHTTPHeaderName(key); len(msgs) != 0 {
return nil, fmt.Errorf("invalid header name %q: %v", key, msgs)
}
res.ResponseHeadersToAdd[key] = escapeHeaderValue(header.Value, map[string]string{})
}
return res, nil
}
func globalRateLimitPolicy(in *sesame_api_v1.GlobalRateLimitPolicy) (*GlobalRateLimitPolicy, error) {
if in == nil {
return nil, nil
}
res := &GlobalRateLimitPolicy{}
for _, d := range in.Descriptors {
var rld RateLimitDescriptor
for _, entry := range d.Entries {
// ensure exactly one field is populated on the entry
var set int
if entry.GenericKey != nil {
set++
rld.Entries = append(rld.Entries, RateLimitDescriptorEntry{
GenericKey: &GenericKeyDescriptorEntry{
Key: entry.GenericKey.Key,
Value: entry.GenericKey.Value,
},
})
}
if entry.RequestHeader != nil {
set++
rld.Entries = append(rld.Entries, RateLimitDescriptorEntry{
HeaderMatch: &HeaderMatchDescriptorEntry{
HeaderName: entry.RequestHeader.HeaderName,
Key: entry.RequestHeader.DescriptorKey,
},
})
}
if entry.RequestHeaderValueMatch != nil {
set++
rld.Entries = append(rld.Entries, RateLimitDescriptorEntry{
HeaderValueMatch: &HeaderValueMatchDescriptorEntry{
Headers: headerMatchConditions(entry.RequestHeaderValueMatch.Headers),
ExpectMatch: entry.RequestHeaderValueMatch.ExpectMatch,
Value: entry.RequestHeaderValueMatch.Value,
},
})
}
if entry.RemoteAddress != nil {
set++
rld.Entries = append(rld.Entries, RateLimitDescriptorEntry{
RemoteAddress: &RemoteAddressDescriptorEntry{},
})
}
if set != 1 {
return nil, errors.New("rate limit descriptor entry must have exactly one field set")
}
}
res.Descriptors = append(res.Descriptors, &rld)
}
return res, nil
}
// Validates and returns list of hash policies along with lb actual strategy to
// be used. Will return default strategy and empty list of hash policies if
// validation fails.
func loadBalancerRequestHashPolicies(lbp *sesame_api_v1.LoadBalancerPolicy, validCond *sesame_api_v1.DetailedCondition) ([]RequestHashPolicy, string) {
if lbp == nil {
return nil, ""
}
strategy := loadBalancerPolicy(lbp)
switch strategy {
case LoadBalancerPolicyCookie:
return []RequestHashPolicy{
{CookieHashOptions: &CookieHashOptions{
CookieName: "X-Sesame-Session-Affinity",
TTL: time.Duration(0),
Path: "/",
}},
}, LoadBalancerPolicyCookie
case LoadBalancerPolicyRequestHash:
rhps := []RequestHashPolicy{}
actualStrategy := strategy
hashSourceIPSet := false
// Map of unique header names.
headerHashPolicies := map[string]bool{}
for _, hashPolicy := range lbp.RequestHashPolicies {
rhp := RequestHashPolicy{
Terminal: hashPolicy.Terminal,
}
// Ensure hashing for exactly one request attribute is set.
if (!hashPolicy.HashSourceIP && hashPolicy.HeaderHashOptions == nil) ||
(hashPolicy.HashSourceIP && hashPolicy.HeaderHashOptions != nil) {
validCond.AddWarningf(sesame_api_v1.ConditionTypeSpecError, "IgnoredField",
"ignoring invalid request hash policy, must set exactly one of hashSourceIP or headerHashOptions")
continue
}
if hashPolicy.HashSourceIP {
if hashSourceIPSet {
validCond.AddWarningf(sesame_api_v1.ConditionTypeSpecError, "IgnoredField",
"ignoring invalid request hash policy, hashSourceIP specified multiple times")
continue
}
rhp.HashSourceIP = true
hashSourceIPSet = true
}
if hashPolicy.HeaderHashOptions != nil {
headerName := http.CanonicalHeaderKey(hashPolicy.HeaderHashOptions.HeaderName)
if msgs := validation.IsHTTPHeaderName(headerName); len(msgs) != 0 {
validCond.AddWarningf(sesame_api_v1.ConditionTypeSpecError, "IgnoredField",
"ignoring invalid header hash policy options with invalid header name %q: %v", headerName, msgs)
continue
}
if _, ok := headerHashPolicies[headerName]; ok {
validCond.AddWarningf("SpecError", "IgnoredField",
"ignoring invalid header hash policy options with duplicated header name %s", headerName)
continue
}
headerHashPolicies[headerName] = true
rhp.HeaderHashOptions = &HeaderHashOptions{
HeaderName: headerName,
}
}
rhps = append(rhps, rhp)
}
if len(rhps) == 0 {
validCond.AddWarningf(sesame_api_v1.ConditionTypeSpecError, "IgnoredField",
"ignoring invalid header hash policy options, setting load balancer strategy to default %s", LoadBalancerPolicyRoundRobin)
rhps = nil
actualStrategy = LoadBalancerPolicyRoundRobin
}
return rhps, actualStrategy
default:
return nil, strategy
}
}