-
Notifications
You must be signed in to change notification settings - Fork 8.3k
/
template.go
1694 lines (1420 loc) · 44.1 KB
/
template.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 2015 The Kubernetes 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 template
import (
"bytes"
"crypto/rand"
"crypto/sha1" // #nosec
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/big"
"net"
"net/url"
"os"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
text_template "text/template"
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/klog/v2"
"k8s.io/ingress-nginx/internal/ingress/annotations/parser"
"k8s.io/ingress-nginx/internal/ingress/annotations/ratelimit"
"k8s.io/ingress-nginx/internal/ingress/controller/config"
ing_net "k8s.io/ingress-nginx/internal/net"
"k8s.io/ingress-nginx/pkg/apis/ingress"
)
const (
slash = "/"
nonIdempotent = "non_idempotent"
defBufferSize = 65535
writeIndentOnEmptyLines = true // backward-compatibility
httpProtocol = "HTTP"
autoHTTPProtocol = "AUTO_HTTP"
httpsProtocol = "HTTPS"
grpcProtocol = "GRPC"
grpcsProtocol = "GRPCS"
fcgiProtocol = "FCGI"
)
const (
stateCode = iota
stateComment
)
// Writer is the interface to render a template
type Writer interface {
// Write renders the template.
// NOTE: Implementors must ensure that the content of the returned slice is not modified by the implementation
// after the return of this function.
Write(conf *config.TemplateConfig) ([]byte, error)
}
// Template ingress template
type Template struct {
tmpl *text_template.Template
bp *BufferPool
}
// NewTemplate returns a new Template instance or an
// error if the specified template file contains errors
func NewTemplate(file string) (*Template, error) {
data, err := os.ReadFile(file)
if err != nil {
return nil, fmt.Errorf("unexpected error reading template %s: %w", file, err)
}
tmpl, err := text_template.New("nginx.tmpl").Funcs(funcMap).Parse(string(data))
if err != nil {
return nil, err
}
return &Template{
tmpl: tmpl,
bp: NewBufferPool(defBufferSize),
}, nil
}
// 1. Removes carriage return symbol (\r)
// 2. Collapses multiple empty lines to single one
// 3. Re-indent
// (ATW: always returns nil)
func cleanConf(in, out *bytes.Buffer) error {
depth := 0
lineStarted := false
emptyLineWritten := false
state := stateCode
for {
c, err := in.ReadByte()
if err != nil {
if err == io.EOF {
return nil
}
return err // unreachable
}
needOutput := false
nextDepth := depth
nextLineStarted := lineStarted
switch state {
case stateCode:
switch c {
case '{':
needOutput = true
nextDepth = depth + 1
nextLineStarted = true
case '}':
needOutput = true
depth--
nextDepth = depth
nextLineStarted = true
case ' ', '\t':
needOutput = lineStarted
case '\r':
rest := in.Bytes()
if len(rest) > 0 {
if rest[0] != '\n' {
c = ' '
needOutput = lineStarted
}
}
case '\n':
needOutput = !(!lineStarted && emptyLineWritten)
nextLineStarted = false
case '#':
needOutput = true
nextLineStarted = true
state = stateComment
default:
needOutput = true
nextLineStarted = true
}
case stateComment:
switch c {
case '\r':
rest := in.Bytes()
if len(rest) > 0 {
if rest[0] != '\n' {
c = ' '
needOutput = lineStarted
}
}
case '\n':
needOutput = true
nextLineStarted = false
state = stateCode
default:
needOutput = true
}
}
if needOutput {
if !lineStarted && (writeIndentOnEmptyLines || c != '\n') {
for i := 0; i < depth; i++ {
err = out.WriteByte('\t') // always nil
if err != nil {
return err
}
}
}
emptyLineWritten = !lineStarted
err = out.WriteByte(c) // always nil
if err != nil {
return err
}
}
depth = nextDepth
lineStarted = nextLineStarted
}
}
/* LuaConfig defines the structure that will be written as a config for lua scripts
The json format should follow what's expected by lua:
use_forwarded_headers = %t,
use_proxy_protocol = %t,
is_ssl_passthrough_enabled = %t,
http_redirect_code = %v,
listen_ports = { ssl_proxy = "%v", https = "%v" },
hsts = %t,
hsts_max_age = %v,
hsts_include_subdomains = %t,
hsts_preload = %t,
*/
type LuaConfig struct {
EnableMetrics bool `json:"enable_metrics"`
ListenPorts LuaListenPorts `json:"listen_ports"`
UseForwardedHeaders bool `json:"use_forwarded_headers"`
UseProxyProtocol bool `json:"use_proxy_protocol"`
IsSSLPassthroughEnabled bool `json:"is_ssl_passthrough_enabled"`
HTTPRedirectCode int `json:"http_redirect_code"`
EnableOCSP bool `json:"enable_ocsp"`
MonitorBatchMaxSize int `json:"monitor_batch_max_size"`
HSTS bool `json:"hsts"`
HSTSMaxAge string `json:"hsts_max_age"`
HSTSIncludeSubdomains bool `json:"hsts_include_subdomains"`
HSTSPreload bool `json:"hsts_preload"`
}
type LuaListenPorts struct {
HTTPSPort string `json:"https"`
StatusPort string `json:"status_port"`
SSLProxyPort string `json:"ssl_proxy"`
}
// Write populates a buffer using a template with NGINX configuration
// and the servers and upstreams created by Ingress rules
func (t *Template) Write(conf *config.TemplateConfig) ([]byte, error) {
tmplBuf := t.bp.Get()
defer t.bp.Put(tmplBuf)
outCmdBuf := t.bp.Get()
defer t.bp.Put(outCmdBuf)
if klog.V(3).Enabled() {
b, err := json.Marshal(*conf)
if err != nil {
klog.Errorf("unexpected error: %v", err)
}
klog.InfoS("NGINX", "configuration", string(b))
}
err := t.tmpl.Execute(tmplBuf, *conf)
if err != nil {
return nil, err
}
// squeezes multiple adjacent empty lines to be single
// spaced this is to avoid the use of regular expressions
err = cleanConf(tmplBuf, outCmdBuf)
if err != nil {
return nil, err
}
// make a copy to ensure that we are no longer modifying the content of the buffer
out := outCmdBuf.Bytes()
res := make([]byte, len(out))
copy(res, out)
return res, nil
}
var funcMap = text_template.FuncMap{
"empty": func(input interface{}) bool {
check, ok := input.(string)
if ok {
return check == ""
}
return true
},
"escapeLiteralDollar": escapeLiteralDollar,
"buildLuaSharedDictionaries": buildLuaSharedDictionaries,
"luaConfigurationRequestBodySize": luaConfigurationRequestBodySize,
"buildLocation": buildLocation,
"buildAuthLocation": buildAuthLocation,
"shouldApplyGlobalAuth": shouldApplyGlobalAuth,
"buildAuthResponseHeaders": buildAuthResponseHeaders,
"buildAuthUpstreamLuaHeaders": buildAuthUpstreamLuaHeaders,
"buildAuthProxySetHeaders": buildAuthProxySetHeaders,
"buildAuthUpstreamName": buildAuthUpstreamName,
"shouldApplyAuthUpstream": shouldApplyAuthUpstream,
"extractHostPort": extractHostPort,
"changeHostPort": changeHostPort,
"buildProxyPass": buildProxyPass,
"filterRateLimits": filterRateLimits,
"buildRateLimitZones": buildRateLimitZones,
"buildRateLimit": buildRateLimit,
"locationConfigForLua": locationConfigForLua,
"buildResolvers": buildResolvers,
"buildUpstreamName": buildUpstreamName,
"isLocationInLocationList": isLocationInLocationList,
"isLocationAllowed": isLocationAllowed,
"buildDenyVariable": buildDenyVariable,
"getenv": os.Getenv,
"contains": strings.Contains,
"split": strings.Split,
"hasPrefix": strings.HasPrefix,
"hasSuffix": strings.HasSuffix,
"trimSpace": strings.TrimSpace,
"toUpper": strings.ToUpper,
"toLower": strings.ToLower,
"formatIP": formatIP,
"quote": quote,
"buildNextUpstream": buildNextUpstream,
"getIngressInformation": getIngressInformation,
"serverConfig": func(all config.TemplateConfig, server *ingress.Server) interface{} {
return struct{ First, Second interface{} }{all, server}
},
"isValidByteSize": isValidByteSize,
"buildForwardedFor": buildForwardedFor,
"buildAuthSignURL": buildAuthSignURL,
"buildAuthSignURLLocation": buildAuthSignURLLocation,
"buildOpentelemetry": buildOpentelemetry,
"proxySetHeader": proxySetHeader,
"enforceRegexModifier": enforceRegexModifier,
"buildCustomErrorDeps": buildCustomErrorDeps,
"buildCustomErrorLocationsPerServer": buildCustomErrorLocationsPerServer,
"shouldLoadModSecurityModule": shouldLoadModSecurityModule,
"buildHTTPListener": buildHTTPListener,
"buildHTTPSListener": buildHTTPSListener,
"buildOpentelemetryForLocation": buildOpentelemetryForLocation,
"shouldLoadOpentelemetryModule": shouldLoadOpentelemetryModule,
"buildModSecurityForLocation": buildModSecurityForLocation,
"buildMirrorLocations": buildMirrorLocations,
"shouldLoadAuthDigestModule": shouldLoadAuthDigestModule,
"buildServerName": buildServerName,
"buildCorsOriginRegex": buildCorsOriginRegex,
}
// escapeLiteralDollar will replace the $ character with ${literal_dollar}
// which is made to work via the following configuration in the http section of
// the template:
//
// geo $literal_dollar {
// default "$";
// }
func escapeLiteralDollar(input interface{}) string {
inputStr, ok := input.(string)
if !ok {
return ""
}
return strings.ReplaceAll(inputStr, `$`, `${literal_dollar}`)
}
// formatIP will wrap IPv6 addresses in [] and return IPv4 addresses
// without modification. If the input cannot be parsed as an IP address
// it is returned without modification.
func formatIP(input string) string {
ip := net.ParseIP(input)
if ip == nil {
return input
}
if v4 := ip.To4(); v4 != nil {
return input
}
return fmt.Sprintf("[%s]", input)
}
func quote(input interface{}) string {
var inputStr string
switch input := input.(type) {
case string:
inputStr = input
case fmt.Stringer:
inputStr = input.String()
case *string:
inputStr = *input
default:
inputStr = fmt.Sprintf("%v", input)
}
return fmt.Sprintf("%q", inputStr)
}
func buildLuaSharedDictionaries(c, s interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return ""
}
_, ok = s.([]*ingress.Server)
if !ok {
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
return ""
}
out := make([]string, 0, len(cfg.LuaSharedDicts))
for name, size := range cfg.LuaSharedDicts {
sizeStr := dictKbToStr(size)
out = append(out, fmt.Sprintf("lua_shared_dict %s %s", name, sizeStr))
}
sort.Strings(out)
return strings.Join(out, ";\n") + ";\n"
}
func luaConfigurationRequestBodySize(c interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return "100M" // just a default number
}
size := cfg.LuaSharedDicts["configuration_data"]
if size < cfg.LuaSharedDicts["certificate_data"] {
size = cfg.LuaSharedDicts["certificate_data"]
}
size += 1024
return dictKbToStr(size)
}
// locationConfigForLua formats some location specific configuration into Lua table represented as string
func locationConfigForLua(l, a interface{}) string {
location, ok := l.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was given", l)
return "{}"
}
all, ok := a.(config.TemplateConfig)
if !ok {
klog.Errorf("expected a 'config.TemplateConfig' type but %T was given", a)
return "{}"
}
/* Lua expects the following vars
force_ssl_redirect = string_to_bool(ngx.var.force_ssl_redirect),
ssl_redirect = string_to_bool(ngx.var.ssl_redirect),
force_no_ssl_redirect = string_to_bool(ngx.var.force_no_ssl_redirect),
preserve_trailing_slash = string_to_bool(ngx.var.preserve_trailing_slash),
use_port_in_redirects = string_to_bool(ngx.var.use_port_in_redirects),
*/
return fmt.Sprintf(`
set $force_ssl_redirect "%t";
set $ssl_redirect "%t";
set $force_no_ssl_redirect "%t";
set $preserve_trailing_slash "%t";
set $use_port_in_redirects "%t";
`,
location.Rewrite.ForceSSLRedirect,
location.Rewrite.SSLRedirect,
isLocationInLocationList(l, all.Cfg.NoTLSRedirectLocations),
location.Rewrite.PreserveTrailingSlash,
location.UsePortInRedirects,
)
}
// buildResolvers returns the resolvers reading the /etc/resolv.conf file
func buildResolvers(res, disableIpv6 interface{}) string {
// NGINX need IPV6 addresses to be surrounded by brackets
nss, ok := res.([]net.IP)
if !ok {
klog.Errorf("expected a '[]net.IP' type but %T was returned", res)
return ""
}
no6, ok := disableIpv6.(bool)
if !ok {
klog.Errorf("expected a 'bool' type but %T was returned", disableIpv6)
return ""
}
if len(nss) == 0 {
return ""
}
r := []string{"resolver"}
for _, ns := range nss {
if ing_net.IsIPV6(ns) {
if no6 {
continue
}
r = append(r, fmt.Sprintf("[%v]", ns))
} else {
r = append(r, ns.String())
}
}
r = append(r, "valid=30s")
if no6 {
r = append(r, "ipv6=off")
}
return strings.Join(r, " ") + ";"
}
func needsRewrite(location *ingress.Location) bool {
if location.Rewrite.Target != "" && location.Rewrite.Target != location.Path {
return true
}
return false
}
// enforceRegexModifier checks if the "rewrite-target" or "use-regex" annotation
// is used on any location path within a server
func enforceRegexModifier(input interface{}) bool {
locations, ok := input.([]*ingress.Location)
if !ok {
klog.Errorf("expected an '[]*ingress.Location' type but %T was returned", input)
return false
}
for _, location := range locations {
if needsRewrite(location) || location.Rewrite.UseRegex {
return true
}
}
return false
}
// buildLocation produces the location string, if the ingress has redirects
// (specified through the nginx.ingress.kubernetes.io/rewrite-target annotation)
func buildLocation(input interface{}, enforceRegex bool) string {
location, ok := input.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
return slash
}
path := location.Path
if enforceRegex {
return fmt.Sprintf(`~* "^%s"`, path)
}
if location.PathType != nil && *location.PathType == networkingv1.PathTypeExact {
return fmt.Sprintf(`= %s`, path)
}
return path
}
func buildAuthLocation(input interface{}, globalExternalAuthURL string) string {
location, ok := input.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
return ""
}
if (location.ExternalAuth.URL == "") && (!shouldApplyGlobalAuth(input, globalExternalAuthURL)) {
return ""
}
str := base64.URLEncoding.EncodeToString([]byte(location.Path))
// removes "=" after encoding
str = strings.ReplaceAll(str, "=", "")
pathType := "default"
if location.PathType != nil {
pathType = fmt.Sprintf("%v", *location.PathType)
}
return fmt.Sprintf("/_external-auth-%v-%v", str, pathType)
}
// shouldApplyGlobalAuth returns true only in case when ExternalAuth.URL is not set and
// GlobalExternalAuth is set and enabled
func shouldApplyGlobalAuth(input interface{}, globalExternalAuthURL string) bool {
location, ok := input.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
}
if (location.ExternalAuth.URL == "") && (globalExternalAuthURL != "") && (location.EnableGlobalAuth) {
return true
}
return false
}
// buildAuthResponseHeaders sets HTTP response headers when `auth-url` is used.
// Based on `auth-keepalive` value we use auth_request_set Nginx directives, or
// we use Lua and Nginx variables instead.
//
// NOTE: Unfortunately auth_request module ignores the keepalive directive (see:
// https://trac.nginx.org/nginx/ticket/1579), that is why we mimic the same
// functionality with access_by_lua_block.
func buildAuthResponseHeaders(proxySetHeader string, headers []string, lua bool) []string {
res := []string{}
if len(headers) == 0 {
return res
}
for i, h := range headers {
if lua {
res = append(res, fmt.Sprintf("set $authHeader%d '';", i))
} else {
hvar := strings.ToLower(h)
hvar = strings.NewReplacer("-", "_").Replace(hvar)
res = append(res, fmt.Sprintf("auth_request_set $authHeader%v $upstream_http_%v;", i, hvar))
}
res = append(res, fmt.Sprintf("%s '%v' $authHeader%v;", proxySetHeader, h, i))
}
return res
}
func buildAuthUpstreamLuaHeaders(headers []string) string {
if len(headers) == 0 {
return ""
}
return strings.Join(headers, ",")
}
func buildAuthProxySetHeaders(headers map[string]string) []string {
res := []string{}
if len(headers) == 0 {
return res
}
for name, value := range headers {
res = append(res, fmt.Sprintf("proxy_set_header '%v' '%v';", name, value))
}
sort.Strings(res)
return res
}
func buildAuthUpstreamName(input interface{}, host string) string {
authPath := buildAuthLocation(input, "")
if authPath == "" || host == "" {
return ""
}
return fmt.Sprintf("%s-%s", host, authPath[2:])
}
// shouldApplyAuthUpstream returns true only in case when ExternalAuth.URL and
// ExternalAuth.KeepaliveConnections are all set
func shouldApplyAuthUpstream(l, c interface{}) bool {
location, ok := l.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", l)
return false
}
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return false
}
if location.ExternalAuth.URL == "" || location.ExternalAuth.KeepaliveConnections == 0 {
return false
}
// Unfortunately, `auth_request` module ignores keepalive in upstream block: https://trac.nginx.org/nginx/ticket/1579
// The workaround is to use `ngx.location.capture` Lua subrequests but it is not supported with HTTP/2
if cfg.UseHTTP2 {
klog.Warning("Upstream keepalive is not supported with HTTP/2")
return false
}
return true
}
// extractHostPort will extract the host:port part from the URL specified by url
func extractHostPort(newURL string) string {
if newURL == "" {
return ""
}
authURL, err := parser.StringToURL(newURL)
if err != nil {
klog.Errorf("expected a valid URL but %s was returned", newURL)
return ""
}
return authURL.Host
}
// changeHostPort will change the host:port part of the url to value
func changeHostPort(newURL, value string) string {
if newURL == "" {
return ""
}
authURL, err := parser.StringToURL(newURL)
if err != nil {
klog.Errorf("expected a valid URL but %s was returned", newURL)
return ""
}
authURL.Host = value
return authURL.String()
}
// buildProxyPass produces the proxy pass string, if the ingress has redirects
// (specified through the nginx.ingress.kubernetes.io/rewrite-target annotation)
// If the annotation nginx.ingress.kubernetes.io/add-base-url:"true" is specified it will
// add a base tag in the head of the response from the service
func buildProxyPass(_ string, b, loc interface{}) string {
backends, ok := b.([]*ingress.Backend)
if !ok {
klog.Errorf("expected an '[]*ingress.Backend' type but %T was returned", b)
return ""
}
location, ok := loc.(*ingress.Location)
if !ok {
klog.Errorf("expected a '*ingress.Location' type but %T was returned", loc)
return ""
}
path := location.Path
proto := "http://"
proxyPass := "proxy_pass"
switch strings.ToUpper(location.BackendProtocol) {
case autoHTTPProtocol:
proto = "$scheme://"
case httpsProtocol:
proto = "https://"
case grpcProtocol:
proto = "grpc://"
proxyPass = "grpc_pass"
case grpcsProtocol:
proto = "grpcs://"
proxyPass = "grpc_pass"
case fcgiProtocol:
proto = ""
proxyPass = "fastcgi_pass"
}
upstreamName := "upstream_balancer"
for _, backend := range backends {
if backend.Name == location.Backend {
if backend.SSLPassthrough {
proto = "https://"
if location.BackendProtocol == grpcsProtocol {
proto = "grpcs://"
}
}
break
}
}
// TODO: add support for custom protocols
if location.Backend == "upstream-default-backend" {
proto = "http://"
proxyPass = "proxy_pass"
}
// defProxyPass returns the default proxy_pass, just the name of the upstream
defProxyPass := fmt.Sprintf("%v %s%s;", proxyPass, proto, upstreamName)
// if the path in the ingress rule is equals to the target: no special rewrite
if path == location.Rewrite.Target {
return defProxyPass
}
if location.Rewrite.Target != "" {
var xForwardedPrefix string
if location.XForwardedPrefix != "" {
xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix %q;\n", proxySetHeader(location), location.XForwardedPrefix)
}
return fmt.Sprintf(`
rewrite "(?i)%s" %s break;
%v%v %s%s;`, path, location.Rewrite.Target, xForwardedPrefix, proxyPass, proto, upstreamName)
}
// default proxy_pass
return defProxyPass
}
func filterRateLimits(input interface{}) []ratelimit.Config {
ratelimits := []ratelimit.Config{}
found := sets.Set[string]{}
servers, ok := input.([]*ingress.Server)
if !ok {
klog.Errorf("expected a '[]ratelimit.RateLimit' type but %T was returned", input)
return ratelimits
}
for _, server := range servers {
for _, loc := range server.Locations {
if loc.RateLimit.ID != "" && !found.Has(loc.RateLimit.ID) {
found.Insert(loc.RateLimit.ID)
ratelimits = append(ratelimits, loc.RateLimit)
}
}
}
return ratelimits
}
// buildRateLimitZones produces an array of limit_conn_zone in order to allow
// rate limiting of request. Each Ingress rule could have up to three zones, one
// for connection limit by IP address, one for limiting requests per minute, and
// one for limiting requests per second.
func buildRateLimitZones(input interface{}) []string {
zones := sets.Set[string]{}
servers, ok := input.([]*ingress.Server)
if !ok {
klog.Errorf("expected a '[]*ingress.Server' type but %T was returned", input)
return zones.UnsortedList()
}
for _, server := range servers {
for _, loc := range server.Locations {
if loc.RateLimit.Connections.Limit > 0 {
zone := fmt.Sprintf("limit_conn_zone $limit_%s zone=%v:%vm;",
loc.RateLimit.ID,
loc.RateLimit.Connections.Name,
loc.RateLimit.Connections.SharedSize)
if !zones.Has(zone) {
zones.Insert(zone)
}
}
if loc.RateLimit.RPM.Limit > 0 {
zone := fmt.Sprintf("limit_req_zone $limit_%s zone=%v:%vm rate=%vr/m;",
loc.RateLimit.ID,
loc.RateLimit.RPM.Name,
loc.RateLimit.RPM.SharedSize,
loc.RateLimit.RPM.Limit)
if !zones.Has(zone) {
zones.Insert(zone)
}
}
if loc.RateLimit.RPS.Limit > 0 {
zone := fmt.Sprintf("limit_req_zone $limit_%s zone=%v:%vm rate=%vr/s;",
loc.RateLimit.ID,
loc.RateLimit.RPS.Name,
loc.RateLimit.RPS.SharedSize,
loc.RateLimit.RPS.Limit)
if !zones.Has(zone) {
zones.Insert(zone)
}
}
}
}
return zones.UnsortedList()
}
// buildRateLimit produces an array of limit_req to be used inside the Path of
// Ingress rules. The order: connections by IP first, then RPS, and RPM last.
func buildRateLimit(input interface{}) []string {
limits := []string{}
loc, ok := input.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
return limits
}
if loc.RateLimit.Connections.Limit > 0 {
limit := fmt.Sprintf("limit_conn %v %v;",
loc.RateLimit.Connections.Name, loc.RateLimit.Connections.Limit)
limits = append(limits, limit)
}
if loc.RateLimit.RPS.Limit > 0 {
limit := fmt.Sprintf("limit_req zone=%v burst=%v nodelay;",
loc.RateLimit.RPS.Name, loc.RateLimit.RPS.Burst)
limits = append(limits, limit)
}
if loc.RateLimit.RPM.Limit > 0 {
limit := fmt.Sprintf("limit_req zone=%v burst=%v nodelay;",
loc.RateLimit.RPM.Name, loc.RateLimit.RPM.Burst)
limits = append(limits, limit)
}
if loc.RateLimit.LimitRateAfter > 0 {
limit := fmt.Sprintf("limit_rate_after %vk;",
loc.RateLimit.LimitRateAfter)
limits = append(limits, limit)
}
if loc.RateLimit.LimitRate > 0 {
limit := fmt.Sprintf("limit_rate %vk;",
loc.RateLimit.LimitRate)
limits = append(limits, limit)
}
return limits
}
func isLocationInLocationList(location interface{}, rawLocationList string) bool {
loc, ok := location.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", location)
return false
}
locationList := strings.Split(rawLocationList, ",")
for _, locationListItem := range locationList {
locationListItem = strings.Trim(locationListItem, " ")
if locationListItem == "" {
continue
}
if strings.HasPrefix(loc.Path, locationListItem) {
return true
}
}
return false
}
func isLocationAllowed(input interface{}) bool {
loc, ok := input.(*ingress.Location)
if !ok {
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
return false
}
return loc.Denied == nil
}
var denyPathSlugMap = map[string]string{}
// buildDenyVariable returns a nginx variable for a location in a
// server to be used in the whitelist check
// This method uses a unique id generator library to reduce the
// size of the string to be used as a variable in nginx to avoid
// issue with the size of the variable bucket size directive
func buildDenyVariable(a interface{}) string {
l, ok := a.(string)
if !ok {
klog.Errorf("expected a 'string' type but %T was returned", a)
return ""
}
if _, ok := denyPathSlugMap[l]; !ok {
denyPathSlugMap[l] = randomString()
}
return fmt.Sprintf("$deny_%v", denyPathSlugMap[l])
}
func buildUpstreamName(loc interface{}) string {
location, ok := loc.(*ingress.Location)
if !ok {
klog.Errorf("expected a '*ingress.Location' type but %T was returned", loc)
return ""
}
upstreamName := location.Backend
return upstreamName
}
func buildNextUpstream(i, r interface{}) string {
nextUpstream, ok := i.(string)
if !ok {
klog.Errorf("expected a 'string' type but %T was returned", i)
return ""
}
retryNonIdempotent, ok := r.(bool)
if !ok {
klog.Errorf("expected a 'bool' type but %T was returned", i)
return ""
}
parts := strings.Split(nextUpstream, " ")
nextUpstreamCodes := make([]string, 0, len(parts))
for _, v := range parts {
if v != "" && v != nonIdempotent {
nextUpstreamCodes = append(nextUpstreamCodes, v)
}
if v == nonIdempotent {
retryNonIdempotent = true
}
}
if retryNonIdempotent {
nextUpstreamCodes = append(nextUpstreamCodes, nonIdempotent)
}
return strings.Join(nextUpstreamCodes, " ")
}
// refer to http://nginx.org/en/docs/syntax.html
// Nginx differentiates between size and offset
// offset directives support gigabytes in addition
var (
nginxSizeRegex = regexp.MustCompile(`^\d+[kKmM]?$`)
nginxOffsetRegex = regexp.MustCompile(`^\d+[kKmMgG]?$`)