ingress-nginx-helm/internal/ingress/controller/template/template.go

1757 lines
46 KiB
Go
Raw Normal View History

2016-02-22 00:13:08 +00:00
/*
Copyright 2015 The Kubernetes Authors.
2016-02-22 00:13:08 +00:00
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.
*/
2016-08-07 22:53:08 +00:00
package template
2016-02-22 00:13:08 +00:00
import (
"bytes"
"crypto/rand"
2020-12-04 12:40:42 +00:00
"crypto/sha1" // #nosec
"encoding/base64"
"encoding/hex"
2016-02-22 00:13:08 +00:00
"encoding/json"
"fmt"
"io"
"math/big"
2016-12-22 03:00:27 +00:00
"net"
"net/url"
"os"
"reflect"
2018-11-30 01:45:32 +00:00
"regexp"
"sort"
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
"strconv"
2016-05-25 21:04:34 +00:00
"strings"
2016-08-07 22:53:08 +00:00
text_template "text/template"
2016-02-22 00:13:08 +00:00
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
networkingv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/util/sets"
2020-08-08 23:31:02 +00:00
"k8s.io/klog/v2"
2019-08-13 18:04:31 +00:00
"k8s.io/ingress-nginx/internal/ingress/annotations/parser"
2017-11-07 22:02:12 +00:00
"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"
2016-02-22 00:13:08 +00:00
)
2016-05-25 21:04:34 +00:00
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
)
2016-02-22 00:13:08 +00:00
// 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
2016-08-07 22:53:08 +00:00
type Template struct {
tmpl *text_template.Template
bp *BufferPool
2016-08-07 22:53:08 +00:00
}
2022-12-29 22:09:29 +00:00
// NewTemplate returns a new Template instance or an
// error if the specified template file contains errors
2019-08-13 21:14:55 +00:00
func NewTemplate(file string) (*Template, error) {
data, err := os.ReadFile(file)
2016-08-07 22:53:08 +00:00
if err != nil {
return nil, fmt.Errorf("unexpected error reading template %s: %w", file, err)
2016-08-07 22:53:08 +00:00
}
tmpl, err := text_template.New("nginx.tmpl").Funcs(funcMap).Parse(string(data))
2016-07-28 21:35:36 +00:00
if err != nil {
2016-08-07 22:53:08 +00:00
return nil, err
2016-07-28 21:35:36 +00:00
}
2016-08-07 22:53:08 +00:00
return &Template{
tmpl: tmpl,
bp: NewBufferPool(defBufferSize),
2016-08-07 22:53:08 +00:00
}, 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':
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':
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
}
}
2016-08-07 22:53:08 +00:00
// 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)
2016-02-22 00:13:08 +00:00
outCmdBuf := t.bp.Get()
defer t.bp.Put(outCmdBuf)
2016-11-16 18:24:26 +00:00
2020-08-08 23:31:02 +00:00
if klog.V(3).Enabled() {
b, err := json.Marshal(*conf)
2016-02-22 00:13:08 +00:00
if err != nil {
2018-12-05 16:27:55 +00:00
klog.Errorf("unexpected error: %v", err)
2016-02-22 00:13:08 +00:00
}
2020-09-27 20:32:40 +00:00
klog.InfoS("NGINX", "configuration", string(b))
2016-02-22 00:13:08 +00:00
}
err := t.tmpl.Execute(tmplBuf, *conf)
if err != nil {
2016-11-16 18:24:26 +00:00
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
2016-02-22 00:13:08 +00:00
}
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,
"configForLua": configForLua,
"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:
2022-12-29 22:09:29 +00:00
//
// 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 ""
}
2019-11-04 18:41:26 +00:00
_, ok = s.([]*ingress.Server)
2018-04-08 20:37:13 +00:00
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
2018-04-08 20:37:13 +00:00
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"
2018-04-08 20:37:13 +00:00
}
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)
}
// configForLua returns some general configuration as Lua table represented as string
func configForLua(input interface{}) string {
all, ok := input.(config.TemplateConfig)
if !ok {
klog.Errorf("expected a 'config.TemplateConfig' type but %T was given", input)
return "{}"
}
return fmt.Sprintf(`{
use_forwarded_headers = %t,
use_proxy_protocol = %t,
is_ssl_passthrough_enabled = %t,
http_redirect_code = %v,
listen_ports = { ssl_proxy = "%v", https = "%v" },
2019-09-24 18:57:17 +00:00
hsts = %t,
hsts_max_age = %v,
hsts_include_subdomains = %t,
hsts_preload = %t,
2020-12-24 16:39:12 +00:00
global_throttle = {
memcached = {
host = "%v", port = %d, connect_timeout = %d, max_idle_timeout = %d, pool_size = %d,
},
status_code = %d,
}
2019-09-24 18:57:17 +00:00
}`,
all.Cfg.UseForwardedHeaders,
all.Cfg.UseProxyProtocol,
2019-09-24 18:57:17 +00:00
all.IsSSLPassthroughEnabled,
all.Cfg.HTTPRedirectCode,
all.ListenPorts.SSLProxy,
all.ListenPorts.HTTPS,
all.Cfg.HSTS,
all.Cfg.HSTSMaxAge,
all.Cfg.HSTSIncludeSubdomains,
all.Cfg.HSTSPreload,
2020-12-24 16:39:12 +00:00
all.Cfg.GlobalRateLimitMemcachedHost,
all.Cfg.GlobalRateLimitMemcachedPort,
all.Cfg.GlobalRateLimitMemcachedConnectTimeout,
all.Cfg.GlobalRateLimitMemcachedMaxIdleTimeout,
all.Cfg.GlobalRateLimitMemcachedPoolSize,
all.Cfg.GlobalRateLimitStatucCode,
2019-09-24 18:57:17 +00:00
)
}
// 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 "{}"
}
2020-12-24 16:39:12 +00:00
ignoredCIDRs, err := convertGoSliceIntoLuaTable(location.GlobalRateLimit.IgnoredCIDRs, false)
if err != nil {
klog.Errorf("failed to convert %v into Lua table: %q", location.GlobalRateLimit.IgnoredCIDRs, err)
ignoredCIDRs = "{}"
}
return fmt.Sprintf(`{
force_ssl_redirect = %t,
2019-09-24 03:40:47 +00:00
ssl_redirect = %t,
force_no_ssl_redirect = %t,
preserve_trailing_slash = %t,
use_port_in_redirects = %t,
2020-12-24 16:39:12 +00:00
global_throttle = { namespace = "%v", limit = %d, window_size = %d, key = %v, ignored_cidrs = %v },
2019-09-24 03:40:47 +00:00
}`,
location.Rewrite.ForceSSLRedirect,
location.Rewrite.SSLRedirect,
isLocationInLocationList(l, all.Cfg.NoTLSRedirectLocations),
location.Rewrite.PreserveTrailingSlash,
2019-09-24 03:40:47 +00:00
location.UsePortInRedirects,
2020-12-24 16:39:12 +00:00
location.GlobalRateLimit.Namespace,
location.GlobalRateLimit.Limit,
location.GlobalRateLimit.WindowSize,
parseComplexNginxVarIntoLuaTable(location.GlobalRateLimit.Key),
ignoredCIDRs,
2019-09-24 03:40:47 +00:00
)
}
2016-12-22 03:00:27 +00:00
// 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 {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a '[]net.IP' type but %T was returned", res)
return ""
}
no6, ok := disableIpv6.(bool)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a 'bool' type but %T was returned", disableIpv6)
return ""
}
2016-12-22 03:00:27 +00:00
if len(nss) == 0 {
return ""
}
r := []string{"resolver"}
for _, ns := range nss {
if ing_net.IsIPV6(ns) {
if no6 {
continue
}
2016-12-22 03:00:27 +00:00
r = append(r, fmt.Sprintf("[%v]", ns))
} else {
r = append(r, ns.String())
2016-12-22 03:00:27 +00:00
}
}
r = append(r, "valid=30s")
if no6 {
r = append(r, "ipv6=off")
}
2016-12-22 03:00:27 +00:00
return strings.Join(r, " ") + ";"
2016-12-22 03:00:27 +00:00
}
func needsRewrite(location *ingress.Location) bool {
if len(location.Rewrite.Target) > 0 && 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 {
2016-08-07 22:53:08 +00:00
location, ok := input.(*ingress.Location)
2016-05-25 21:04:34 +00:00
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
2016-05-25 21:04:34 +00:00
return slash
}
path := location.Path
if enforceRegex {
return fmt.Sprintf(`~* "^%s"`, path)
}
2020-04-22 16:24:57 +00:00
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
if location.PathType != nil && *location.PathType == networkingv1.PathTypeExact {
return fmt.Sprintf(`= %s`, path)
2020-04-22 16:24:57 +00:00
}
2016-05-25 21:04:34 +00:00
return path
}
func buildAuthLocation(input interface{}, globalExternalAuthURL string) string {
location, ok := input.(*ingress.Location)
if !ok {
2018-12-05 16:27:55 +00:00
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 {
2018-12-05 16:27:55 +00:00
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 {
res := []string{}
if len(headers) == 0 {
return res
}
for i, h := range headers {
res = append(res, fmt.Sprintf("ngx.var.authHeader%d = res.header['%s']", i, h))
}
return res
}
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))
}
2019-09-24 19:09:54 +00:00
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)
2017-11-08 20:58:57 +00:00
// 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 {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected an '[]*ingress.Backend' type but %T was returned", b)
return ""
}
2016-11-16 18:24:26 +00:00
location, ok := loc.(*ingress.Location)
2016-05-25 21:04:34 +00:00
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a '*ingress.Location' type but %T was returned", loc)
2016-05-25 21:04:34 +00:00
return ""
}
path := location.Path
2018-08-05 22:43:45 +00:00
proto := "http://"
2016-11-16 18:24:26 +00:00
proxyPass := "proxy_pass"
2018-08-05 22:43:45 +00:00
switch strings.ToUpper(location.BackendProtocol) {
case autoHTTPProtocol:
proto = "$scheme://"
case httpsProtocol:
2018-08-05 22:43:45 +00:00
proto = "https://"
case grpcProtocol:
2018-08-05 22:43:45 +00:00
proto = "grpc://"
proxyPass = "grpc_pass"
case grpcsProtocol:
2018-08-05 22:43:45 +00:00
proto = "grpcs://"
proxyPass = "grpc_pass"
case fcgiProtocol:
proto = ""
proxyPass = "fastcgi_pass"
2018-08-05 22:43:45 +00:00
}
upstreamName := "upstream_balancer"
2016-11-16 18:24:26 +00:00
for _, backend := range backends {
if backend.Name == location.Backend {
if backend.SSLPassthrough {
2018-08-05 22:43:45 +00:00
proto = "https://"
if location.BackendProtocol == grpcsProtocol {
2018-08-05 22:43:45 +00:00
proto = "grpcs://"
}
2016-11-16 18:24:26 +00:00
}
2016-11-16 18:24:26 +00:00
break
}
2016-06-01 18:47:37 +00:00
}
2016-11-16 18:24:26 +00:00
// 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
2018-08-05 22:43:45 +00:00
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
2016-05-25 21:04:34 +00:00
}
if len(location.Rewrite.Target) > 0 {
var xForwardedPrefix string
2019-03-11 16:23:14 +00:00
if len(location.XForwardedPrefix) > 0 {
xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix %q;\n", proxySetHeader(location), location.XForwardedPrefix)
2017-12-06 20:11:18 +00:00
}
return fmt.Sprintf(`
2018-12-13 18:02:05 +00:00
rewrite "(?i)%s" %s break;
%v%v %s%s;`, path, location.Rewrite.Target, xForwardedPrefix, proxyPass, proto, upstreamName)
2016-05-25 21:04:34 +00:00
}
// default proxy_pass
return defProxyPass
2016-05-25 21:04:34 +00:00
}
2017-11-07 16:36:51 +00:00
func filterRateLimits(input interface{}) []ratelimit.Config {
ratelimits := []ratelimit.Config{}
found := sets.Set[string]{}
2017-08-22 18:53:53 +00:00
2017-08-23 00:47:29 +00:00
servers, ok := input.([]*ingress.Server)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a '[]ratelimit.RateLimit' type but %T was returned", input)
2017-08-23 00:47:29 +00:00
return ratelimits
2017-08-21 19:36:31 +00:00
}
2017-08-23 00:47:29 +00:00
for _, server := range servers {
for _, loc := range server.Locations {
if loc.RateLimit.ID != "" && !found.Has(loc.RateLimit.ID) {
found.Insert(loc.RateLimit.ID)
2017-08-23 00:47:29 +00:00
ratelimits = append(ratelimits, loc.RateLimit)
}
}
}
return ratelimits
2017-08-21 19:36:31 +00:00
}
// buildRateLimitZones produces an array of limit_conn_zone in order to allow
2017-08-23 00:47:29 +00:00
// 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.
2017-08-21 19:36:31 +00:00
func buildRateLimitZones(input interface{}) []string {
zones := sets.Set[string]{}
2016-08-07 22:53:08 +00:00
servers, ok := input.([]*ingress.Server)
if !ok {
2018-12-05 16:27:55 +00:00
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;",
2017-08-23 00:47:29 +00:00
loc.RateLimit.ID,
loc.RateLimit.Connections.Name,
loc.RateLimit.Connections.SharedSize)
if !zones.Has(zone) {
zones.Insert(zone)
}
}
2017-08-02 03:24:48 +00:00
if loc.RateLimit.RPM.Limit > 0 {
zone := fmt.Sprintf("limit_req_zone $limit_%s zone=%v:%vm rate=%vr/m;",
2017-08-23 00:47:29 +00:00
loc.RateLimit.ID,
2017-08-02 03:24:48 +00:00
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;",
2017-08-23 00:47:29 +00:00
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
2017-08-02 03:24:48 +00:00
// Ingress rules. The order: connections by IP first, then RPS, and RPM last.
func buildRateLimit(input interface{}) []string {
limits := []string{}
2016-08-07 22:53:08 +00:00
loc, ok := input.(*ingress.Location)
if !ok {
2018-12-05 16:27:55 +00:00
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)
2017-08-02 03:24:48 +00:00
}
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 {
2018-12-05 16:27:55 +00:00
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 {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected an '*ingress.Location' type but %T was returned", input)
return false
}
return loc.Denied == nil
}
2017-06-02 03:30:22 +00:00
var denyPathSlugMap = map[string]string{}
2017-06-02 03:30:22 +00:00
// 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 {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a 'string' type but %T was returned", a)
return ""
}
2017-06-02 03:30:22 +00:00
if _, ok := denyPathSlugMap[l]; !ok {
denyPathSlugMap[l] = randomString()
2017-06-02 03:30:22 +00:00
}
return fmt.Sprintf("$deny_%v", denyPathSlugMap[l])
}
2018-10-09 22:36:10 +00:00
func buildUpstreamName(loc interface{}) string {
location, ok := loc.(*ingress.Location)
if !ok {
2018-12-05 16:27:55 +00:00
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 {
2018-12-05 16:27:55 +00:00
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, " ")
}
2017-08-20 23:39:58 +00:00
2018-12-02 18:10:36 +00:00
// 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]?$`)
)
2018-11-30 01:45:32 +00:00
// isValidByteSize validates size units valid in nginx
// http://nginx.org/en/docs/syntax.html
2018-12-02 18:10:36 +00:00
func isValidByteSize(input interface{}, isOffset bool) bool {
s, ok := input.(string)
if !ok {
2018-12-05 16:28:28 +00:00
klog.Errorf("expected an 'string' type but %T was returned", input)
return false
}
2018-11-30 01:45:32 +00:00
s = strings.TrimSpace(s)
if s == "" {
2018-12-05 16:28:28 +00:00
klog.V(2).Info("empty byte size, hence it will not be set")
return false
}
2018-12-02 18:10:36 +00:00
if isOffset {
return nginxOffsetRegex.MatchString(s)
}
return nginxSizeRegex.MatchString(s)
}
type ingressInformation struct {
Namespace string
2020-12-11 15:27:15 +00:00
Path string
Rule string
Service string
ServicePort string
Annotations map[string]string
}
func (info *ingressInformation) Equal(other *ingressInformation) bool {
if info.Namespace != other.Namespace {
return false
}
if info.Rule != other.Rule {
return false
}
if info.Service != other.Service {
return false
}
if info.ServicePort != other.ServicePort {
return false
}
if !reflect.DeepEqual(info.Annotations, other.Annotations) {
return false
}
return true
}
func getIngressInformation(i, h, p interface{}) *ingressInformation {
ing, ok := i.(*ingress.Ingress)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected an '*ingress.Ingress' type but %T was returned", i)
return &ingressInformation{}
}
hostname, ok := h.(string)
if !ok {
klog.Errorf("expected a 'string' type but %T was returned", h)
return &ingressInformation{}
}
2020-12-11 15:27:15 +00:00
ingressPath, ok := p.(string)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a 'string' type but %T was returned", p)
return &ingressInformation{}
}
if ing == nil {
return &ingressInformation{}
}
info := &ingressInformation{
Namespace: ing.GetNamespace(),
Rule: ing.GetName(),
Annotations: ing.Annotations,
2020-12-11 15:27:15 +00:00
Path: ingressPath,
}
if ingressPath == "" {
ingressPath = "/"
info.Path = "/"
}
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
if ing.Spec.DefaultBackend != nil && ing.Spec.DefaultBackend.Service != nil {
info.Service = ing.Spec.DefaultBackend.Service.Name
if ing.Spec.DefaultBackend.Service.Port.Number > 0 {
info.ServicePort = strconv.Itoa(int(ing.Spec.DefaultBackend.Service.Port.Number))
} else {
info.ServicePort = ing.Spec.DefaultBackend.Service.Port.Name
}
}
for _, rule := range ing.Spec.Rules {
if rule.HTTP == nil {
continue
}
if hostname != "_" && rule.Host == "" {
continue
}
host := "_"
if rule.Host != "" {
host = rule.Host
}
if hostname != host {
continue
}
for _, rPath := range rule.HTTP.Paths {
2020-12-11 15:27:15 +00:00
if ingressPath != rPath.Path {
continue
}
Improving e2e tests for non-service backends #7544 (#7545) * Adding test cases for backend with nil service Signed-off-by: Marcos <marcosnery.comp@gmail.com> Co-authored-by: Renato Araujo <renatobritto@protonmail.com> Co-authored-by: André Goretti <andremotta96@gmail.com> Co-authored-by: Kalebe Lopes <calbkalebe@gmail.com> * Add e2e test for backend nil service and add nil safeguard (#7344) Co-authored-by: Renato Araujo <renatobritto@protonmail.com> Co-authored-by: André Goretti <andremotta96@gmail.com> Co-authored-by: Kalebe Lopes <calbkalebe@gmail.com> * changing portuguese names to english in order to maintain the pattern * updating boilerplate header * adding second test case to also test valid path Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * Updating boilerplate * fixing boilerplate Signed-off-by: MarcosN <marcosnery.comp@gmail.com> Co-authored-by: André Goretti <andremotta96@gmail.com> Co-authored-by: Gabriel Albino <enggabrielalbino@gmail.com> * Improving template test for cases where a nil backend service is included Signed-off-by: MarcosN <marcosnery.comp@gmail.com> Co-authored-by: André Goretti <andremotta96@gmail.com> Co-authored-by: Gabriel Albino <enggabrielalbino@gmail.com> Co-authored-by: Renato Araujo <renatobritto@protonmail.com> Co-authored-by: André Goretti <andremotta96@gmail.com> Co-authored-by: Kalebe Lopes <calbkalebe@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> Co-authored-by: Gabriel Albino <enggabrielalbino@gmail.com>
2021-08-26 00:45:23 +00:00
if rPath.Backend.Service == nil {
continue
}
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
if info.Service != "" && rPath.Backend.Service.Name == "" {
// empty rule. Only contains a Path and PathType
return info
}
Release v1 (#7470) * Drop v1beta1 from ingress nginx (#7156) * Drop v1beta1 from ingress nginx Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix intorstr logic in controller Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * fixing admission Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * more intorstr fixing * correct template rendering Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix e2e tests for v1 api Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix gofmt errors * This is finally working...almost there... Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Re-add removed validation of AdmissionReview * Prepare for v1.0.0-alpha.1 release Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Update changelog and matrix table for v1.0.0-alpha.1 (#7274) Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * add docs for syslog feature (#7219) * Fix link to e2e-tests.md in developer-guide (#7201) * Use ENV expansion for namespace in args (#7146) Update the DaemonSet namespace references to use the `POD_NAMESPACE` environment variable in the same way that the Deployment does. * chart: using Helm builtin capabilities check (#7190) Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> * Update proper default value for HTTP2MaxConcurrentStreams in Docs (#6944) It should be 128 as documented in https://github.com/kubernetes/ingress-nginx/blob/master/internal/ingress/controller/config/config.go#L780 * Fix MaxWorkerOpenFiles calculation on high cores nodes (#7107) * Fix MaxWorkerOpenFiles calculation on high cores nodes * Add e2e test for rlimit_nofile * Fix doc for max-worker-open-files * ingress/tcp: add additional error logging on failed (#7208) * Add file containing stable release (#7313) * Handle named (non-numeric) ports correctly (#7311) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Updated v1beta1 to v1 as its deprecated (#7308) * remove mercurial from build (#7031) * Retry to download maxmind DB if it fails (#7242) * Retry to download maxmind DB if it fails. Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Add retries count arg, move retry logic into DownloadGeoLite2DB function Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Reorder parameters in DownloadGeoLite2DB Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Remove hardcoded value Signed-off-by: Sergey Shakuto <sshakuto@infoblox.com> * Release v1.0.0-alpha.1 * Add changelog for v1.0.0-alpha.2 * controller: ignore non-service backends (#7332) * controller: ignore non-service backends Signed-off-by: Carlos Panato <ctadeu@gmail.com> * update per feedback Signed-off-by: Carlos Panato <ctadeu@gmail.com> * fix: allow scope/tcp/udp configmap namespace to altered (#7161) * Lower webhook timeout for digital ocean (#7319) * Lower webhook timeout for digital ocean * Set Digital Ocean value controller.admissionWebhooks.timeoutSeconds to 29 * update OWNERS and aliases files (#7365) (#7366) Signed-off-by: Carlos Panato <ctadeu@gmail.com> * Downgrade Lua modules for s390x (#7355) Downgrade Lua modules to last known working version. * Fix IngressClass logic for newer releases (#7341) * Fix IngressClass logic for newer releases Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Change e2e tests for the new IngressClass presence * Fix chart and admission tests Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix helm chart test Signed-off-by: Ricardo Pchevuzinske Katz <ricardo.katz@gmail.com> * Fix reviews * Remove ingressclass code from admission * update tag to v1.0.0-beta.1 * update readme and changelog for v1.0.0-beta.1 * Release v1.0.0-beta.1 - helm and manifests (#7422) * Change the order of annotation just to trigger a new helm release (#7425) * [cherry-pick] Add dev-v1 branch into helm releaser (#7428) * Add dev-v1 branch into helm releaser (#7424) * chore: add link for artifacthub.io/prerelease annotations Signed-off-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Ricardo Katz <rikatz@users.noreply.github.com> * k8s job ci pipeline for dev-v1 br v1.22.0 (#7453) * k8s job ci pipeline for dev-v1 br v1.22.0 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * k8s job ci pipeline for dev-v1 br v1.21.2 Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * remove v1.21.1 version Signed-off-by: Neha Lohia <nehapithadiya444@gmail.com> * Add controller.watchIngressWithoutClass config option (#7459) Signed-off-by: Akshit Grover <akshit.grover2016@gmail.com> * Release new helm chart with certgen fixed (#7478) * Update go version, modules and remove ioutil * Release new helm chart with certgen fixed * changed appversion, chartversion, TAG, image (#7490) * Fix CI conflict * Fix CI conflict * Fix build.sh from rebase process * Fix controller_test post rebase Co-authored-by: Tianhao Guo <rggth09@gmail.com> Co-authored-by: Ray <61553+rctay@users.noreply.github.com> Co-authored-by: Bill Cassidy <cassid4@gmail.com> Co-authored-by: Jintao Zhang <tao12345666333@163.com> Co-authored-by: Sathish Ramani <rsathishx87@gmail.com> Co-authored-by: Mansur Marvanov <nanorobocop@gmail.com> Co-authored-by: Matt1360 <568198+Matt1360@users.noreply.github.com> Co-authored-by: Carlos Tadeu Panato Junior <ctadeu@gmail.com> Co-authored-by: Kundan Kumar <kundan.kumar@india.nec.com> Co-authored-by: Tom Hayward <thayward@infoblox.com> Co-authored-by: Sergey Shakuto <sshakuto@infoblox.com> Co-authored-by: Tore <tore.lonoy@gmail.com> Co-authored-by: Bouke Versteegh <info@boukeversteegh.nl> Co-authored-by: Shahid <shahid@us.ibm.com> Co-authored-by: James Strong <strong.james.e@gmail.com> Co-authored-by: Long Wu Yuan <longwuyuan@gmail.com> Co-authored-by: Jintao Zhang <zhangjintao9020@gmail.com> Co-authored-by: Neha Lohia <nehapithadiya444@gmail.com> Co-authored-by: Akshit Grover <akshit.grover2016@gmail.com>
2021-08-21 20:42:00 +00:00
info.Service = rPath.Backend.Service.Name
if rPath.Backend.Service.Port.Number > 0 {
info.ServicePort = strconv.Itoa(int(rPath.Backend.Service.Port.Number))
} else {
info.ServicePort = rPath.Backend.Service.Port.Name
}
return info
}
}
return info
}
2017-09-07 21:11:23 +00:00
func buildForwardedFor(input interface{}) string {
s, ok := input.(string)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a 'string' type but %T was returned", input)
return ""
2017-09-07 21:11:23 +00:00
}
ffh := strings.ReplaceAll(s, "-", "_")
2017-09-07 21:11:23 +00:00
ffh = strings.ToLower(ffh)
return fmt.Sprintf("$http_%v", ffh)
}
2017-09-17 18:03:05 +00:00
func buildAuthSignURL(authSignURL, authRedirectParam string) string {
u, err := url.Parse(authSignURL)
if err != nil {
klog.Errorf("error parsing authSignURL: %v", err)
return ""
}
q := u.Query()
if authRedirectParam == "" {
authRedirectParam = defaultGlobalAuthRedirectParam
}
if len(q) == 0 {
return fmt.Sprintf("%v?%v=$pass_access_scheme://$http_host$escaped_request_uri", authSignURL, authRedirectParam)
}
if q.Get(authRedirectParam) != "" {
return authSignURL
}
return fmt.Sprintf("%v&%v=$pass_access_scheme://$http_host$escaped_request_uri", authSignURL, authRedirectParam)
}
func buildAuthSignURLLocation(location, authSignURL string) string {
2020-12-04 12:40:42 +00:00
hasher := sha1.New() // #nosec
hasher.Write([]byte(location))
hasher.Write([]byte(authSignURL))
return "@" + hex.EncodeToString(hasher.Sum(nil))
}
2018-01-07 15:07:33 +00:00
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randomString() string {
b := make([]rune, 32)
for i := range b {
idx, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
if err != nil {
klog.Errorf("unexpected error generating random index: %v", err)
return ""
}
b[i] = letters[idx.Int64()]
2018-01-07 15:07:33 +00:00
}
return string(b)
2018-01-07 15:07:33 +00:00
}
func buildOpentelemetry(c, s interface{}) string {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return ""
}
servers, ok := s.([]*ingress.Server)
if !ok {
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
return ""
}
if !shouldLoadOpentelemetryModule(cfg, servers) {
return ""
}
buf := bytes.NewBufferString("")
buf.WriteString("\r\n")
if cfg.OpentelemetryOperationName != "" {
fmt.Fprintf(buf, "opentelemetry_operation_name \"%s\";\n", cfg.OpentelemetryOperationName)
}
return buf.String()
}
2018-05-17 12:35:11 +00:00
func proxySetHeader(loc interface{}) string {
location, ok := loc.(*ingress.Location)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a '*ingress.Location' type but %T was returned", loc)
2018-05-17 12:35:11 +00:00
return "proxy_set_header"
}
if location.BackendProtocol == grpcProtocol || location.BackendProtocol == grpcsProtocol {
2018-05-17 12:35:11 +00:00
return "grpc_set_header"
}
return "proxy_set_header"
}
// buildCustomErrorDeps is a utility function returning a struct wrapper with
// the data required to build the 'CUSTOM_ERRORS' template
func buildCustomErrorDeps(upstreamName string, errorCodes []int, enableMetrics, modsecurityEnabled bool) interface{} {
return struct {
UpstreamName string
ErrorCodes []int
EnableMetrics bool
ModsecurityEnabled bool
}{
UpstreamName: upstreamName,
ErrorCodes: errorCodes,
EnableMetrics: enableMetrics,
ModsecurityEnabled: modsecurityEnabled,
}
}
type errorLocation struct {
UpstreamName string
Codes []int
}
// buildCustomErrorLocationsPerServer is a utility function which will collect all
// custom error codes for all locations of a server block, deduplicates them,
// and returns a set which is unique by default-upstream and error code. It returns an array
// of errorLocations, each of which contain the upstream name and a list of
// error codes for that given upstream, so that sufficiently unique
// @custom error location blocks can be created in the template
2019-12-17 15:06:17 +00:00
func buildCustomErrorLocationsPerServer(input interface{}) []errorLocation {
server, ok := input.(*ingress.Server)
if !ok {
2018-12-05 16:27:55 +00:00
klog.Errorf("expected a '*ingress.Server' type but %T was returned", input)
return nil
}
codesMap := make(map[string]map[int]bool)
for _, loc := range server.Locations {
backendUpstream := loc.DefaultBackendUpstreamName
var dedupedCodes map[int]bool
if existingMap, ok := codesMap[backendUpstream]; ok {
dedupedCodes = existingMap
} else {
dedupedCodes = make(map[int]bool)
}
for _, code := range loc.CustomHTTPErrors {
dedupedCodes[code] = true
}
codesMap[backendUpstream] = dedupedCodes
}
errorLocations := []errorLocation{}
for upstream, dedupedCodes := range codesMap {
codesForUpstream := []int{}
for code := range dedupedCodes {
codesForUpstream = append(codesForUpstream, code)
}
sort.Ints(codesForUpstream)
errorLocations = append(errorLocations, errorLocation{
UpstreamName: upstream,
Codes: codesForUpstream,
})
}
sort.Slice(errorLocations, func(i, j int) bool {
return errorLocations[i].UpstreamName < errorLocations[j].UpstreamName
})
return errorLocations
}
func opentelemetryPropagateContext(location *ingress.Location) string {
if location == nil {
return ""
}
return "opentelemetry_propagate;"
}
// shouldLoadModSecurityModule determines whether or not the ModSecurity module needs to be loaded.
// First, it checks if `enable-modsecurity` is set in the ConfigMap. If it is not, it iterates over all locations to
// check if ModSecurity is enabled by the annotation `nginx.ingress.kubernetes.io/enable-modsecurity`.
func shouldLoadModSecurityModule(c, s interface{}) bool {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return false
}
servers, ok := s.([]*ingress.Server)
if !ok {
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
return false
}
// Determine if ModSecurity is enabled globally.
if cfg.EnableModsecurity {
return true
}
// If ModSecurity is not enabled globally, check if any location has it enabled via annotation.
for _, server := range servers {
for _, location := range server.Locations {
if location.ModSecurity.Enable {
return true
}
}
}
// Not enabled globally nor via annotation on a location, no need to load the module.
return false
}
2019-08-13 18:04:31 +00:00
func buildHTTPListener(t, s interface{}) string {
2019-08-13 18:04:31 +00:00
var out []string
tc, ok := t.(config.TemplateConfig)
if !ok {
klog.Errorf("expected a 'config.TemplateConfig' type but %T was returned", t)
return ""
}
hostname, ok := s.(string)
if !ok {
klog.Errorf("expected a 'string' type but %T was returned", s)
return ""
}
addrV4 := []string{""}
if len(tc.Cfg.BindAddressIpv4) > 0 {
addrV4 = tc.Cfg.BindAddressIpv4
}
co := commonListenOptions(&tc, hostname)
2019-08-13 18:04:31 +00:00
out = append(out, httpListener(addrV4, co, &tc)...)
2019-08-13 18:04:31 +00:00
if !tc.IsIPV6Enabled {
return strings.Join(out, "\n")
}
addrV6 := []string{"[::]"}
if len(tc.Cfg.BindAddressIpv6) > 0 {
addrV6 = tc.Cfg.BindAddressIpv6
}
out = append(out, httpListener(addrV6, co, &tc)...)
2019-08-13 18:04:31 +00:00
return strings.Join(out, "\n")
}
func buildHTTPSListener(t, s interface{}) string {
2019-08-13 18:04:31 +00:00
var out []string
tc, ok := t.(config.TemplateConfig)
if !ok {
klog.Errorf("expected a 'config.TemplateConfig' type but %T was returned", t)
return ""
}
hostname, ok := s.(string)
if !ok {
klog.Errorf("expected a 'string' type but %T was returned", s)
return ""
}
co := commonListenOptions(&tc, hostname)
2019-08-13 18:04:31 +00:00
addrV4 := []string{""}
if len(tc.Cfg.BindAddressIpv4) > 0 {
addrV4 = tc.Cfg.BindAddressIpv4
}
out = append(out, httpsListener(addrV4, co, &tc)...)
2019-08-13 18:04:31 +00:00
if !tc.IsIPV6Enabled {
return strings.Join(out, "\n")
}
addrV6 := []string{"[::]"}
if len(tc.Cfg.BindAddressIpv6) > 0 {
addrV6 = tc.Cfg.BindAddressIpv6
}
out = append(out, httpsListener(addrV6, co, &tc)...)
2019-08-13 18:04:31 +00:00
return strings.Join(out, "\n")
}
func commonListenOptions(template *config.TemplateConfig, hostname string) string {
2019-08-13 18:04:31 +00:00
var out []string
if template.Cfg.UseProxyProtocol {
out = append(out, "proxy_protocol")
}
if hostname != "_" {
return strings.Join(out, " ")
}
// setup options that are valid only once per port
out = append(out, "default_server")
if template.Cfg.ReusePort {
out = append(out, "reuseport")
}
out = append(out, fmt.Sprintf("backlog=%v", template.BacklogSize))
return strings.Join(out, " ")
}
func httpListener(addresses []string, co string, tc *config.TemplateConfig) []string {
2019-08-13 18:04:31 +00:00
out := make([]string, 0)
for _, address := range addresses {
lo := []string{"listen"}
2019-08-13 18:04:31 +00:00
if address == "" {
lo = append(lo, fmt.Sprintf("%v", tc.ListenPorts.HTTP))
2019-08-13 18:04:31 +00:00
} else {
lo = append(lo, fmt.Sprintf("%v:%v", address, tc.ListenPorts.HTTP))
2019-08-13 18:04:31 +00:00
}
lo = append(lo, co, ";")
out = append(out, strings.Join(lo, " "))
2019-08-13 18:04:31 +00:00
}
return out
}
func httpsListener(addresses []string, co string, tc *config.TemplateConfig) []string {
2019-08-13 18:04:31 +00:00
out := make([]string, 0)
for _, address := range addresses {
lo := []string{"listen"}
2019-08-13 18:04:31 +00:00
if tc.IsSSLPassthroughEnabled {
if address == "" {
lo = append(lo, fmt.Sprintf("%v", tc.ListenPorts.SSLProxy))
2019-08-13 18:04:31 +00:00
} else {
lo = append(lo, fmt.Sprintf("%v:%v", address, tc.ListenPorts.SSLProxy))
2019-08-13 18:04:31 +00:00
}
if !strings.Contains(co, "proxy_protocol") {
lo = append(lo, "proxy_protocol")
}
2019-08-13 18:04:31 +00:00
} else {
if address == "" {
lo = append(lo, fmt.Sprintf("%v", tc.ListenPorts.HTTPS))
2019-08-13 18:04:31 +00:00
} else {
lo = append(lo, fmt.Sprintf("%v:%v", address, tc.ListenPorts.HTTPS))
2019-08-13 18:04:31 +00:00
}
}
lo = append(lo, co, "ssl")
2019-08-13 18:04:31 +00:00
if tc.Cfg.UseHTTP2 {
lo = append(lo, "http2")
2019-08-13 18:04:31 +00:00
}
lo = append(lo, ";")
out = append(out, strings.Join(lo, " "))
2019-08-13 18:04:31 +00:00
}
return out
}
func buildOpentelemetryForLocation(isOTEnabled, isOTTrustSet bool, location *ingress.Location) string {
isOTEnabledInLoc := location.Opentelemetry.Enabled
isOTSetInLoc := location.Opentelemetry.Set
if isOTEnabled {
if isOTSetInLoc && !isOTEnabledInLoc {
return "opentelemetry off;"
}
} else if !isOTSetInLoc || !isOTEnabledInLoc {
return ""
}
opc := opentelemetryPropagateContext(location)
if opc != "" {
opc = fmt.Sprintf("opentelemetry on;\n%v", opc)
}
if location.Opentelemetry.OperationName != "" {
opc += "\nopentelemetry_operation_name " + location.Opentelemetry.OperationName + ";"
}
if (!isOTTrustSet && !location.Opentelemetry.TrustSet) ||
(location.Opentelemetry.TrustSet && !location.Opentelemetry.TrustEnabled) {
opc += "\nopentelemetry_trust_incoming_spans off;"
} else {
opc += "\nopentelemetry_trust_incoming_spans on;"
}
return opc
}
// shouldLoadOpentelemetryModule determines whether or not the Opentelemetry module needs to be loaded.
// It checks if `enable-opentelemetry` is set in the ConfigMap.
func shouldLoadOpentelemetryModule(c, s interface{}) bool {
cfg, ok := c.(config.Configuration)
if !ok {
klog.Errorf("expected a 'config.Configuration' type but %T was returned", c)
return false
}
servers, ok := s.([]*ingress.Server)
if !ok {
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
return false
}
if cfg.EnableOpentelemetry {
return true
}
for _, server := range servers {
for _, location := range server.Locations {
if location.Opentelemetry.Enabled {
return true
}
}
}
return false
}
//nolint:gocritic // Ignore passing cfg by pointer error
func buildModSecurityForLocation(cfg config.Configuration, location *ingress.Location) string {
isMSEnabledInLoc := location.ModSecurity.Enable
isMSEnableSetInLoc := location.ModSecurity.EnableSet
isMSEnabled := cfg.EnableModsecurity
if !isMSEnabled && !isMSEnabledInLoc {
return ""
}
if isMSEnableSetInLoc && !isMSEnabledInLoc {
return "modsecurity off;"
}
var buffer bytes.Buffer
if !isMSEnabled {
buffer.WriteString(`modsecurity on;
`)
}
if location.ModSecurity.Snippet != "" {
buffer.WriteString(fmt.Sprintf(`modsecurity_rules '
%v
';
`, location.ModSecurity.Snippet))
}
if location.ModSecurity.TransactionID != "" {
buffer.WriteString(fmt.Sprintf(`modsecurity_transaction_id "%v";
`, location.ModSecurity.TransactionID))
}
Disable default modsecurity_rules_file if modsecurity-snippet is specified (#8021) * Disabled default modsecurity_rules_file if modsecurity-snippet is specifed The default modsecurity_rules_file overwrites the ModSecurity-snippet if it is specified with custom config settings like "SecRuleEngine On". This will not let Modsecurity be in blocking mode even if "SecRuleEngine On" is specified in the ModSecurity-snippet configuration * Remove unnecessary comments Only have the default Modsecurity conf settings in case Modsecurity configuration snippet is not present and remove unnecessary comments * Fixed modsecurity default file only if Modsecurity snippet present Fixed if condition Modsecurity snippet present have modsecurity default config file * Added e2e test to disabling modsecurity conf Added e2e in case modsecurity-snippet enabled to disable settings in default modsecurity.conf * Validate writing to a different location Validate also modsecurity to write to a different location instead of the default directory * Fixed the formatting * Fixed if empty ModsecuritySnippet * Fixed ModsecuritySnippet condition * Fixed the condition also in ingress controller template * Removed the default config condition in ingress controller template * Fixed the default config condition in ingress controller template * Fixed pull-ingress-nginx-test * Revert "Fixed the default config condition in ingress controller template" This reverts commit 9d38eca40fe615a4c756500ca57b05634240edde. * Revert template_test * Adjusted the formating %v
2021-12-23 11:34:38 +00:00
if !isMSEnabled && location.ModSecurity.Snippet == "" {
buffer.WriteString(`modsecurity_rules_file /etc/nginx/modsecurity/modsecurity.conf;
`)
}
if !cfg.EnableOWASPCoreRules && location.ModSecurity.OWASPRules {
buffer.WriteString(`modsecurity_rules_file /etc/nginx/owasp-modsecurity-crs/nginx-modsecurity.conf;
`)
}
return buffer.String()
}
2020-02-05 02:06:07 +00:00
func buildMirrorLocations(locs []*ingress.Location) string {
var buffer bytes.Buffer
mapped := sets.Set[string]{}
2020-02-05 02:06:07 +00:00
for _, loc := range locs {
if loc.Mirror.Source == "" || loc.Mirror.Target == "" || loc.Mirror.Host == "" {
2020-02-05 02:06:07 +00:00
continue
}
if mapped.Has(loc.Mirror.Source) {
continue
}
mapped.Insert(loc.Mirror.Source)
buffer.WriteString(fmt.Sprintf(`location = %v {
internal;
proxy_set_header Host "%v";
proxy_pass "%v";
2020-02-05 02:06:07 +00:00
}
`, loc.Mirror.Source, loc.Mirror.Host, loc.Mirror.Target))
2020-02-05 02:06:07 +00:00
}
return buffer.String()
}
2020-09-08 23:47:01 +00:00
// shouldLoadAuthDigestModule determines whether or not the ngx_http_auth_digest_module module needs to be loaded.
func shouldLoadAuthDigestModule(s interface{}) bool {
servers, ok := s.([]*ingress.Server)
if !ok {
klog.Errorf("expected an '[]*ingress.Server' type but %T was returned", s)
return false
}
for _, server := range servers {
for _, location := range server.Locations {
if !location.BasicDigestAuth.Secured {
continue
}
if location.BasicDigestAuth.Type == "digest" {
return true
}
}
}
return false
}
// buildServerName ensures wildcard hostnames are valid
func buildServerName(hostname string) string {
if !strings.HasPrefix(hostname, "*") {
return hostname
}
hostname = strings.Replace(hostname, "*.", "", 1)
parts := strings.Split(hostname, ".")
return `~^(?<subdomain>[\w-]+)\.` + strings.Join(parts, "\\.") + `$`
}
2020-12-24 16:39:12 +00:00
// parseComplexNginxVarIntoLuaTable parses things like "$my${complex}ngx\$var" into
2020-12-24 16:39:12 +00:00
// [["$var", "complex", "my", "ngx"]]. In other words, 2nd and 3rd elements
// in the result are actual NGINX variable names, whereas first and 4th elements
// are string literals.
func parseComplexNginxVarIntoLuaTable(ngxVar string) string {
r := regexp.MustCompile(`(\\\$[0-9a-zA-Z_]+)|\$\{([0-9a-zA-Z_]+)\}|\$([0-9a-zA-Z_]+)|(\$|[^$\\]+)`)
matches := r.FindAllStringSubmatch(ngxVar, -1)
components := make([][]string, len(matches))
for i, match := range matches {
components[i] = match[1:]
}
luaTable, err := convertGoSliceIntoLuaTable(components, true)
if err != nil {
klog.Errorf("unexpected error: %v", err)
luaTable = "{}"
}
return luaTable
}
func convertGoSliceIntoLuaTable(goSliceInterface interface{}, emptyStringAsNil bool) (string, error) {
goSlice := reflect.ValueOf(goSliceInterface)
kind := goSlice.Kind()
switch kind {
case reflect.String:
if emptyStringAsNil && goSlice.Interface().(string) == "" {
2020-12-24 16:39:12 +00:00
return "nil", nil
}
return fmt.Sprintf(`"%v"`, goSlice.Interface()), nil
case reflect.Int, reflect.Bool:
return fmt.Sprintf(`%v`, goSlice.Interface()), nil
case reflect.Slice, reflect.Array:
luaTable := "{ "
for i := 0; i < goSlice.Len(); i++ {
luaEl, err := convertGoSliceIntoLuaTable(goSlice.Index(i).Interface(), emptyStringAsNil)
if err != nil {
return "", err
}
luaTable = luaTable + luaEl + ", "
}
luaTable += "}"
return luaTable, nil
default:
return "", fmt.Errorf("could not process type: %s", kind)
}
}
Support cors-allow-origin with multiple origins (#7614) * Add Initial support for multiple cors origins in nginx - bump cluster version for `make dev-env` - add buildOriginRegex function in nginx.tmpl - add e2e 4 e2e tests for cors.go - refers to feature request #5496 * add tests + use search to identify '*' origin * add tests + use search to identify '*' origin Signed-off-by: Christopher Larivière <lariviere.c@gmail.com> * fix "should enable cors test" looking at improper values * Modify tests and add some logic for origin validation - add origin validation in cors ingress annotations - add extra tests to validate regex - properly escape regex using "QuoteMeta" - fix some copy/paste errors * add TrimSpace and length validation before adding a new origin * modify documentation for cors and remove dangling comment * add support for optional port mapping on origin * support single-level wildcard subdomains + tests * Remove automatic `*` fonctionality from incorrect origins - use []string instead of basic string to avoid reparsing in template.go - fix typo in docs - modify template to properly enable only if the whole block is enabled - modify cors parsing - test properly by validating that the value returned is the proper origin - update unit tests and annotation tests * Re-add `*` when no cors origins are supplied + fix tests - fix e2e tests to allow for `*` - re-add `*` to cors parsing if trimmed cors-allow-origin is empty (supplied but empty) and if it wasn't supplied at all. * remove unecessary logic for building cors origin + remove comments - add some edge cases in e2e tests - rework logic for building cors origin there was no need for logic in template.go for buildCorsOriginRegex if there is a `*` it ill be short-circuited by first if. if it's a wildcard domain or any domain (without a wildcard), it MUST match the main/cors.go regex format. if there's a star in a wildcard domain, it must be replaced with `[A-Za-z0-9]+` * add missing check in e2e tests
2021-11-02 19:31:42 +00:00
func buildOriginRegex(origin string) string {
origin = regexp.QuoteMeta(origin)
origin = strings.Replace(origin, "\\*", `[A-Za-z0-9\-]+`, 1)
Support cors-allow-origin with multiple origins (#7614) * Add Initial support for multiple cors origins in nginx - bump cluster version for `make dev-env` - add buildOriginRegex function in nginx.tmpl - add e2e 4 e2e tests for cors.go - refers to feature request #5496 * add tests + use search to identify '*' origin * add tests + use search to identify '*' origin Signed-off-by: Christopher Larivière <lariviere.c@gmail.com> * fix "should enable cors test" looking at improper values * Modify tests and add some logic for origin validation - add origin validation in cors ingress annotations - add extra tests to validate regex - properly escape regex using "QuoteMeta" - fix some copy/paste errors * add TrimSpace and length validation before adding a new origin * modify documentation for cors and remove dangling comment * add support for optional port mapping on origin * support single-level wildcard subdomains + tests * Remove automatic `*` fonctionality from incorrect origins - use []string instead of basic string to avoid reparsing in template.go - fix typo in docs - modify template to properly enable only if the whole block is enabled - modify cors parsing - test properly by validating that the value returned is the proper origin - update unit tests and annotation tests * Re-add `*` when no cors origins are supplied + fix tests - fix e2e tests to allow for `*` - re-add `*` to cors parsing if trimmed cors-allow-origin is empty (supplied but empty) and if it wasn't supplied at all. * remove unecessary logic for building cors origin + remove comments - add some edge cases in e2e tests - rework logic for building cors origin there was no need for logic in template.go for buildCorsOriginRegex if there is a `*` it ill be short-circuited by first if. if it's a wildcard domain or any domain (without a wildcard), it MUST match the main/cors.go regex format. if there's a star in a wildcard domain, it must be replaced with `[A-Za-z0-9]+` * add missing check in e2e tests
2021-11-02 19:31:42 +00:00
return fmt.Sprintf("(%s)", origin)
}
func buildCorsOriginRegex(corsOrigins []string) string {
if len(corsOrigins) == 1 && corsOrigins[0] == "*" {
return "set $http_origin *;\nset $cors 'true';"
}
originsRegex := "if ($http_origin ~* ("
Support cors-allow-origin with multiple origins (#7614) * Add Initial support for multiple cors origins in nginx - bump cluster version for `make dev-env` - add buildOriginRegex function in nginx.tmpl - add e2e 4 e2e tests for cors.go - refers to feature request #5496 * add tests + use search to identify '*' origin * add tests + use search to identify '*' origin Signed-off-by: Christopher Larivière <lariviere.c@gmail.com> * fix "should enable cors test" looking at improper values * Modify tests and add some logic for origin validation - add origin validation in cors ingress annotations - add extra tests to validate regex - properly escape regex using "QuoteMeta" - fix some copy/paste errors * add TrimSpace and length validation before adding a new origin * modify documentation for cors and remove dangling comment * add support for optional port mapping on origin * support single-level wildcard subdomains + tests * Remove automatic `*` fonctionality from incorrect origins - use []string instead of basic string to avoid reparsing in template.go - fix typo in docs - modify template to properly enable only if the whole block is enabled - modify cors parsing - test properly by validating that the value returned is the proper origin - update unit tests and annotation tests * Re-add `*` when no cors origins are supplied + fix tests - fix e2e tests to allow for `*` - re-add `*` to cors parsing if trimmed cors-allow-origin is empty (supplied but empty) and if it wasn't supplied at all. * remove unecessary logic for building cors origin + remove comments - add some edge cases in e2e tests - rework logic for building cors origin there was no need for logic in template.go for buildCorsOriginRegex if there is a `*` it ill be short-circuited by first if. if it's a wildcard domain or any domain (without a wildcard), it MUST match the main/cors.go regex format. if there's a star in a wildcard domain, it must be replaced with `[A-Za-z0-9]+` * add missing check in e2e tests
2021-11-02 19:31:42 +00:00
for i, origin := range corsOrigins {
originTrimmed := strings.TrimSpace(origin)
if len(originTrimmed) > 0 {
builtOrigin := buildOriginRegex(originTrimmed)
originsRegex += builtOrigin
if i != len(corsOrigins)-1 {
originsRegex += "|"
Support cors-allow-origin with multiple origins (#7614) * Add Initial support for multiple cors origins in nginx - bump cluster version for `make dev-env` - add buildOriginRegex function in nginx.tmpl - add e2e 4 e2e tests for cors.go - refers to feature request #5496 * add tests + use search to identify '*' origin * add tests + use search to identify '*' origin Signed-off-by: Christopher Larivière <lariviere.c@gmail.com> * fix "should enable cors test" looking at improper values * Modify tests and add some logic for origin validation - add origin validation in cors ingress annotations - add extra tests to validate regex - properly escape regex using "QuoteMeta" - fix some copy/paste errors * add TrimSpace and length validation before adding a new origin * modify documentation for cors and remove dangling comment * add support for optional port mapping on origin * support single-level wildcard subdomains + tests * Remove automatic `*` fonctionality from incorrect origins - use []string instead of basic string to avoid reparsing in template.go - fix typo in docs - modify template to properly enable only if the whole block is enabled - modify cors parsing - test properly by validating that the value returned is the proper origin - update unit tests and annotation tests * Re-add `*` when no cors origins are supplied + fix tests - fix e2e tests to allow for `*` - re-add `*` to cors parsing if trimmed cors-allow-origin is empty (supplied but empty) and if it wasn't supplied at all. * remove unecessary logic for building cors origin + remove comments - add some edge cases in e2e tests - rework logic for building cors origin there was no need for logic in template.go for buildCorsOriginRegex if there is a `*` it ill be short-circuited by first if. if it's a wildcard domain or any domain (without a wildcard), it MUST match the main/cors.go regex format. if there's a star in a wildcard domain, it must be replaced with `[A-Za-z0-9]+` * add missing check in e2e tests
2021-11-02 19:31:42 +00:00
}
}
}
originsRegex += ")$ ) { set $cors 'true'; }"
Support cors-allow-origin with multiple origins (#7614) * Add Initial support for multiple cors origins in nginx - bump cluster version for `make dev-env` - add buildOriginRegex function in nginx.tmpl - add e2e 4 e2e tests for cors.go - refers to feature request #5496 * add tests + use search to identify '*' origin * add tests + use search to identify '*' origin Signed-off-by: Christopher Larivière <lariviere.c@gmail.com> * fix "should enable cors test" looking at improper values * Modify tests and add some logic for origin validation - add origin validation in cors ingress annotations - add extra tests to validate regex - properly escape regex using "QuoteMeta" - fix some copy/paste errors * add TrimSpace and length validation before adding a new origin * modify documentation for cors and remove dangling comment * add support for optional port mapping on origin * support single-level wildcard subdomains + tests * Remove automatic `*` fonctionality from incorrect origins - use []string instead of basic string to avoid reparsing in template.go - fix typo in docs - modify template to properly enable only if the whole block is enabled - modify cors parsing - test properly by validating that the value returned is the proper origin - update unit tests and annotation tests * Re-add `*` when no cors origins are supplied + fix tests - fix e2e tests to allow for `*` - re-add `*` to cors parsing if trimmed cors-allow-origin is empty (supplied but empty) and if it wasn't supplied at all. * remove unecessary logic for building cors origin + remove comments - add some edge cases in e2e tests - rework logic for building cors origin there was no need for logic in template.go for buildCorsOriginRegex if there is a `*` it ill be short-circuited by first if. if it's a wildcard domain or any domain (without a wildcard), it MUST match the main/cors.go regex format. if there's a star in a wildcard domain, it must be replaced with `[A-Za-z0-9]+` * add missing check in e2e tests
2021-11-02 19:31:42 +00:00
return originsRegex
}