From ff0cb504d672c2c576d99adcf7ae9abc98857f6d Mon Sep 17 00:00:00 2001 From: Chen Chen Date: Thu, 6 Jul 2023 19:31:03 +0800 Subject: [PATCH 01/47] Cleanup errcheck code (#10166) Signed-off-by: z1cheng --- test/e2e/endpointslices/topology.go | 5 ++--- test/e2e/settings/proxy_protocol.go | 34 ++++++++++++++--------------- test/e2e/ssl/secret_update.go | 5 ++--- 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/test/e2e/endpointslices/topology.go b/test/e2e/endpointslices/topology.go index 8dd0becfb..ff66f2ad1 100644 --- a/test/e2e/endpointslices/topology.go +++ b/test/e2e/endpointslices/topology.go @@ -76,9 +76,8 @@ var _ = framework.IngressNginxDescribeSerial("[TopologyHints] topology aware rou status, err := f.ExecIngressPod(curlCmd) assert.Nil(ginkgo.GinkgoT(), err) var backends []map[string]interface{} - if err := json.Unmarshal([]byte(status), &backends); err != nil { - assert.Nil(ginkgo.GinkgoT(), err) - } + err = json.Unmarshal([]byte(status), &backends) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error unmarshalling backends") gotBackends := 0 for _, bck := range backends { if strings.Contains(bck["name"].(string), "topology") { diff --git a/test/e2e/settings/proxy_protocol.go b/test/e2e/settings/proxy_protocol.go index 1567b2267..9939cad9e 100644 --- a/test/e2e/settings/proxy_protocol.go +++ b/test/e2e/settings/proxy_protocol.go @@ -63,12 +63,11 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { defer conn.Close() header := "PROXY TCP4 192.168.0.1 192.168.0.11 56324 1234\r\n" - if _, err := conn.Write([]byte(header)); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") - } - if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") - } + _, err = conn.Write([]byte(header)) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") + + _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") data, err := io.ReadAll(conn) assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") @@ -100,12 +99,11 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { defer conn.Close() header := "PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n" - if _, err := conn.Write([]byte(header)); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") - } - if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") - } + _, err = conn.Write([]byte(header)) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") + + _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") data, err := io.ReadAll(conn) assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") @@ -213,12 +211,12 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { defer conn.Close() header := "PROXY TCP4 192.168.0.1 192.168.0.11 56324 8080\r\n" - if _, err := conn.Write([]byte(header)); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") - } - if _, err := conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") - } + _, err = conn.Write([]byte(header)) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing header") + + _, err = conn.Write([]byte("GET / HTTP/1.1\r\nHost: proxy-protocol\r\n\r\n")) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error writing request") + _, err = io.ReadAll(conn) assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") diff --git a/test/e2e/ssl/secret_update.go b/test/e2e/ssl/secret_update.go index 242b370ee..fe7bfca0c 100644 --- a/test/e2e/ssl/secret_update.go +++ b/test/e2e/ssl/secret_update.go @@ -73,9 +73,8 @@ var _ = framework.IngressNginxDescribe("[SSL] secret update", func() { dummySecret.Data["some-key"] = []byte("some value") - if _, err := f.KubeClientSet.CoreV1().Secrets(f.Namespace).Update(context.TODO(), dummySecret, metav1.UpdateOptions{}); err != nil { - assert.Nil(ginkgo.GinkgoT(), err, "updating secret") - } + _, err = f.KubeClientSet.CoreV1().Secrets(f.Namespace).Update(context.TODO(), dummySecret, metav1.UpdateOptions{}) + assert.Nil(ginkgo.GinkgoT(), err, "updating secret") assert.NotContains(ginkgo.GinkgoT(), log, fmt.Sprintf("starting syncing of secret %v/dummy", f.Namespace)) assert.NotContains(ginkgo.GinkgoT(), log, fmt.Sprintf("error obtaining PEM from secret %v/dummy", f.Namespace)) From c8f7cb052af9f6ddbcb3e92c677d88af13204889 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A1z=C3=A1r=20Gy=C3=B6rgy?= <55853197+lgyurci@users.noreply.github.com> Date: Fri, 7 Jul 2023 01:39:04 +0200 Subject: [PATCH 02/47] Exposed continent data as variable in the case of Maxmind city files (#10157) --- rootfs/etc/nginx/template/nginx.tmpl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 6ace87448..189c13d6c 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -224,6 +224,8 @@ http { $geoip2_subregion_code source=$remote_addr subdivisions 1 iso_code; $geoip2_subregion_name source=$remote_addr subdivisions 1 names en; $geoip2_subregion_geoname_id source=$remote_addr subdivisions 1 geoname_id; + $geoip2_city_continent_code source=$remote_addr continent code; + $geoip2_city_continent_name source=$remote_addr continent names en; } {{ end }} @@ -245,6 +247,8 @@ http { $geoip2_subregion_code source=$remote_addr subdivisions 1 iso_code; $geoip2_subregion_name source=$remote_addr subdivisions 1 names en; $geoip2_subregion_geoname_id source=$remote_addr subdivisions 1 geoname_id; + $geoip2_city_continent_code source=$remote_addr continent code; + $geoip2_city_continent_name source=$remote_addr continent names en; } {{ end }} From 125b3be6f9960f86174fbcb842912e87d5f530bd Mon Sep 17 00:00:00 2001 From: Alex Matchneer Date: Thu, 6 Jul 2023 19:47:04 -0400 Subject: [PATCH 03/47] Clarify TCP/UDP service docs (#10146) In the current state, the docs on TCP/UDP aren't really clear on exactly whether/how TCP/UDP traffic is supported. This is an attempt to clarify the limitations inherent to k8s Ingress resources vs what can be accomplished with this controller. --- docs/user-guide/exposing-tcp-udp-services.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/user-guide/exposing-tcp-udp-services.md b/docs/user-guide/exposing-tcp-udp-services.md index 63293f0e5..089511ff9 100644 --- a/docs/user-guide/exposing-tcp-udp-services.md +++ b/docs/user-guide/exposing-tcp-udp-services.md @@ -1,6 +1,8 @@ # Exposing TCP and UDP services -Ingress does not support TCP or UDP services. For this reason this Ingress controller uses the flags `--tcp-services-configmap` and `--udp-services-configmap` to point to an existing config map where the key is the external port to use and the value indicates the service to expose using the format: +While the Kubernetes Ingress resource only officially supports routing external HTTP(s) traffic to services, ingress-nginx can be configured to receive external TCP/UDP traffic from non-HTTP protocols and route them to internal services using TCP/UDP port mappings that are specified within a ConfigMap. + +To support this, the `--tcp-services-configmap` and `--udp-services-configmap` flags can be used to point to an existing config map where the key is the external port to use and the value indicates the service to expose using the format: `::[PROXY]:[PROXY]` It is also possible to use a number or the name of the port. The two last fields are optional. From 6d55e1f3c42925db5e99f61457695778a681c8be Mon Sep 17 00:00:00 2001 From: David Goffredo Date: Thu, 6 Jul 2023 19:51:04 -0400 Subject: [PATCH 04/47] revise Datadog trace sampling configuration (#10151) * datadog: sample_rate omitted by default * config: use *float32 with nil instead of float32 with sentinel value * change some names * gofmt -s -w internal/ingress/controller/nginx.go --- internal/ingress/controller/config/config.go | 14 +--- internal/ingress/controller/nginx.go | 80 ++++++++++++-------- 2 files changed, 52 insertions(+), 42 deletions(-) diff --git a/internal/ingress/controller/config/config.go b/internal/ingress/controller/config/config.go index 000bfc730..345ce89b4 100644 --- a/internal/ingress/controller/config/config.go +++ b/internal/ingress/controller/config/config.go @@ -706,16 +706,9 @@ type Configuration struct { // Default: nginx.handle DatadogOperationNameOverride string `json:"datadog-operation-name-override"` - // DatadogPrioritySampling specifies to use client-side sampling - // If true disables client-side sampling (thus ignoring sample_rate) and enables distributed - // priority sampling, where traces are sampled based on a combination of user-assigned - // Default: true - DatadogPrioritySampling bool `json:"datadog-priority-sampling"` - // DatadogSampleRate specifies sample rate for any traces created. - // This is effective only when datadog-priority-sampling is false - // Default: 1.0 - DatadogSampleRate float32 `json:"datadog-sample-rate"` + // Default: use a dynamic rate instead + DatadogSampleRate *float32 `json:"datadog-sample-rate",omitempty` // MainSnippet adds custom configuration to the main section of the nginx configuration MainSnippet string `json:"main-snippet"` @@ -1001,8 +994,7 @@ func NewDefault() Configuration { DatadogEnvironment: "prod", DatadogCollectorPort: 8126, DatadogOperationNameOverride: "nginx.handle", - DatadogSampleRate: 1.0, - DatadogPrioritySampling: true, + DatadogSampleRate: nil, LimitReqStatusCode: 503, LimitConnStatusCode: 503, SyslogPort: 514, diff --git a/internal/ingress/controller/nginx.go b/internal/ingress/controller/nginx.go index 4a5a07625..6c25aa34f 100644 --- a/internal/ingress/controller/nginx.go +++ b/internal/ingress/controller/nginx.go @@ -1011,16 +1011,6 @@ const jaegerTmpl = `{ } }` -const datadogTmpl = `{ - "service": "{{ .DatadogServiceName }}", - "agent_host": "{{ .DatadogCollectorHost }}", - "agent_port": {{ .DatadogCollectorPort }}, - "environment": "{{ .DatadogEnvironment }}", - "operation_name_override": "{{ .DatadogOperationNameOverride }}", - "sample_rate": {{ .DatadogSampleRate }}, - "dd.priority.sampling": {{ .DatadogPrioritySampling }} -}` - const otelTmpl = ` exporter = "otlp" processor = "batch" @@ -1044,37 +1034,65 @@ ratio = {{ .OtelSamplerRatio }} parent_based = {{ .OtelSamplerParentBased }} ` -func createOpentracingCfg(cfg ngx_config.Configuration) error { - var tmpl *template.Template - var err error +func datadogOpentracingCfg(cfg ngx_config.Configuration) (string, error) { + m := map[string]interface{}{ + "service": cfg.DatadogServiceName, + "agent_host": cfg.DatadogCollectorHost, + "agent_port": cfg.DatadogCollectorPort, + "environment": cfg.DatadogEnvironment, + "operation_name_override": cfg.DatadogOperationNameOverride, + } - if cfg.ZipkinCollectorHost != "" { - tmpl, err = template.New("zipkin").Parse(zipkinTmpl) - if err != nil { - return err - } - } else if cfg.JaegerCollectorHost != "" || cfg.JaegerEndpoint != "" { - tmpl, err = template.New("jaeger").Parse(jaegerTmpl) - if err != nil { - return err - } - } else if cfg.DatadogCollectorHost != "" { - tmpl, err = template.New("datadog").Parse(datadogTmpl) - if err != nil { - return err - } - } else { - tmpl, _ = template.New("empty").Parse("{}") + // Omit "sample_rate" if the configuration's sample rate is unset (nil). + // Omitting "sample_rate" from the plugin JSON indicates to the tracer that + // it should use dynamic rates instead of a configured rate. + if cfg.DatadogSampleRate != nil { + m["sample_rate"] = *cfg.DatadogSampleRate + } + + buf, err := json.Marshal(m) + if err != nil { + return "", err + } + + return string(buf), nil +} + +func opentracingCfgFromTemplate(cfg ngx_config.Configuration, tmplName string, tmplText string) (string, error) { + tmpl, err := template.New(tmplName).Parse(tmplText) + if err != nil { + return "", err } tmplBuf := bytes.NewBuffer(make([]byte, 0)) err = tmpl.Execute(tmplBuf, cfg) + if err != nil { + return "", err + } + + return tmplBuf.String(), nil +} + +func createOpentracingCfg(cfg ngx_config.Configuration) error { + var configData string + var err error + + if cfg.ZipkinCollectorHost != "" { + configData, err = opentracingCfgFromTemplate(cfg, "zipkin", zipkinTmpl) + } else if cfg.JaegerCollectorHost != "" || cfg.JaegerEndpoint != "" { + configData, err = opentracingCfgFromTemplate(cfg, "jaeger", jaegerTmpl) + } else if cfg.DatadogCollectorHost != "" { + configData, err = datadogOpentracingCfg(cfg) + } else { + configData = "{}" + } + if err != nil { return err } // Expand possible environment variables before writing the configuration to file. - expanded := os.ExpandEnv(tmplBuf.String()) + expanded := os.ExpandEnv(configData) return os.WriteFile("/etc/nginx/opentracing.json", []byte(expanded), file.ReadWriteByUser) } From b9122e0248a5de64bfb3fd7c321be7e2c5238040 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 05:55:07 -0700 Subject: [PATCH 05/47] Bump docker/setup-buildx-action from 2.8.0 to 2.9.0 (#10191) Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2.8.0 to 2.9.0. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/16c0bc4a6e6ada2cfd8afd41d22d95379cf7c32a...2a1a44ac4aa01993040736bd95bb470da1a38365) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 150ec29ae..e2ddec049 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -158,7 +158,7 @@ jobs: - name: Set up Docker Buildx id: buildx - uses: docker/setup-buildx-action@16c0bc4a6e6ada2cfd8afd41d22d95379cf7c32a # v2.8.0 + uses: docker/setup-buildx-action@2a1a44ac4aa01993040736bd95bb470da1a38365 # v2.9.0 with: version: latest From 5b35651a1a40f5506d06540c1fcd103dc41a16d5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 10 Jul 2023 05:57:06 -0700 Subject: [PATCH 06/47] Bump golang.org/x/crypto from 0.10.0 to 0.11.0 (#10192) Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.10.0 to 0.11.0. - [Commits](https://github.com/golang/crypto/compare/v0.10.0...v0.11.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 8 ++++---- go.sum | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/go.mod b/go.mod index 4b75cbd12..2b808ef2b 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/stretchr/testify v1.8.4 github.com/yudai/gojsondiff v1.0.0 github.com/zakjan/cert-chain-resolver v0.0.0-20211122211144-c6b0b792af9a - golang.org/x/crypto v0.10.0 + golang.org/x/crypto v0.11.0 google.golang.org/grpc v1.56.1 google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 gopkg.in/go-playground/pool.v3 v3.1.1 @@ -103,9 +103,9 @@ require ( golang.org/x/mod v0.10.0 // indirect golang.org/x/net v0.10.0 // indirect golang.org/x/oauth2 v0.8.0 // indirect - golang.org/x/sys v0.9.0 // indirect - golang.org/x/term v0.9.0 // indirect - golang.org/x/text v0.10.0 // indirect + golang.org/x/sys v0.10.0 // indirect + golang.org/x/term v0.10.0 // indirect + golang.org/x/text v0.11.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.9.1 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index db879481c..9fee095bc 100644 --- a/go.sum +++ b/go.sum @@ -390,8 +390,8 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.10.0 h1:LKqV2xt9+kDzSTfOhx4FrkEBcMrAgHSYgzywV9zcGmM= -golang.org/x/crypto v0.10.0/go.mod h1:o4eNf7Ede1fv+hwOwZsTHl9EsPFO6q6ZvYR8vYfY45I= +golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= +golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -524,19 +524,19 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.9.0 h1:KS/R3tvhPqvJvwcKfnBHJwwthS11LRhmM5D59eEXa0s= -golang.org/x/sys v0.9.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= +golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.9.0 h1:GRRCnKYhdQrD8kfRAdQ6Zcw1P0OcELxGLKJvtjVMZ28= -golang.org/x/term v0.9.0/go.mod h1:M6DEAAIenWoTxdKrOltXcmDY3rSplQUkrvaDU5FcQyo= +golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= +golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.10.0 h1:UpjohKhiEgNc0CSauXmwYftY1+LlaC75SJwh0SgCX58= -golang.org/x/text v0.10.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= +golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= From 0cd1f16c476ca72c324b8ded07c861ebe0dce4e0 Mon Sep 17 00:00:00 2001 From: lijie Date: Mon, 17 Jul 2023 04:45:06 +0800 Subject: [PATCH 07/47] Scanning port 10247 lead to tcp connection 502 error (#9815) * fix tcp 502 error * fix tcp 502 error for parse tcp backend data * fix tcp 502 error for parse tcp backend data --- rootfs/etc/nginx/lua/tcp_udp_configuration.lua | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/rootfs/etc/nginx/lua/tcp_udp_configuration.lua b/rootfs/etc/nginx/lua/tcp_udp_configuration.lua index 85864b45b..f191454fa 100644 --- a/rootfs/etc/nginx/lua/tcp_udp_configuration.lua +++ b/rootfs/etc/nginx/lua/tcp_udp_configuration.lua @@ -1,5 +1,6 @@ local ngx = ngx local tostring = tostring +local cjson = require("cjson.safe") -- this is the Lua representation of TCP/UDP Configuration local tcp_udp_configuration_data = ngx.shared.tcp_udp_configuration_data @@ -37,6 +38,14 @@ function _M.call() return end + local _, backends_err = cjson.decode(backends) + + if backends_err then + ngx.log(ngx.ERR, "could not parse backends data: ", backends_err) + return + end + + local success, err_conf = tcp_udp_configuration_data:set("backends", backends) if not success then ngx.log(ngx.ERR, "dynamic-configuration: error updating configuration: " .. tostring(err_conf)) From 8f8f471422f0ec4ef8dc09dd22d317b9ee1814de Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Jul 2023 04:47:08 -0700 Subject: [PATCH 08/47] Bump docker/setup-buildx-action from 2.9.0 to 2.9.1 (#10207) Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2.9.0 to 2.9.1. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/2a1a44ac4aa01993040736bd95bb470da1a38365...4c0219f9ac95b02789c1075625400b2acbff50b1) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e2ddec049..097e77276 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -158,7 +158,7 @@ jobs: - name: Set up Docker Buildx id: buildx - uses: docker/setup-buildx-action@2a1a44ac4aa01993040736bd95bb470da1a38365 # v2.9.0 + uses: docker/setup-buildx-action@4c0219f9ac95b02789c1075625400b2acbff50b1 # v2.9.1 with: version: latest From 49674631ef52ef3b37f0ec0ec3210f8cfe3aa951 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 17 Jul 2023 05:49:09 -0700 Subject: [PATCH 09/47] Bump google.golang.org/grpc from 1.56.1 to 1.56.2 (#10193) Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.56.1 to 1.56.2. - [Release notes](https://github.com/grpc/grpc-go/releases) - [Commits](https://github.com/grpc/grpc-go/compare/v1.56.1...v1.56.2) --- updated-dependencies: - dependency-name: google.golang.org/grpc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 2b808ef2b..8864e3a83 100644 --- a/go.mod +++ b/go.mod @@ -26,7 +26,7 @@ require ( github.com/yudai/gojsondiff v1.0.0 github.com/zakjan/cert-chain-resolver v0.0.0-20211122211144-c6b0b792af9a golang.org/x/crypto v0.11.0 - google.golang.org/grpc v1.56.1 + google.golang.org/grpc v1.56.2 google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 gopkg.in/go-playground/pool.v3 v3.1.1 gopkg.in/mcuadros/go-syslog.v2 v2.3.0 diff --git a/go.sum b/go.sum index 9fee095bc..acd310e3a 100644 --- a/go.sum +++ b/go.sum @@ -661,8 +661,8 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.56.1 h1:z0dNfjIl0VpaZ9iSVjA6daGatAYwPGstTjt5vkRMFkQ= -google.golang.org/grpc v1.56.1/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= +google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 h1:pPsdyuBif+uoyUoL19yuj/TCfUPsmpJHJZhWQ98JGLU= google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7/go.mod h1:8pQa1yxxkh+EsxUK8/455D5MSbv3vgmEJqKCH3y17mI= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= From 6416ed821d726d78d8988ed1ae189bc243903471 Mon Sep 17 00:00:00 2001 From: Jintao Zhang Date: Thu, 20 Jul 2023 23:36:09 +0800 Subject: [PATCH 10/47] chore: bump OpenResty to v1.21.4.2 (#10219) Signed-off-by: Jintao Zhang --- images/nginx/rootfs/build.sh | 66 ++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/images/nginx/rootfs/build.sh b/images/nginx/rootfs/build.sh index 5e215bf72..a99ebd292 100755 --- a/images/nginx/rootfs/build.sh +++ b/images/nginx/rootfs/build.sh @@ -20,14 +20,14 @@ set -o pipefail export NGINX_VERSION=1.21.6 -# Check for recent changes: https://github.com/vision5/ngx_devel_kit/compare/v0.3.1...master -export NDK_VERSION=0.3.1 +# Check for recent changes: https://github.com/vision5/ngx_devel_kit/compare/v0.3.2...master +export NDK_VERSION=0.3.2 # Check for recent changes: https://github.com/openresty/set-misc-nginx-module/compare/v0.33...master export SETMISC_VERSION=0.33 -# Check for recent changes: https://github.com/openresty/headers-more-nginx-module/compare/v0.33...master -export MORE_HEADERS_VERSION=0.33 +# Check for recent changes: https://github.com/openresty/headers-more-nginx-module/compare/v0.34...master +export MORE_HEADERS_VERSION=0.34 # Check for recent changes: https://github.com/atomx/nginx-http-auth-digest/compare/v1.0.0...atomx:master export NGINX_DIGEST_AUTH=1.0.0 @@ -65,32 +65,32 @@ export MODSECURITY_LIB_VERSION=e9a7ba4a60be48f761e0328c6dfcc668d70e35a0 # Check for recent changes: https://github.com/coreruleset/coreruleset/compare/v3.3.2...v3.3/master export OWASP_MODSECURITY_CRS_VERSION=v3.3.4 -# Check for recent changes: https://github.com/openresty/lua-nginx-module/compare/v0.10.21...master -export LUA_NGX_VERSION=0.10.21 +# Check for recent changes: https://github.com/openresty/lua-nginx-module/compare/v0.10.25...master +export LUA_NGX_VERSION=0.10.25 -# Check for recent changes: https://github.com/openresty/stream-lua-nginx-module/compare/v0.0.11...master -export LUA_STREAM_NGX_VERSION=0.0.11 +# Check for recent changes: https://github.com/openresty/stream-lua-nginx-module/compare/v0.0.13...master +export LUA_STREAM_NGX_VERSION=0.0.13 # Check for recent changes: https://github.com/openresty/lua-upstream-nginx-module/compare/8aa93ead98ba2060d4efd594ae33a35d153589bf...master export LUA_UPSTREAM_VERSION=8aa93ead98ba2060d4efd594ae33a35d153589bf -# Check for recent changes: https://github.com/openresty/lua-cjson/compare/2.1.0.10...openresty:master -export LUA_CJSON_VERSION=2.1.0.10 +# Check for recent changes: https://github.com/openresty/lua-cjson/compare/2.1.0.11...openresty:master +export LUA_CJSON_VERSION=2.1.0.11 # Check for recent changes: https://github.com/leev/ngx_http_geoip2_module/compare/3.3...master export GEOIP2_VERSION=a26c6beed77e81553686852dceb6c7fdacc5970d -# Check for recent changes: https://github.com/openresty/luajit2/compare/v2.1-20220411...v2.1-agentzh -export LUAJIT_VERSION=2.1-20220411 +# Check for recent changes: https://github.com/openresty/luajit2/compare/v2.1-20230410...v2.1-agentzh +export LUAJIT_VERSION=2.1-20230410 # Check for recent changes: https://github.com/openresty/lua-resty-balancer/compare/v0.04...master export LUA_RESTY_BALANCER=0.04 -# Check for recent changes: https://github.com/openresty/lua-resty-lrucache/compare/v0.11...master -export LUA_RESTY_CACHE=0.11 +# Check for recent changes: https://github.com/openresty/lua-resty-lrucache/compare/v0.13...master +export LUA_RESTY_CACHE=0.13 -# Check for recent changes: https://github.com/openresty/lua-resty-core/compare/v0.1.23...master -export LUA_RESTY_CORE=0.1.23 +# Check for recent changes: https://github.com/openresty/lua-resty-core/compare/v0.1.27...master +export LUA_RESTY_CORE=0.1.27 # Check for recent changes: https://github.com/cloudflare/lua-resty-cookie/compare/v0.1.0...master export LUA_RESTY_COOKIE_VERSION=303e32e512defced053a6484bc0745cf9dc0d39e @@ -101,17 +101,17 @@ export LUA_RESTY_DNS=0.22 # Check for recent changes: https://github.com/ledgetech/lua-resty-http/compare/v0.16.1...master export LUA_RESTY_HTTP=0ce55d6d15da140ecc5966fa848204c6fd9074e8 -# Check for recent changes: https://github.com/openresty/lua-resty-lock/compare/v0.08...master -export LUA_RESTY_LOCK=0.08 +# Check for recent changes: https://github.com/openresty/lua-resty-lock/compare/v0.09...master +export LUA_RESTY_LOCK=0.09 -# Check for recent changes: https://github.com/openresty/lua-resty-upload/compare/v0.10...master -export LUA_RESTY_UPLOAD_VERSION=0.10 +# Check for recent changes: https://github.com/openresty/lua-resty-upload/compare/v0.11...master +export LUA_RESTY_UPLOAD_VERSION=0.11 # Check for recent changes: https://github.com/openresty/lua-resty-string/compare/v0.15...master export LUA_RESTY_STRING_VERSION=0.15 -# Check for recent changes: https://github.com/openresty/lua-resty-memcached/compare/v0.16...master -export LUA_RESTY_MEMCACHED_VERSION=0.16 +# Check for recent changes: https://github.com/openresty/lua-resty-memcached/compare/v0.17...master +export LUA_RESTY_MEMCACHED_VERSION=0.17 # Check for recent changes: https://github.com/openresty/lua-resty-redis/compare/v0.30...master export LUA_RESTY_REDIS_VERSION=0.30 @@ -199,13 +199,13 @@ cd "$BUILD_PATH" get_src 66dc7081488811e9f925719e34d1b4504c2801c81dee2920e5452a86b11405ae \ "https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz" -get_src 0e971105e210d272a497567fa2e2c256f4e39b845a5ba80d373e26ba1abfbd85 \ +get_src 09fec34ff3ef1baf23dd0eaf04307fd73db865cdf99294687de45bf80c58f146 \ "https://github.com/simpl/ngx_devel_kit/archive/v$NDK_VERSION.tar.gz" get_src cd5e2cc834bcfa30149e7511f2b5a2183baf0b70dc091af717a89a64e44a2985 \ "https://github.com/openresty/set-misc-nginx-module/archive/v$SETMISC_VERSION.tar.gz" -get_src a3dcbab117a9c103bc1ea5200fc00a7b7d2af97ff7fd525f16f8ac2632e30fbf \ +get_src 2a86088a37932a4a9812d2e552cc3847e11470a753ed78a18510b196344c2734 \ "https://github.com/openresty/headers-more-nginx-module/archive/v$MORE_HEADERS_VERSION.tar.gz" get_src f09851e6309560a8ff3e901548405066c83f1f6ff88aa7171e0763bd9514762b \ @@ -241,10 +241,10 @@ get_src 7d5f3439c8df56046d0564b5857fd8a30296ab1bd6df0f048aed7afb56a0a4c2 \ get_src 99c47c75c159795c9faf76bbb9fa58e5a50b75286c86565ffcec8514b1c74bf9 \ "https://github.com/openresty/stream-lua-nginx-module/archive/v$LUA_STREAM_NGX_VERSION.tar.gz" else -get_src 9db756000578efaecb43bea4fc6cf631aaa80988d86ffe5d3afeb9927895ffad \ +get_src bc764db42830aeaf74755754b900253c233ad57498debe7a441cee2c6f4b07c2 \ "https://github.com/openresty/lua-nginx-module/archive/v$LUA_NGX_VERSION.tar.gz" -get_src c7924f28cb014a99636e747ea907724dd55f60e180cb92cde6e8ed48d2278f27 \ +get_src c4df29aeee1ec648a2d2d527c2b27312617a1f1a4033e492e8cf8e6ecbbc269d \ "https://github.com/openresty/stream-lua-nginx-module/archive/v$LUA_STREAM_NGX_VERSION.tar.gz" fi @@ -256,7 +256,7 @@ if [[ ${ARCH} == "s390x" ]]; then get_src 266ed1abb70a9806d97cb958537a44b67db6afb33d3b32292a2d68a2acedea75 \ "https://github.com/openresty/luajit2/archive/$LUAJIT_VERSION.tar.gz" else -get_src d3f2c870f8f88477b01726b32accab30f6e5d57ae59c5ec87374ff73d0794316 \ +get_src 77bbcbb24c3c78f51560017288f3118d995fe71240aa379f5818ff6b166712ff \ "https://github.com/openresty/luajit2/archive/v$LUAJIT_VERSION.tar.gz" fi @@ -266,7 +266,7 @@ get_src 8d39c6b23f941a2d11571daaccc04e69539a3fcbcc50a631837560d5861a7b96 \ get_src 4c1933434572226942c65b2f2b26c8a536ab76aa771a3c7f6c2629faa764976b \ "https://github.com/leev/ngx_http_geoip2_module/archive/$GEOIP2_VERSION.tar.gz" -get_src 5d16e623d17d4f42cc64ea9cfb69ca960d313e12f5d828f785dd227cc483fcbd \ +get_src c7e94aefd32ed04068642fd5da2dcc41aa41a63a8dfac6d73b203bc73f1a3232 \ "https://github.com/openresty/lua-resty-upload/archive/v$LUA_RESTY_UPLOAD_VERSION.tar.gz" get_src bdbf271003d95aa91cab0a92f24dca129e99b33f79c13ebfcdbbcbb558129491 \ @@ -279,20 +279,20 @@ if [[ ${ARCH} == "s390x" ]]; then get_src 8f5f76d2689a3f6b0782f0a009c56a65e4c7a4382be86422c9b3549fe95b0dc4 \ "https://github.com/openresty/lua-resty-core/archive/v$LUA_RESTY_CORE.tar.gz" else -get_src efd6b51520429e64b1bcc10f477d370ebed1631c190f7e4dc270d959a743ad7d \ +get_src 5249631c2f493fc41a9e85b1e7214675d2e31d5bb52cac7a1e99d9a5eb873ba9 \ "https://github.com/openresty/lua-resty-core/archive/v$LUA_RESTY_CORE.tar.gz" fi -get_src 0c551d6898f89f876e48730f9b55790d0ba07d5bc0aa6c76153277f63c19489f \ +get_src a77b9de160d81712f2f442e1de8b78a5a7ef0d08f13430ff619f79235db974d4 \ "https://github.com/openresty/lua-cjson/archive/$LUA_CJSON_VERSION.tar.gz" get_src 5ed48c36231e2622b001308622d46a0077525ac2f751e8cc0c9905914254baa4 \ "https://github.com/cloudflare/lua-resty-cookie/archive/$LUA_RESTY_COOKIE_VERSION.tar.gz" -get_src e810ed124fe788b8e4aac2c8960dda1b9a6f8d0ca94ce162f28d3f4d877df8af \ +get_src b38ba9620a08cf3e0b3cc17f85bde285dca6441fe5a6bd982ef732f4b6036e66 \ "https://github.com/openresty/lua-resty-lrucache/archive/v$LUA_RESTY_CACHE.tar.gz" -get_src 2b4683f9abe73e18ca00345c65010c9056777970907a311d6e1699f753141de2 \ +get_src 6aebf4412639a84eedc8b140aa48e065d625453859699a6712a62fa8085f2704 \ "https://github.com/openresty/lua-resty-lock/archive/v$LUA_RESTY_LOCK.tar.gz" get_src 70e9a01eb32ccade0d5116a25bcffde0445b94ad35035ce06b94ccd260ad1bf0 \ @@ -301,7 +301,7 @@ get_src 70e9a01eb32ccade0d5116a25bcffde0445b94ad35035ce06b94ccd260ad1bf0 \ get_src 9fcb6db95bc37b6fce77d3b3dc740d593f9d90dce0369b405eb04844d56ac43f \ "https://github.com/ledgetech/lua-resty-http/archive/$LUA_RESTY_HTTP.tar.gz" -get_src 42893da0e3de4ec180c9bf02f82608d78787290a70c5644b538f29d243147396 \ +get_src 0513e2be4e9d6dd59c5575432c8a28e5f7a105b373009fa5058f685f0759f28f \ "https://github.com/openresty/lua-resty-memcached/archive/v$LUA_RESTY_MEMCACHED_VERSION.tar.gz" get_src c15aed1a01c88a3a6387d9af67a957dff670357f5fdb4ee182beb44635eef3f1 \ From 1dd8d0cfd70b13aeb3220ab2f5157302bebf7418 Mon Sep 17 00:00:00 2001 From: amirschw <24677563+amirschw@users.noreply.github.com> Date: Thu, 20 Jul 2023 20:34:11 +0300 Subject: [PATCH 11/47] Ignore deployment template's replicas if KEDA is enabled (#9534) --- charts/ingress-nginx/templates/controller-deployment.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/charts/ingress-nginx/templates/controller-deployment.yaml b/charts/ingress-nginx/templates/controller-deployment.yaml index 7fe8804ea..c4a1a37e1 100644 --- a/charts/ingress-nginx/templates/controller-deployment.yaml +++ b/charts/ingress-nginx/templates/controller-deployment.yaml @@ -19,7 +19,7 @@ spec: matchLabels: {{- include "ingress-nginx.selectorLabels" . | nindent 6 }} app.kubernetes.io/component: controller - {{- if not .Values.controller.autoscaling.enabled }} + {{- if not (or .Values.controller.autoscaling.enabled .Values.controller.keda.enabled) }} replicas: {{ .Values.controller.replicaCount }} {{- end }} revisionHistoryLimit: {{ .Values.revisionHistoryLimit }} From a297cedb7abdff51e1afbb286e4bd008e9715c69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Thu, 20 Jul 2023 20:00:10 +0200 Subject: [PATCH 12/47] [helm] pass service annotations through helm tpl engine (#10084) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jan-Otto Kröpke --- charts/ingress-nginx/README.md | 4 ++-- .../ingress-nginx/templates/controller-service-internal.yaml | 2 +- charts/ingress-nginx/templates/controller-service.yaml | 2 +- charts/ingress-nginx/values.yaml | 3 ++- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/charts/ingress-nginx/README.md b/charts/ingress-nginx/README.md index 955091873..953eff685 100644 --- a/charts/ingress-nginx/README.md +++ b/charts/ingress-nginx/README.md @@ -399,14 +399,14 @@ As of version `1.26.0` of this chart, by simply not providing any clusterIP valu | controller.scope.enabled | bool | `false` | Enable 'scope' or not | | controller.scope.namespace | string | `""` | Namespace to limit the controller to; defaults to $(POD_NAMESPACE) | | controller.scope.namespaceSelector | string | `""` | When scope.enabled == false, instead of watching all namespaces, we watching namespaces whose labels only match with namespaceSelector. Format like foo=bar. Defaults to empty, means watching all namespaces. | -| controller.service.annotations | object | `{}` | | +| controller.service.annotations | object | `{}` | Annotations are mandatory for the load balancer to come up. Varies with the cloud service. Values passed through helm tpl engine. | | controller.service.appProtocol | bool | `true` | If enabled is adding an appProtocol option for Kubernetes service. An appProtocol field replacing annotations that were using for setting a backend protocol. Here is an example for AWS: service.beta.kubernetes.io/aws-load-balancer-backend-protocol: http It allows choosing the protocol for each backend specified in the Kubernetes service. See the following GitHub issue for more details about the purpose: https://github.com/kubernetes/kubernetes/issues/40244 Will be ignored for Kubernetes versions older than 1.20 # | | controller.service.enableHttp | bool | `true` | | | controller.service.enableHttps | bool | `true` | | | controller.service.enabled | bool | `true` | | | controller.service.external.enabled | bool | `true` | | | controller.service.externalIPs | list | `[]` | List of IP addresses at which the controller services are available # Ref: https://kubernetes.io/docs/concepts/services-networking/service/#external-ips # | -| controller.service.internal.annotations | object | `{}` | Annotations are mandatory for the load balancer to come up. Varies with the cloud service. | +| controller.service.internal.annotations | object | `{}` | Annotations are mandatory for the load balancer to come up. Varies with the cloud service. Values passed through helm tpl engine. | | controller.service.internal.enabled | bool | `false` | Enables an additional internal load balancer (besides the external one). | | controller.service.internal.loadBalancerIP | string | `""` | Used by cloud providers to connect the resulting internal LoadBalancer to a pre-existing static IP. Make sure to add to the service the needed annotation to specify the subnet which the static IP belongs to. For instance, `networking.gke.io/internal-load-balancer-subnet` for GCP and `service.beta.kubernetes.io/aws-load-balancer-subnets` for AWS. | | controller.service.internal.loadBalancerSourceRanges | list | `[]` | Restrict access For LoadBalancer service. Defaults to 0.0.0.0/0. | diff --git a/charts/ingress-nginx/templates/controller-service-internal.yaml b/charts/ingress-nginx/templates/controller-service-internal.yaml index 87146b746..3966b3260 100644 --- a/charts/ingress-nginx/templates/controller-service-internal.yaml +++ b/charts/ingress-nginx/templates/controller-service-internal.yaml @@ -4,7 +4,7 @@ kind: Service metadata: annotations: {{- range $key, $value := .Values.controller.service.internal.annotations }} - {{ $key }}: {{ $value | quote }} + {{ $key }}: {{ tpl ($value | toString) $ | quote }} {{- end }} labels: {{- include "ingress-nginx.labels" . | nindent 4 }} diff --git a/charts/ingress-nginx/templates/controller-service.yaml b/charts/ingress-nginx/templates/controller-service.yaml index b2735d2e8..f079fd4d8 100644 --- a/charts/ingress-nginx/templates/controller-service.yaml +++ b/charts/ingress-nginx/templates/controller-service.yaml @@ -4,7 +4,7 @@ kind: Service metadata: annotations: {{- range $key, $value := .Values.controller.service.annotations }} - {{ $key }}: {{ $value | quote }} + {{ $key }}: {{ tpl ($value | toString) $ | quote }} {{- end }} labels: {{- include "ingress-nginx.labels" . | nindent 4 }} diff --git a/charts/ingress-nginx/values.yaml b/charts/ingress-nginx/values.yaml index d091391a8..6fd113b67 100644 --- a/charts/ingress-nginx/values.yaml +++ b/charts/ingress-nginx/values.yaml @@ -415,6 +415,7 @@ controller: # Will be ignored for Kubernetes versions older than 1.20 ## appProtocol: true + # -- Annotations are mandatory for the load balancer to come up. Varies with the cloud service. Values passed through helm tpl engine. annotations: {} labels: {} # clusterIP: "" @@ -476,7 +477,7 @@ controller: internal: # -- Enables an additional internal load balancer (besides the external one). enabled: false - # -- Annotations are mandatory for the load balancer to come up. Varies with the cloud service. + # -- Annotations are mandatory for the load balancer to come up. Varies with the cloud service. Values passed through helm tpl engine. annotations: {} # -- Used by cloud providers to connect the resulting internal LoadBalancer to a pre-existing static IP. Make sure to add to the service the needed annotation to specify the subnet which the static IP belongs to. For instance, `networking.gke.io/internal-load-balancer-subnet` for GCP and `service.beta.kubernetes.io/aws-load-balancer-subnets` for AWS. loadBalancerIP: "" From 24fda9da20e3045de54c92ef64016d801c370bc9 Mon Sep 17 00:00:00 2001 From: James Strong Date: Thu, 20 Jul 2023 17:34:12 -0400 Subject: [PATCH 13/47] Golang 1.20.6 for test runner (#10230) * Golang 1.20.6 for test runner * alpine 3.18.2 as well Signed-off-by: James Strong --------- Signed-off-by: James Strong --- images/cfssl/rootfs/Dockerfile | 2 +- images/nginx/rootfs/Dockerfile | 4 ++-- images/opentelemetry/rootfs/Dockerfile | 2 +- images/test-runner/Makefile | 4 ++-- rootfs/Dockerfile-chroot | 2 +- test/e2e-image/Dockerfile | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/images/cfssl/rootfs/Dockerfile b/images/cfssl/rootfs/Dockerfile index e8d6c617a..89a5eef9c 100644 --- a/images/cfssl/rootfs/Dockerfile +++ b/images/cfssl/rootfs/Dockerfile @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -FROM alpine:3.18.0 +FROM alpine:3.18.2 RUN echo "@testing http://nl.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories diff --git a/images/nginx/rootfs/Dockerfile b/images/nginx/rootfs/Dockerfile index 9b4abf244..7627870ba 100644 --- a/images/nginx/rootfs/Dockerfile +++ b/images/nginx/rootfs/Dockerfile @@ -11,7 +11,7 @@ # 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. -FROM alpine:3.18.0 as builder +FROM alpine:3.18.2 as builder COPY . / @@ -21,7 +21,7 @@ RUN apk update \ && /build.sh # Use a multi-stage build -FROM alpine:3.18.0 +FROM alpine:3.18.2 ENV PATH=$PATH:/usr/local/luajit/bin:/usr/local/nginx/sbin:/usr/local/nginx/bin diff --git a/images/opentelemetry/rootfs/Dockerfile b/images/opentelemetry/rootfs/Dockerfile index d15c28bbf..f3628b1f3 100644 --- a/images/opentelemetry/rootfs/Dockerfile +++ b/images/opentelemetry/rootfs/Dockerfile @@ -13,7 +13,7 @@ # limitations under the License. -FROM alpine:3.18.0 as base +FROM alpine:3.18.2 as base RUN mkdir -p /opt/third_party/install COPY . /opt/third_party/ diff --git a/images/test-runner/Makefile b/images/test-runner/Makefile index acf3dd660..3cd378937 100644 --- a/images/test-runner/Makefile +++ b/images/test-runner/Makefile @@ -43,7 +43,7 @@ image: --pull \ --push \ --build-arg BASE_IMAGE=${NGINX_BASE_IMAGE} \ - --build-arg GOLANG_VERSION=1.20.5 \ + --build-arg GOLANG_VERSION=1.20.6 \ --build-arg ETCD_VERSION=3.4.3-0 \ --build-arg K8S_RELEASE=v1.26.0 \ --build-arg RESTY_CLI_VERSION=0.27 \ @@ -64,7 +64,7 @@ build: ensure-buildx --progress=${PROGRESS} \ --pull \ --build-arg BASE_IMAGE=${NGINX_BASE_IMAGE} \ - --build-arg GOLANG_VERSION=1.20.5 \ + --build-arg GOLANG_VERSION=1.20.6 \ --build-arg ETCD_VERSION=3.4.3-0 \ --build-arg K8S_RELEASE=v1.26.0 \ --build-arg RESTY_CLI_VERSION=0.27 \ diff --git a/rootfs/Dockerfile-chroot b/rootfs/Dockerfile-chroot index a4123fe87..48facd44f 100644 --- a/rootfs/Dockerfile-chroot +++ b/rootfs/Dockerfile-chroot @@ -23,7 +23,7 @@ RUN apk update \ && apk upgrade \ && /chroot.sh -FROM alpine:3.18.0 +FROM alpine:3.18.2 ARG TARGETARCH ARG VERSION diff --git a/test/e2e-image/Dockerfile b/test/e2e-image/Dockerfile index 97986ec95..2ee5716ed 100644 --- a/test/e2e-image/Dockerfile +++ b/test/e2e-image/Dockerfile @@ -1,7 +1,7 @@ ARG E2E_BASE_IMAGE FROM ${E2E_BASE_IMAGE} AS BASE -FROM alpine:3.18.0 +FROM alpine:3.18.2 RUN apk update \ && apk upgrade && apk add -U --no-cache \ From e8097d8b8ff4aa4573a8d25e4bb98093323e6302 Mon Sep 17 00:00:00 2001 From: James Strong Date: Thu, 20 Jul 2023 21:04:21 -0400 Subject: [PATCH 14/47] fix gcloud builds Signed-off-by: James Strong --- images/cfssl/Makefile | 2 -- images/cfssl/cloudbuild.yaml | 5 ----- images/custom-error-pages/cloudbuild.yaml | 5 ----- images/echo/cloudbuild.yaml | 5 ----- images/ext-auth-example-authsvc/Makefile | 4 +++- images/ext-auth-example-authsvc/cloudbuild.yaml | 5 ----- images/fastcgi-helloserver/cloudbuild.yaml | 6 +----- images/go-grpc-greeter-server/cloudbuild.yaml | 5 ----- images/httpbun/cloudbuild.yaml | 5 ----- images/kube-webhook-certgen/cloudbuild.yaml | 5 ----- images/opentelemetry/cloudbuild.yaml | 5 ----- images/test-runner/Makefile | 2 +- 12 files changed, 5 insertions(+), 49 deletions(-) diff --git a/images/cfssl/Makefile b/images/cfssl/Makefile index 8d8e597a4..31c37fbc5 100644 --- a/images/cfssl/Makefile +++ b/images/cfssl/Makefile @@ -23,8 +23,6 @@ TAG ?=v$(shell date +%Y%m%d)-$(SHORT_SHA) REGISTRY ?= local - - IMAGE = $(REGISTRY)/e2e-test-cfssl # required to enable buildx diff --git a/images/cfssl/cloudbuild.yaml b/images/cfssl/cloudbuild.yaml index 4976a3f67..5fed3b712 100644 --- a/images/cfssl/cloudbuild.yaml +++ b/images/cfssl/cloudbuild.yaml @@ -6,8 +6,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -17,6 +15,3 @@ steps: - | gcloud auth configure-docker \ && cd images/cfssl && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/custom-error-pages/cloudbuild.yaml b/images/custom-error-pages/cloudbuild.yaml index e38d4bcdc..a443d2b11 100644 --- a/images/custom-error-pages/cloudbuild.yaml +++ b/images/custom-error-pages/cloudbuild.yaml @@ -6,8 +6,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -17,6 +15,3 @@ steps: - | gcloud auth configure-docker \ && cd images/custom-error-pages && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/echo/cloudbuild.yaml b/images/echo/cloudbuild.yaml index f07be825a..811d8d3f0 100644 --- a/images/echo/cloudbuild.yaml +++ b/images/echo/cloudbuild.yaml @@ -6,8 +6,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -17,6 +15,3 @@ steps: - | gcloud auth configure-docker \ && cd images/echo && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/ext-auth-example-authsvc/Makefile b/images/ext-auth-example-authsvc/Makefile index 85d2f8e6b..63f261ec3 100644 --- a/images/ext-auth-example-authsvc/Makefile +++ b/images/ext-auth-example-authsvc/Makefile @@ -18,7 +18,9 @@ SHELL=/bin/bash -o pipefail -o errexit DIR:=$(strip $(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))) INIT_BUILDX=$(DIR)/../../hack/init-buildx.sh -TAG ?=v1.0.0 +SHORT_SHA ?=$(shell git rev-parse --short HEAD) +TAG ?=v$(shell date +%Y%m%d)-$(SHORT_SHA) + REGISTRY ?= local IMAGE = $(REGISTRY)/ext-auth-example-authsvc diff --git a/images/ext-auth-example-authsvc/cloudbuild.yaml b/images/ext-auth-example-authsvc/cloudbuild.yaml index c5bb5db6a..4a436e012 100644 --- a/images/ext-auth-example-authsvc/cloudbuild.yaml +++ b/images/ext-auth-example-authsvc/cloudbuild.yaml @@ -8,8 +8,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -19,6 +17,3 @@ steps: - | gcloud auth configure-docker \ && cd images/ext-auth-example-authsvc && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/fastcgi-helloserver/cloudbuild.yaml b/images/fastcgi-helloserver/cloudbuild.yaml index a4c9d5eff..80623a197 100644 --- a/images/fastcgi-helloserver/cloudbuild.yaml +++ b/images/fastcgi-helloserver/cloudbuild.yaml @@ -6,8 +6,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -17,6 +15,4 @@ steps: - | gcloud auth configure-docker \ && cd images/fastcgi-helloserver && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" + diff --git a/images/go-grpc-greeter-server/cloudbuild.yaml b/images/go-grpc-greeter-server/cloudbuild.yaml index 6f32bcf50..20740eb27 100644 --- a/images/go-grpc-greeter-server/cloudbuild.yaml +++ b/images/go-grpc-greeter-server/cloudbuild.yaml @@ -8,8 +8,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -19,6 +17,3 @@ steps: - | gcloud auth configure-docker \ && cd images/go-grpc-greeter-server && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/httpbun/cloudbuild.yaml b/images/httpbun/cloudbuild.yaml index 9e3af5935..68afbe873 100644 --- a/images/httpbun/cloudbuild.yaml +++ b/images/httpbun/cloudbuild.yaml @@ -8,8 +8,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -19,6 +17,3 @@ steps: - | gcloud auth configure-docker \ && cd images/httpbun && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "master" diff --git a/images/kube-webhook-certgen/cloudbuild.yaml b/images/kube-webhook-certgen/cloudbuild.yaml index bf0bd3ce1..88d7400d0 100644 --- a/images/kube-webhook-certgen/cloudbuild.yaml +++ b/images/kube-webhook-certgen/cloudbuild.yaml @@ -21,8 +21,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -32,6 +30,3 @@ steps: - | gcloud auth configure-docker \ && cd images/kube-webhook-certgen && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "main" diff --git a/images/opentelemetry/cloudbuild.yaml b/images/opentelemetry/cloudbuild.yaml index 9556ccba9..baf29a051 100644 --- a/images/opentelemetry/cloudbuild.yaml +++ b/images/opentelemetry/cloudbuild.yaml @@ -8,8 +8,6 @@ steps: entrypoint: bash env: - DOCKER_CLI_EXPERIMENTAL=enabled - - SHORT_SHA=$SHORT_SHA - - BASE_REF=$_PULL_BASE_REF - REGISTRY=gcr.io/k8s-staging-ingress-nginx # default cloudbuild has HOME=/builder/home and docker buildx is in /root/.docker/cli-plugins/docker-buildx # set the home to /root explicitly to if using docker buildx @@ -19,6 +17,3 @@ steps: - | gcloud auth configure-docker \ && cd images/opentelemetry && make push -substitutions: - _GIT_TAG: "12345" - _PULL_BASE_REF: "main" diff --git a/images/test-runner/Makefile b/images/test-runner/Makefile index 3cd378937..97133045e 100644 --- a/images/test-runner/Makefile +++ b/images/test-runner/Makefile @@ -21,7 +21,7 @@ INIT_BUILDX=$(DIR)/../../hack/init-buildx.sh SHORT_SHA ?=$(shell git rev-parse --short HEAD) TAG ?=v$(shell date +%Y%m%d)-$(SHORT_SHA) -REGISTRY ?= local +REGISTRY ?= gcr.io/k8s-staging-ingress-nginx IMAGE = $(REGISTRY)/e2e-test-runner From b0081a574ab46d5477544294836da0746953af17 Mon Sep 17 00:00:00 2001 From: James Strong Date: Thu, 20 Jul 2023 21:05:38 -0400 Subject: [PATCH 15/47] update reg Signed-off-by: James Strong --- images/test-runner/Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/images/test-runner/Makefile b/images/test-runner/Makefile index 97133045e..3cd378937 100644 --- a/images/test-runner/Makefile +++ b/images/test-runner/Makefile @@ -21,7 +21,7 @@ INIT_BUILDX=$(DIR)/../../hack/init-buildx.sh SHORT_SHA ?=$(shell git rev-parse --short HEAD) TAG ?=v$(shell date +%Y%m%d)-$(SHORT_SHA) -REGISTRY ?= gcr.io/k8s-staging-ingress-nginx +REGISTRY ?= local IMAGE = $(REGISTRY)/e2e-test-runner From c83422fd6592b7b6aea2f58b5688929a5170875a Mon Sep 17 00:00:00 2001 From: Jintao Zhang Date: Sat, 22 Jul 2023 06:41:22 +0800 Subject: [PATCH 16/47] fix deps sha Signed-off-by: Jintao Zhang --- images/nginx/rootfs/build.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/images/nginx/rootfs/build.sh b/images/nginx/rootfs/build.sh index a99ebd292..db1eebfb8 100755 --- a/images/nginx/rootfs/build.sh +++ b/images/nginx/rootfs/build.sh @@ -199,13 +199,13 @@ cd "$BUILD_PATH" get_src 66dc7081488811e9f925719e34d1b4504c2801c81dee2920e5452a86b11405ae \ "https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz" -get_src 09fec34ff3ef1baf23dd0eaf04307fd73db865cdf99294687de45bf80c58f146 \ - "https://github.com/simpl/ngx_devel_kit/archive/v$NDK_VERSION.tar.gz" +get_src aa961eafb8317e0eb8da37eb6e2c9ff42267edd18b56947384e719b85188f58b \ + "https://github.com/vision5/ngx_devel_kit/archive/v$NDK_VERSION.tar.gz" get_src cd5e2cc834bcfa30149e7511f2b5a2183baf0b70dc091af717a89a64e44a2985 \ "https://github.com/openresty/set-misc-nginx-module/archive/v$SETMISC_VERSION.tar.gz" -get_src 2a86088a37932a4a9812d2e552cc3847e11470a753ed78a18510b196344c2734 \ +get_src 0c0d2ced2ce895b3f45eb2b230cd90508ab2a773299f153de14a43e44c1209b3 \ "https://github.com/openresty/headers-more-nginx-module/archive/v$MORE_HEADERS_VERSION.tar.gz" get_src f09851e6309560a8ff3e901548405066c83f1f6ff88aa7171e0763bd9514762b \ @@ -244,7 +244,7 @@ else get_src bc764db42830aeaf74755754b900253c233ad57498debe7a441cee2c6f4b07c2 \ "https://github.com/openresty/lua-nginx-module/archive/v$LUA_NGX_VERSION.tar.gz" -get_src c4df29aeee1ec648a2d2d527c2b27312617a1f1a4033e492e8cf8e6ecbbc269d \ +get_src 01b715754a8248cc7228e0c8f97f7488ae429d90208de0481394e35d24cef32f \ "https://github.com/openresty/stream-lua-nginx-module/archive/v$LUA_STREAM_NGX_VERSION.tar.gz" fi @@ -266,7 +266,7 @@ get_src 8d39c6b23f941a2d11571daaccc04e69539a3fcbcc50a631837560d5861a7b96 \ get_src 4c1933434572226942c65b2f2b26c8a536ab76aa771a3c7f6c2629faa764976b \ "https://github.com/leev/ngx_http_geoip2_module/archive/$GEOIP2_VERSION.tar.gz" -get_src c7e94aefd32ed04068642fd5da2dcc41aa41a63a8dfac6d73b203bc73f1a3232 \ +get_src deb4ab1ffb9f3d962c4b4a2c4bdff692b86a209e3835ae71ebdf3b97189e40a9 \ "https://github.com/openresty/lua-resty-upload/archive/v$LUA_RESTY_UPLOAD_VERSION.tar.gz" get_src bdbf271003d95aa91cab0a92f24dca129e99b33f79c13ebfcdbbcbb558129491 \ @@ -279,7 +279,7 @@ if [[ ${ARCH} == "s390x" ]]; then get_src 8f5f76d2689a3f6b0782f0a009c56a65e4c7a4382be86422c9b3549fe95b0dc4 \ "https://github.com/openresty/lua-resty-core/archive/v$LUA_RESTY_CORE.tar.gz" else -get_src 5249631c2f493fc41a9e85b1e7214675d2e31d5bb52cac7a1e99d9a5eb873ba9 \ +get_src 39baab9e2b31cc48cecf896cea40ef6e80559054fd8a6e440cc804a858ea84d4 \ "https://github.com/openresty/lua-resty-core/archive/v$LUA_RESTY_CORE.tar.gz" fi @@ -289,10 +289,10 @@ get_src a77b9de160d81712f2f442e1de8b78a5a7ef0d08f13430ff619f79235db974d4 \ get_src 5ed48c36231e2622b001308622d46a0077525ac2f751e8cc0c9905914254baa4 \ "https://github.com/cloudflare/lua-resty-cookie/archive/$LUA_RESTY_COOKIE_VERSION.tar.gz" -get_src b38ba9620a08cf3e0b3cc17f85bde285dca6441fe5a6bd982ef732f4b6036e66 \ +get_src 573184006b98ccee2594b0d134fa4d05e5d2afd5141cbad315051ccf7e9b6403 \ "https://github.com/openresty/lua-resty-lrucache/archive/v$LUA_RESTY_CACHE.tar.gz" -get_src 6aebf4412639a84eedc8b140aa48e065d625453859699a6712a62fa8085f2704 \ +get_src b4ddcd47db347e9adf5c1e1491a6279a6ae2a3aff3155ef77ea0a65c998a69c1 \ "https://github.com/openresty/lua-resty-lock/archive/v$LUA_RESTY_LOCK.tar.gz" get_src 70e9a01eb32ccade0d5116a25bcffde0445b94ad35035ce06b94ccd260ad1bf0 \ @@ -301,7 +301,7 @@ get_src 70e9a01eb32ccade0d5116a25bcffde0445b94ad35035ce06b94ccd260ad1bf0 \ get_src 9fcb6db95bc37b6fce77d3b3dc740d593f9d90dce0369b405eb04844d56ac43f \ "https://github.com/ledgetech/lua-resty-http/archive/$LUA_RESTY_HTTP.tar.gz" -get_src 0513e2be4e9d6dd59c5575432c8a28e5f7a105b373009fa5058f685f0759f28f \ +get_src 02733575c4aed15f6cab662378e4b071c0a4a4d07940c4ef19a7319e9be943d4 \ "https://github.com/openresty/lua-resty-memcached/archive/v$LUA_RESTY_MEMCACHED_VERSION.tar.gz" get_src c15aed1a01c88a3a6387d9af67a957dff670357f5fdb4ee182beb44635eef3f1 \ From c5f348ea2eec5f15ab0d5c5e976b29d6787fd3dc Mon Sep 17 00:00:00 2001 From: Ricardo Katz Date: Sat, 22 Jul 2023 00:32:07 -0300 Subject: [PATCH 17/47] Implement annotation validation (#9673) * Add validation to all annotations * Add annotation validation for fcgi * Fix reviews and fcgi e2e * Add flag to disable cross namespace validation * Add risk, flag for validation, tests * Add missing formating * Enable validation by default on tests * Test validation flag * remove ajp from list * Finalize validation changes * Add validations to CI * Update helm docs * Fix code review * Use a better name for annotation risk --- .github/workflows/ci.yaml | 49 +++ charts/ingress-nginx/README.md | 1 + charts/ingress-nginx/templates/_params.tpl | 3 + charts/ingress-nginx/values.yaml | 1 + docs/user-guide/cli-arguments.md | 1 + .../nginx-configuration/configmap.md | 26 ++ internal/ingress/annotations/alias/main.go | 36 +- .../ingress/annotations/alias/main_test.go | 35 +- internal/ingress/annotations/annotations.go | 17 +- .../ingress/annotations/annotations_test.go | 32 +- internal/ingress/annotations/auth/main.go | 86 ++++- .../ingress/annotations/auth/main_test.go | 114 ++++++- internal/ingress/annotations/authreq/main.go | 221 +++++++++++-- .../ingress/annotations/authreq/main_test.go | 6 +- .../ingress/annotations/authreqglobal/main.go | 35 +- internal/ingress/annotations/authtls/main.go | 105 +++++- .../ingress/annotations/authtls/main_test.go | 66 +++- .../annotations/backendprotocol/main.go | 59 +++- .../annotations/backendprotocol/main_test.go | 4 +- internal/ingress/annotations/canary/main.go | 121 ++++++- .../annotations/clientbodybuffersize/main.go | 38 ++- .../clientbodybuffersize/main_test.go | 3 + .../ingress/annotations/connection/main.go | 41 ++- .../annotations/connection/main_test.go | 20 +- internal/ingress/annotations/cors/main.go | 120 ++++++- .../ingress/annotations/cors/main_test.go | 42 +-- .../annotations/customhttperrors/main.go | 43 ++- .../annotations/defaultbackend/main.go | 36 +- .../annotations/defaultbackend/main_test.go | 58 +++- internal/ingress/annotations/fastcgi/main.go | 71 +++- .../ingress/annotations/fastcgi/main_test.go | 124 ++++++- .../annotations/globalratelimit/main.go | 81 ++++- .../annotations/globalratelimit/main_test.go | 22 +- .../annotations/http2pushpreload/main.go | 35 +- .../annotations/http2pushpreload/main_test.go | 20 +- .../{ipwhitelist => ipallowlist}/main.go | 64 +++- .../{ipwhitelist => ipallowlist}/main_test.go | 83 ++++- .../ingress/annotations/ipdenylist/main.go | 47 ++- .../annotations/ipdenylist/main_test.go | 30 +- .../ingress/annotations/loadbalancing/main.go | 44 ++- .../annotations/loadbalancing/main_test.go | 3 +- internal/ingress/annotations/log/main.go | 44 ++- internal/ingress/annotations/log/main_test.go | 22 +- internal/ingress/annotations/mirror/main.go | 74 ++++- .../ingress/annotations/mirror/main_test.go | 11 +- .../ingress/annotations/modsecurity/main.go | 73 ++++- .../ingress/annotations/opentelemetry/main.go | 67 +++- .../annotations/opentelemetry/main_test.go | 30 +- .../ingress/annotations/opentracing/main.go | 45 ++- .../annotations/opentracing/main_test.go | 8 +- internal/ingress/annotations/parser/main.go | 109 ++++-- .../ingress/annotations/parser/main_test.go | 21 +- .../ingress/annotations/parser/validators.go | 239 ++++++++++++++ .../annotations/parser/validators_test.go | 310 ++++++++++++++++++ .../annotations/portinredirect/main.go | 35 +- .../annotations/portinredirect/main_test.go | 28 +- internal/ingress/annotations/proxy/main.go | 188 +++++++++-- .../ingress/annotations/proxy/main_test.go | 68 ++++ internal/ingress/annotations/proxyssl/main.go | 115 ++++++- .../ingress/annotations/proxyssl/main_test.go | 2 +- .../ingress/annotations/ratelimit/main.go | 120 ++++++- .../annotations/ratelimit/main_test.go | 93 +++++- .../ingress/annotations/redirect/redirect.go | 67 +++- .../annotations/redirect/redirect_test.go | 10 +- internal/ingress/annotations/rewrite/main.go | 103 +++++- .../ingress/annotations/rewrite/main_test.go | 24 ++ internal/ingress/annotations/satisfy/main.go | 37 ++- .../ingress/annotations/satisfy/main_test.go | 2 +- .../ingress/annotations/serversnippet/main.go | 35 +- .../annotations/serversnippet/main_test.go | 2 +- .../annotations/serviceupstream/main.go | 35 +- .../annotations/serviceupstream/main_test.go | 6 +- .../annotations/sessionaffinity/main.go | 125 ++++++- internal/ingress/annotations/snippet/main.go | 35 +- .../ingress/annotations/snippet/main_test.go | 2 +- .../ingress/annotations/sslcipher/main.go | 56 +++- .../annotations/sslcipher/main_test.go | 27 +- .../annotations/sslpassthrough/main.go | 34 +- .../annotations/sslpassthrough/main_test.go | 2 +- .../ingress/annotations/streamsnippet/main.go | 35 +- .../annotations/streamsnippet/main_test.go | 2 +- .../annotations/upstreamhashby/main.go | 71 +++- .../annotations/upstreamhashby/main_test.go | 32 +- .../ingress/annotations/upstreamvhost/main.go | 36 +- .../annotations/upstreamvhost/main_test.go | 2 +- .../annotations/xforwardedprefix/main.go | 35 +- .../annotations/xforwardedprefix/main_test.go | 2 +- internal/ingress/controller/config/config.go | 15 +- internal/ingress/controller/controller.go | 15 +- .../ingress/controller/controller_test.go | 13 +- internal/ingress/controller/store/store.go | 35 +- .../ingress/controller/store/store_test.go | 17 +- internal/ingress/defaults/main.go | 12 + internal/ingress/errors/errors.go | 44 +++ internal/ingress/resolver/main.go | 3 + internal/ingress/resolver/mock.go | 15 +- pkg/apis/ingress/types.go | 8 +- pkg/apis/ingress/types_equals.go | 2 +- pkg/flags/flags.go | 4 + rootfs/etc/nginx/template/nginx.tmpl | 10 +- .../validations/values.yaml | 38 +++ test/e2e/annotations/fastcgi.go | 4 +- .../{ipwhitelist.go => ipallowlist.go} | 10 +- test/e2e/e2e.go | 2 + test/e2e/framework/exec.go | 7 +- test/e2e/run-e2e-suite.sh | 1 + test/e2e/run-kind-e2e.sh | 1 + test/e2e/settings/validations/validations.go | 86 +++++ test/e2e/wait-for-nginx.sh | 2 + 109 files changed, 4320 insertions(+), 586 deletions(-) rename internal/ingress/annotations/{ipwhitelist => ipallowlist}/main.go (53%) rename internal/ingress/annotations/{ipwhitelist => ipallowlist}/main_test.go (64%) create mode 100644 internal/ingress/annotations/parser/validators.go create mode 100644 internal/ingress/annotations/parser/validators_test.go create mode 100644 test/e2e-image/namespace-overlays/validations/values.yaml rename test/e2e/annotations/{ipwhitelist.go => ipallowlist.go} (81%) create mode 100644 test/e2e/settings/validations/validations.go diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 097e77276..453775379 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -319,6 +319,55 @@ jobs: name: e2e-test-reports-${{ matrix.k8s }} path: 'test/junitreports/report*.xml' + kubernetes-validations: + name: Kubernetes with Validations + runs-on: ubuntu-latest + needs: + - changes + - build + if: | + (needs.changes.outputs.go == 'true') || ${{ inputs.run_e2e }} + + strategy: + matrix: + k8s: [v1.27.1] + + steps: + - name: Checkout + uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + + - name: cache + uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 + with: + name: docker.tar.gz + + - name: Create Kubernetes ${{ matrix.k8s }} cluster + id: kind + run: | + kind create cluster --image=kindest/node:${{ matrix.k8s }} --config test/e2e/kind.yaml + + - name: Load images from cache + run: | + echo "loading docker images..." + pigz -dc docker.tar.gz | docker load + + - name: Run e2e tests + env: + KIND_CLUSTER_NAME: kind + SKIP_CLUSTER_CREATION: true + SKIP_IMAGE_CREATION: true + ENABLE_VALIDATIONS: true + run: | + kind get kubeconfig > $HOME/.kube/kind-config-kind + make kind-e2e-test + + - name: Upload e2e junit-reports + uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2 + if: success() || failure() + with: + name: e2e-test-reports-${{ matrix.k8s }} + path: 'test/junitreports/report*.xml' + kubernetes-chroot: name: Kubernetes chroot diff --git a/charts/ingress-nginx/README.md b/charts/ingress-nginx/README.md index 953eff685..17547912d 100644 --- a/charts/ingress-nginx/README.md +++ b/charts/ingress-nginx/README.md @@ -294,6 +294,7 @@ As of version `1.26.0` of this chart, by simply not providing any clusterIP valu | controller.dnsConfig | object | `{}` | Optionally customize the pod dnsConfig. | | controller.dnsPolicy | string | `"ClusterFirst"` | Optionally change this to ClusterFirstWithHostNet in case you have 'hostNetwork: true'. By default, while using host network, name resolution uses the host's DNS. If you wish nginx-controller to keep resolving names inside the k8s network, use ClusterFirstWithHostNet. | | controller.electionID | string | `""` | Election ID to use for status update, by default it uses the controller name combined with a suffix of 'leader' | +| controller.enableAnnotationValidations | bool | `false` | | | controller.enableMimalloc | bool | `true` | Enable mimalloc as a drop-in replacement for malloc. # ref: https://github.com/microsoft/mimalloc # | | controller.enableTopologyAwareRouting | bool | `false` | This configuration enables Topology Aware Routing feature, used together with service annotation service.kubernetes.io/topology-aware-hints="auto" Defaults to false | | controller.existingPsp | string | `""` | Use an existing PSP instead of creating one | diff --git a/charts/ingress-nginx/templates/_params.tpl b/charts/ingress-nginx/templates/_params.tpl index a1aef01ae..47d024e85 100644 --- a/charts/ingress-nginx/templates/_params.tpl +++ b/charts/ingress-nginx/templates/_params.tpl @@ -1,5 +1,8 @@ {{- define "ingress-nginx.params" -}} - /nginx-ingress-controller +{{- if .Values.controller.enableAnnotationValidations }} +- --enable-annotation-validation=true +{{- end }} {{- if .Values.defaultBackend.enabled }} - --default-backend-service=$(POD_NAMESPACE)/{{ include "ingress-nginx.defaultBackend.fullname" . }} {{- end }} diff --git a/charts/ingress-nginx/values.yaml b/charts/ingress-nginx/values.yaml index 6fd113b67..1cd74dad0 100644 --- a/charts/ingress-nginx/values.yaml +++ b/charts/ingress-nginx/values.yaml @@ -15,6 +15,7 @@ commonLabels: {} controller: name: controller + enableAnnotationValidations: false image: ## Keep false as default for now! chroot: false diff --git a/docs/user-guide/cli-arguments.md b/docs/user-guide/cli-arguments.md index bc0894a52..be6e1dd50 100644 --- a/docs/user-guide/cli-arguments.md +++ b/docs/user-guide/cli-arguments.md @@ -15,6 +15,7 @@ They are set in the container spec of the `ingress-nginx-controller` Deployment | `--default-backend-service` | Service used to serve HTTP requests not matching any known server name (catch-all). Takes the form "namespace/name". The controller configures NGINX to forward requests to the first port of this Service. | | `--default-server-port` | Port to use for exposing the default server (catch-all). (default 8181) | | `--default-ssl-certificate` | Secret containing a SSL certificate to be used by the default HTTPS server (catch-all). Takes the form "namespace/name". | +| `--enable-annotation-validation` | If true, will enable the annotation validation feature. This value will be defaulted to true on a future release. | | `--disable-catch-all` | Disable support for catch-all Ingresses. (default false) | | `--disable-full-test` | Disable full test of all merged ingresses at the admission stage and tests the template of the ingress being created or updated (full test of all ingresses is enabled by default). | | `--disable-svc-external-name` | Disable support for Services of type ExternalName. (default false) | diff --git a/docs/user-guide/nginx-configuration/configmap.md b/docs/user-guide/nginx-configuration/configmap.md index c55b7502a..0a7e44dce 100644 --- a/docs/user-guide/nginx-configuration/configmap.md +++ b/docs/user-guide/nginx-configuration/configmap.md @@ -29,7 +29,9 @@ The following table shows a configuration option's name, type, and the default v |:---|:---|:------|:----| |[add-headers](#add-headers)|string|""|| |[allow-backend-server-header](#allow-backend-server-header)|bool|"false"|| +|[allow-cross-namespace-resources](#allow-cross-namespace-resources)|bool|"true"|| |[allow-snippet-annotations](#allow-snippet-annotations)|bool|true|| +|[annotations-risk-level](#annotations-risk-level)|string|Critical|| |[annotation-value-word-blocklist](#annotation-value-word-blocklist)|string array|""|| |[hide-headers](#hide-headers)|string array|empty|| |[access-log-params](#access-log-params)|string|""|| @@ -239,6 +241,20 @@ Sets custom headers from named configmap before sending traffic to the client. S Enables the return of the header Server from the backend instead of the generic nginx string. _**default:**_ is disabled +## allow-cross-namespace-resources + +Enables users to consume cross namespace resource on annotations, when was previously enabled . _**default:**_ true + +**Annotations that may be impacted with this change**: +* `auth-secret` +* `auth-proxy-set-header` +* `auth-tls-secret` +* `fastcgi-params-configmap` +* `proxy-ssl-secret` + + +**This option will be defaulted to false in the next major release** + ## allow-snippet-annotations Enables Ingress to parse and add *-snippet annotations/directives created by the user. _**default:**_ `true` @@ -246,6 +262,16 @@ Enables Ingress to parse and add *-snippet annotations/directives created by the Warning: We recommend enabling this option only if you TRUST users with permission to create Ingress objects, as this may allow a user to add restricted configurations to the final nginx.conf file +**This option will be defaulted to false in the next major release** + +## annotations-risk-level + +Represents the risk accepted on an annotation. If the risk is, for instance `Medium`, annotations with risk High and Critical will not be accepted. + +Accepted values are `Critical`, `High`, `Medium` and `Low`. + +Defaults to `Critical` but will be changed to `High` on the next minor release + ## annotation-value-word-blocklist Contains a comma-separated value of chars/words that are well known of being used to abuse Ingress configuration diff --git a/internal/ingress/annotations/alias/main.go b/internal/ingress/annotations/alias/main.go index bd2067c9f..4a5e6f188 100644 --- a/internal/ingress/annotations/alias/main.go +++ b/internal/ingress/annotations/alias/main.go @@ -27,19 +27,44 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + serverAliasAnnotation = "server-alias" +) + +var aliasAnnotation = parser.Annotation{ + Group: "alias", + Annotations: parser.AnnotationFields{ + serverAliasAnnotation: { + Validator: parser.ValidateArrayOfServerName, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, // High as this allows regex chars + Documentation: `this annotation can be used to define additional server + aliases for this Ingress`, + }, + }, +} + type alias struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new Alias annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return alias{r} + return alias{ + r: r, + annotationConfig: aliasAnnotation, + } +} + +func (a alias) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations } // Parse parses the annotations contained in the ingress rule // used to add an alias to the provided hosts func (a alias) Parse(ing *networking.Ingress) (interface{}, error) { - val, err := parser.GetStringAnnotation("server-alias", ing) + val, err := parser.GetStringAnnotation(serverAliasAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return []string{}, err } @@ -61,3 +86,8 @@ func (a alias) Parse(ing *networking.Ingress) (interface{}, error) { return l, nil } + +func (a alias) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, aliasAnnotation.Annotations) +} diff --git a/internal/ingress/annotations/alias/main_test.go b/internal/ingress/annotations/alias/main_test.go index 8e6fca447..1965f2630 100644 --- a/internal/ingress/annotations/alias/main_test.go +++ b/internal/ingress/annotations/alias/main_test.go @@ -27,7 +27,7 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -var annotation = parser.GetAnnotationWithPrefix("server-alias") +var annotation = parser.GetAnnotationWithPrefix(serverAliasAnnotation) func TestParse(t *testing.T) { ap := NewParser(&resolver.Mock{}) @@ -36,16 +36,20 @@ func TestParse(t *testing.T) { } testCases := []struct { - annotations map[string]string - expected []string + annotations map[string]string + expected []string + skipValidation bool + wantErr bool }{ - {map[string]string{annotation: "a.com, b.com, , c.com"}, []string{"a.com", "b.com", "c.com"}}, - {map[string]string{annotation: "www.example.com"}, []string{"www.example.com"}}, - {map[string]string{annotation: "*.example.com,www.example.*"}, []string{"*.example.com", "www.example.*"}}, - {map[string]string{annotation: `~^www\d+\.example\.com$`}, []string{`~^www\d+\.example\.com$`}}, - {map[string]string{annotation: ""}, []string{}}, - {map[string]string{}, []string{}}, - {nil, []string{}}, + {map[string]string{annotation: "a.com, b.com, , c.com"}, []string{"a.com", "b.com", "c.com"}, false, false}, + {map[string]string{annotation: "www.example.com"}, []string{"www.example.com"}, false, false}, + {map[string]string{annotation: "*.example.com,www.example.*"}, []string{"*.example.com", "www.example.*"}, false, false}, + {map[string]string{annotation: `~^www\d+\.example\.com$`}, []string{`~^www\d+\.example\.com$`}, false, false}, + {map[string]string{annotation: `www.xpto;lala`}, []string{}, false, true}, + {map[string]string{annotation: `www.xpto;lala`}, []string{"www.xpto;lala"}, true, false}, // When we skip validation no error should happen + {map[string]string{annotation: ""}, []string{}, false, true}, + {map[string]string{}, []string{}, false, true}, + {nil, []string{}, false, true}, } ing := &networking.Ingress{ @@ -58,7 +62,16 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) + if testCase.skipValidation { + parser.EnableAnnotationValidation = false + } + defer func() { + parser.EnableAnnotationValidation = true + }() + result, err := ap.Parse(ing) + if (err != nil) != testCase.wantErr { + t.Errorf("ParseAliasAnnotation() annotation: %s, error = %v, wantErr %v", testCase.annotations, err, testCase.wantErr) + } if !reflect.DeepEqual(result, testCase.expected) { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) } diff --git a/internal/ingress/annotations/annotations.go b/internal/ingress/annotations/annotations.go index 5bb2bf5e6..5371e6eb7 100644 --- a/internal/ingress/annotations/annotations.go +++ b/internal/ingress/annotations/annotations.go @@ -44,8 +44,8 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/fastcgi" "k8s.io/ingress-nginx/internal/ingress/annotations/globalratelimit" "k8s.io/ingress-nginx/internal/ingress/annotations/http2pushpreload" + "k8s.io/ingress-nginx/internal/ingress/annotations/ipallowlist" "k8s.io/ingress-nginx/internal/ingress/annotations/ipdenylist" - "k8s.io/ingress-nginx/internal/ingress/annotations/ipwhitelist" "k8s.io/ingress-nginx/internal/ingress/annotations/loadbalancing" "k8s.io/ingress-nginx/internal/ingress/annotations/log" "k8s.io/ingress-nginx/internal/ingress/annotations/mirror" @@ -109,7 +109,6 @@ type Ingress struct { UpstreamHashBy upstreamhashby.Config LoadBalancing string UpstreamVhost string - Whitelist ipwhitelist.SourceRange Denylist ipdenylist.SourceRange XForwardedPrefix string SSLCipher sslcipher.Config @@ -117,6 +116,7 @@ type Ingress struct { ModSecurity modsecurity.Config Mirror mirror.Config StreamSnippet string + Allowlist ipallowlist.SourceRange } // Extractor defines the annotation parsers to be used in the extraction of annotations @@ -159,7 +159,7 @@ func NewAnnotationExtractor(cfg resolver.Resolver) Extractor { "UpstreamHashBy": upstreamhashby.NewParser(cfg), "LoadBalancing": loadbalancing.NewParser(cfg), "UpstreamVhost": upstreamvhost.NewParser(cfg), - "Whitelist": ipwhitelist.NewParser(cfg), + "Allowlist": ipallowlist.NewParser(cfg), "Denylist": ipdenylist.NewParser(cfg), "XForwardedPrefix": xforwardedprefix.NewParser(cfg), "SSLCipher": sslcipher.NewParser(cfg), @@ -173,16 +173,23 @@ func NewAnnotationExtractor(cfg resolver.Resolver) Extractor { } // Extract extracts the annotations from an Ingress -func (e Extractor) Extract(ing *networking.Ingress) *Ingress { +func (e Extractor) Extract(ing *networking.Ingress) (*Ingress, error) { pia := &Ingress{ ObjectMeta: ing.ObjectMeta, } data := make(map[string]interface{}) for name, annotationParser := range e.annotations { + if err := annotationParser.Validate(ing.GetAnnotations()); err != nil { + return nil, errors.NewRiskyAnnotations(name) + } val, err := annotationParser.Parse(ing) klog.V(5).InfoS("Parsing Ingress annotation", "name", name, "ingress", klog.KObj(ing), "value", val) if err != nil { + if errors.IsValidationError(err) { + klog.ErrorS(err, "ingress contains invalid annotation value") + return nil, err + } if errors.IsMissingAnnotations(err) { continue } @@ -220,5 +227,5 @@ func (e Extractor) Extract(ing *networking.Ingress) *Ingress { klog.ErrorS(err, "unexpected error merging extracted annotations") } - return pia + return pia, nil } diff --git a/internal/ingress/annotations/annotations_test.go b/internal/ingress/annotations/annotations_test.go index d792801bc..2b2a64268 100644 --- a/internal/ingress/annotations/annotations_test.go +++ b/internal/ingress/annotations/annotations_test.go @@ -134,8 +134,11 @@ func TestSSLPassthrough(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Extract(ing).SSLPassthrough - if r != foo.er { + r, err := ec.Extract(ing) + if err != nil { + t.Errorf("Errors should be null: %v", err) + } + if r.SSLPassthrough != foo.er { t.Errorf("Returned %v but expected %v", r, foo.er) } } @@ -158,8 +161,11 @@ func TestUpstreamHashBy(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Extract(ing).UpstreamHashBy.UpstreamHashBy - if r != foo.er { + r, err := ec.Extract(ing) + if err != nil { + t.Errorf("error should be null: %v", err) + } + if r.UpstreamHashBy.UpstreamHashBy != foo.er { t.Errorf("Returned %v but expected %v", r, foo.er) } } @@ -185,7 +191,11 @@ func TestAffinitySession(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Extract(ing).SessionAffinity + rann, err := ec.Extract(ing) + if err != nil { + t.Errorf("error should be null: %v", err) + } + r := rann.SessionAffinity t.Logf("Testing pass %v %v", foo.affinitytype, foo.cookiename) if r.Type != foo.affinitytype { @@ -228,7 +238,11 @@ func TestCors(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Extract(ing).CorsConfig + rann, err := ec.Extract(ing) + if err != nil { + t.Errorf("error should be null: %v", err) + } + r := rann.CorsConfig t.Logf("Testing pass %v %v %v %v %v", foo.corsenabled, foo.methods, foo.headers, foo.origin, foo.credentials) if r.CorsEnabled != foo.corsenabled { @@ -277,7 +291,11 @@ func TestCustomHTTPErrors(t *testing.T) { for _, foo := range fooAnns { ing.SetAnnotations(foo.annotations) - r := ec.Extract(ing).CustomHTTPErrors + rann, err := ec.Extract(ing) + if err != nil { + t.Errorf("error should be null: %v", err) + } + r := rann.CustomHTTPErrors // Check that expected codes were created for i := range foo.er { diff --git a/internal/ingress/annotations/auth/main.go b/internal/ingress/annotations/auth/main.go index 62d70873e..beecebdb1 100644 --- a/internal/ingress/annotations/auth/main.go +++ b/internal/ingress/annotations/auth/main.go @@ -32,13 +32,56 @@ import ( "k8s.io/ingress-nginx/pkg/util/file" ) +const ( + authSecretTypeAnnotation = "auth-secret-type" //#nosec G101 + authRealmAnnotation = "auth-realm" + authTypeAnnotation = "auth-type" + // This should be exported as it is imported by other packages + AuthSecretAnnotation = "auth-secret" //#nosec G101 +) + var ( - authTypeRegex = regexp.MustCompile(`basic|digest`) + authTypeRegex = regexp.MustCompile(`basic|digest`) + authSecretTypeRegex = regexp.MustCompile(`auth-file|auth-map`) + // AuthDirectory default directory used to store files // to authenticate request AuthDirectory = "/etc/ingress-controller/auth" ) +var AuthSecretConfig = parser.AnnotationConfig{ + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars + Documentation: `This annotation defines the name of the Secret that contains the usernames and passwords which are granted access to the paths defined in the Ingress rules. `, +} + +var authSecretAnnotations = parser.Annotation{ + Group: "authentication", + Annotations: parser.AnnotationFields{ + AuthSecretAnnotation: AuthSecretConfig, + authSecretTypeAnnotation: { + Validator: parser.ValidateRegex(*authSecretTypeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation what is the format of auth-secret value. Can be "auth-file" that defines the content of an htpasswd file, or "auth-map" where each key + is a user and each value is the password.`, + }, + authRealmAnnotation: { + Validator: parser.ValidateRegex(*parser.CharsWithSpace, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars + Documentation: `This annotation defines the realm (message) that should be shown to user when authentication is requested.`, + }, + authTypeAnnotation: { + Validator: parser.ValidateRegex(*authTypeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines the basic authentication type. Should be "basic" or "digest"`, + }, + }, +} + const ( fileAuth = "auth-file" mapAuth = "auth-map" @@ -85,13 +128,18 @@ func (bd1 *Config) Equal(bd2 *Config) bool { } type auth struct { - r resolver.Resolver - authDirectory string + r resolver.Resolver + authDirectory string + annotationConfig parser.Annotation } // NewParser creates a new authentication annotation parser func NewParser(authDirectory string, r resolver.Resolver) parser.IngressAnnotation { - return auth{r, authDirectory} + return auth{ + r: r, + authDirectory: authDirectory, + annotationConfig: authSecretAnnotations, + } } // Parse parses the annotations contained in the ingress @@ -99,7 +147,7 @@ func NewParser(authDirectory string, r resolver.Resolver) parser.IngressAnnotati // and generated an htpasswd compatible file to be used as source // during the authentication process func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { - at, err := parser.GetStringAnnotation("auth-type", ing) + at, err := parser.GetStringAnnotation(authTypeAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return nil, err } @@ -109,12 +157,15 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { } var secretType string - secretType, err = parser.GetStringAnnotation("auth-secret-type", ing) + secretType, err = parser.GetStringAnnotation(authSecretTypeAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + return nil, err + } secretType = fileAuth } - s, err := parser.GetStringAnnotation("auth-secret", ing) + s, err := parser.GetStringAnnotation(AuthSecretAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return nil, ing_errors.LocationDenied{ Reason: fmt.Errorf("error reading secret name from annotation: %w", err), @@ -131,6 +182,13 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { if sns == "" { sns = ing.Namespace } + secCfg := a.r.GetSecurityConfiguration() + // We don't accept different namespaces for secrets. + if !secCfg.AllowCrossNamespaceResources && sns != ing.Namespace { + return nil, ing_errors.LocationDenied{ + Reason: fmt.Errorf("cross namespace usage of secrets is not allowed"), + } + } name := fmt.Sprintf("%v/%v", sns, sname) secret, err := a.r.GetSecret(name) @@ -140,7 +198,10 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { } } - realm, _ := parser.GetStringAnnotation("auth-realm", ing) + realm, err := parser.GetStringAnnotation(authRealmAnnotation, ing, a.annotationConfig.Annotations) + if ing_errors.IsValidationError(err) { + return nil, err + } passFilename := fmt.Sprintf("%v/%v-%v-%v.passwd", a.authDirectory, ing.GetNamespace(), ing.UID, secret.UID) @@ -210,3 +271,12 @@ func dumpSecretAuthMap(filename string, secret *api.Secret) error { return nil } + +func (a auth) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a auth) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, authSecretAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/auth/main_test.go b/internal/ingress/annotations/auth/main_test.go index d4ec53459..2a9dc7c72 100644 --- a/internal/ingress/annotations/auth/main_test.go +++ b/internal/ingress/annotations/auth/main_test.go @@ -26,6 +26,7 @@ import ( api "k8s.io/api/core/v1" networking "k8s.io/api/networking/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/tools/cache" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" @@ -79,13 +80,18 @@ type mockSecret struct { } func (m mockSecret) GetSecret(name string) (*api.Secret, error) { - if name != "default/demo-secret" { + if name != "default/demo-secret" && name != "otherns/demo-secret" { return nil, fmt.Errorf("there is no secret with name %v", name) } + ns, _, err := cache.SplitMetaNamespaceKey(name) + if err != nil { + return nil, err + } + return &api.Secret{ ObjectMeta: meta_v1.ObjectMeta{ - Namespace: api.NamespaceDefault, + Namespace: ns, Name: "demo-secret", }, Data: map[string][]byte{"auth": []byte("foo:$apr1$OFG3Xybp$ckL0FHDAkoXYIlH9.cysT0")}, @@ -106,13 +112,91 @@ func TestIngressAuthBadAuthType(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-type")] = "invalid" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "invalid" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - expected := ing_errors.NewLocationDenied("invalid authentication type") + expected := ing_errors.NewValidationError("nginx.ingress.kubernetes.io/auth-type") + _, err := NewParser(dir, &mockSecret{}).Parse(ing) + if err.Error() != expected.Error() { + t.Errorf("expected '%v' but got '%v'", expected, err) + } +} + +func TestIngressInvalidRealm(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "something weird ; location trying to { break }" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" + ing.SetAnnotations(data) + + _, dir, _ := dummySecretContent(t) + defer os.RemoveAll(dir) + + expected := ing_errors.NewValidationError("nginx.ingress.kubernetes.io/auth-realm") + _, err := NewParser(dir, &mockSecret{}).Parse(ing) + if err.Error() != expected.Error() { + t.Errorf("expected '%v' but got '%v'", expected, err) + } +} + +func TestIngressInvalidDifferentNamespace(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "otherns/demo-secret" + ing.SetAnnotations(data) + + _, dir, _ := dummySecretContent(t) + defer os.RemoveAll(dir) + + expected := ing_errors.LocationDenied{ + Reason: errors.New("cross namespace usage of secrets is not allowed"), + } + _, err := NewParser(dir, &mockSecret{}).Parse(ing) + if err.Error() != expected.Error() { + t.Errorf("expected '%v' but got '%v'", expected, err) + } +} + +func TestIngressInvalidDifferentNamespaceAllowed(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "otherns/demo-secret" + ing.SetAnnotations(data) + + _, dir, _ := dummySecretContent(t) + defer os.RemoveAll(dir) + + r := mockSecret{} + r.AllowCrossNamespace = true + _, err := NewParser(dir, r).Parse(ing) + if err != nil { + t.Errorf("not expecting an error") + } +} + +func TestIngressInvalidSecretName(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret;xpto" + ing.SetAnnotations(data) + + _, dir, _ := dummySecretContent(t) + defer os.RemoveAll(dir) + + expected := ing_errors.LocationDenied{ + Reason: errors.New("error reading secret name from annotation: annotation nginx.ingress.kubernetes.io/auth-secret contains invalid value"), + } _, err := NewParser(dir, &mockSecret{}).Parse(ing) if err.Error() != expected.Error() { t.Errorf("expected '%v' but got '%v'", expected, err) @@ -123,7 +207,7 @@ func TestInvalidIngressAuthNoSecret(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-type")] = "basic" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -142,9 +226,9 @@ func TestIngressAuth(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-type")] = "basic" - data[parser.GetAnnotationWithPrefix("auth-secret")] = "demo-secret" - data[parser.GetAnnotationWithPrefix("auth-realm")] = "-realm-" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -173,9 +257,9 @@ func TestIngressAuthWithoutSecret(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-type")] = "basic" - data[parser.GetAnnotationWithPrefix("auth-secret")] = "invalid-secret" - data[parser.GetAnnotationWithPrefix("auth-realm")] = "-realm-" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "invalid-secret" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -191,10 +275,10 @@ func TestIngressAuthInvalidSecretKey(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-type")] = "basic" - data[parser.GetAnnotationWithPrefix("auth-secret")] = "demo-secret" - data[parser.GetAnnotationWithPrefix("auth-secret-type")] = "invalid-type" - data[parser.GetAnnotationWithPrefix("auth-realm")] = "-realm-" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" + data[parser.GetAnnotationWithPrefix(authSecretTypeAnnotation)] = "invalid-type" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) diff --git a/internal/ingress/annotations/authreq/main.go b/internal/ingress/annotations/authreq/main.go index 2ab389146..2ab98ace0 100644 --- a/internal/ingress/annotations/authreq/main.go +++ b/internal/ingress/annotations/authreq/main.go @@ -24,6 +24,7 @@ import ( "k8s.io/klog/v2" networking "k8s.io/api/networking/v1" + "k8s.io/client-go/tools/cache" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" @@ -31,6 +32,118 @@ import ( "k8s.io/ingress-nginx/pkg/util/sets" ) +const ( + authReqURLAnnotation = "auth-url" + authReqMethodAnnotation = "auth-method" + authReqSigninAnnotation = "auth-signin" + authReqSigninRedirParamAnnotation = "auth-signin-redirect-param" + authReqSnippetAnnotation = "auth-snippet" + authReqCacheKeyAnnotation = "auth-cache-key" + authReqKeepaliveAnnotation = "auth-keepalive" + authReqKeepaliveRequestsAnnotation = "auth-keepalive-requests" + authReqKeepaliveTimeout = "auth-keepalive-timeout" + authReqCacheDuration = "auth-cache-duration" + authReqResponseHeadersAnnotation = "auth-response-headers" + authReqProxySetHeadersAnnotation = "auth-proxy-set-headers" + authReqRequestRedirectAnnotation = "auth-request-redirect" + authReqAlwaysSetCookieAnnotation = "auth-always-set-cookie" + + // This should be exported as it is imported by other packages + AuthSecretAnnotation = "auth-secret" +) + +var authReqAnnotations = parser.Annotation{ + Group: "authentication", + Annotations: parser.AnnotationFields{ + authReqURLAnnotation: { + Validator: parser.ValidateRegex(*parser.URLWithNginxVariableRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation allows to indicate the URL where the HTTP request should be sent`, + }, + authReqMethodAnnotation: { + Validator: parser.ValidateRegex(*methodsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows to specify the HTTP method to use`, + }, + authReqSigninAnnotation: { + Validator: parser.ValidateRegex(*parser.URLWithNginxVariableRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation allows to specify the location of the error page`, + }, + authReqSigninRedirParamAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows to specify the URL parameter in the error page which should contain the original URL for a failed signin request`, + }, + authReqSnippetAnnotation: { + Validator: parser.ValidateNull, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskCritical, + Documentation: `This annotation allows to specify a custom snippet to use with external authentication`, + }, + authReqCacheKeyAnnotation: { + Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation enables caching for auth requests.`, + }, + authReqKeepaliveAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation specifies the maximum number of keepalive connections to auth-url. Only takes effect when no variables are used in the host part of the URL`, + }, + authReqKeepaliveRequestsAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines the maximum number of requests that can be served through one keepalive connection`, + }, + authReqKeepaliveTimeout: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation specifies a duration in seconds which an idle keepalive connection to an upstream server will stay open`, + }, + authReqCacheDuration: { + Validator: parser.ValidateRegex(*parser.ExtendedCharsRegex, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows to specify a caching time for auth responses based on their response codes, e.g. 200 202 30m`, + }, + authReqResponseHeadersAnnotation: { + Validator: parser.ValidateRegex(*parser.HeadersVariable, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation sets the headers to pass to backend once authentication request completes. They should be separated by comma.`, + }, + authReqProxySetHeadersAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation sets the name of a ConfigMap that specifies headers to pass to the authentication service. + Only ConfigMaps on the same namespace are allowed`, + }, + authReqRequestRedirectAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows to specify the X-Auth-Request-Redirect header value`, + }, + authReqAlwaysSetCookieAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables setting a cookie returned by auth request. + By default, the cookie will be set only if an upstream reports with the code 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308`, + }, + }, +} + // Config returns external authentication configuration for an Ingress rule type Config struct { URL string `json:"url"` @@ -121,7 +234,7 @@ func (e1 *Config) Equal(e2 *Config) bool { } var ( - methods = []string{"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "CONNECT", "OPTIONS", "TRACE"} + methodsRegex = regexp.MustCompile("(GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS|TRACE)") headerRegexp = regexp.MustCompile(`^[a-zA-Z\d\-_]+$`) statusCodeRegex = regexp.MustCompile(`^[\d]{3}$`) durationRegex = regexp.MustCompile(`^[\d]+(ms|s|m|h|d|w|M|y)$`) // see http://nginx.org/en/docs/syntax.html @@ -129,16 +242,7 @@ var ( // ValidMethod checks is the provided string a valid HTTP method func ValidMethod(method string) bool { - if len(method) == 0 { - return false - } - - for _, m := range methods { - if method == m { - return true - } - } - return false + return methodsRegex.MatchString(method) } // ValidHeader checks is the provided string satisfies the header's name regex @@ -173,19 +277,23 @@ func ValidCacheDuration(duration string) bool { } type authReq struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new authentication request annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return authReq{r} + return authReq{ + r: r, + annotationConfig: authReqAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress // rule used to use an Config URL as source for authentication func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { // Required Parameters - urlString, err := parser.GetStringAnnotation("auth-url", ing) + urlString, err := parser.GetStringAnnotation(authReqURLAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return nil, err } @@ -195,33 +303,44 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { return nil, ing_errors.LocationDenied{Reason: fmt.Errorf("could not parse auth-url annotation: %v", err)} } - authMethod, _ := parser.GetStringAnnotation("auth-method", ing) - if len(authMethod) != 0 && !ValidMethod(authMethod) { - return nil, ing_errors.NewLocationDenied("invalid HTTP method") + authMethod, err := parser.GetStringAnnotation(authReqMethodAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + if ing_errors.IsValidationError(err) { + return nil, ing_errors.NewLocationDenied("invalid HTTP method") + } } // Optional Parameters - signIn, err := parser.GetStringAnnotation("auth-signin", ing) + signIn, err := parser.GetStringAnnotation(authReqSigninAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + klog.Warningf("%s value is invalid: %s", authReqSigninAnnotation, err) + } klog.V(3).InfoS("auth-signin annotation is undefined and will not be set") } - signInRedirectParam, err := parser.GetStringAnnotation("auth-signin-redirect-param", ing) + signInRedirectParam, err := parser.GetStringAnnotation(authReqSigninRedirParamAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + klog.Warningf("%s value is invalid: %s", authReqSigninRedirParamAnnotation, err) + } klog.V(3).Infof("auth-signin-redirect-param annotation is undefined and will not be set") } - authSnippet, err := parser.GetStringAnnotation("auth-snippet", ing) + authSnippet, err := parser.GetStringAnnotation(authReqSnippetAnnotation, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("auth-snippet annotation is undefined and will not be set") } - authCacheKey, err := parser.GetStringAnnotation("auth-cache-key", ing) + authCacheKey, err := parser.GetStringAnnotation(authReqCacheKeyAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + klog.Warningf("%s value is invalid: %s", authReqCacheKeyAnnotation, err) + } klog.V(3).InfoS("auth-cache-key annotation is undefined and will not be set") } - keepaliveConnections, err := parser.GetIntAnnotation("auth-keepalive", ing) + keepaliveConnections, err := parser.GetIntAnnotation(authReqKeepaliveAnnotation, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("auth-keepalive annotation is undefined and will be set to its default value") keepaliveConnections = defaultKeepaliveConnections @@ -238,9 +357,9 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { } } - keepaliveRequests, err := parser.GetIntAnnotation("auth-keepalive-requests", ing) + keepaliveRequests, err := parser.GetIntAnnotation(authReqKeepaliveRequestsAnnotation, ing, a.annotationConfig.Annotations) if err != nil { - klog.V(3).InfoS("auth-keepalive-requests annotation is undefined and will be set to its default value") + klog.V(3).InfoS("auth-keepalive-requests annotation is undefined or invalid and will be set to its default value") keepaliveRequests = defaultKeepaliveRequests } if keepaliveRequests <= 0 { @@ -248,7 +367,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { keepaliveConnections = 0 } - keepaliveTimeout, err := parser.GetIntAnnotation("auth-keepalive-timeout", ing) + keepaliveTimeout, err := parser.GetIntAnnotation(authReqKeepaliveTimeout, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("auth-keepalive-timeout annotation is undefined and will be set to its default value") keepaliveTimeout = defaultKeepaliveTimeout @@ -258,14 +377,20 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { keepaliveConnections = 0 } - durstr, _ := parser.GetStringAnnotation("auth-cache-duration", ing) + durstr, err := parser.GetStringAnnotation(authReqCacheDuration, ing, a.annotationConfig.Annotations) + if err != nil && ing_errors.IsValidationError(err) { + return nil, fmt.Errorf("%s contains invalid value", authReqCacheDuration) + } authCacheDuration, err := ParseStringToCacheDurations(durstr) if err != nil { return nil, err } responseHeaders := []string{} - hstr, _ := parser.GetStringAnnotation("auth-response-headers", ing) + hstr, err := parser.GetStringAnnotation(authReqResponseHeadersAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && ing_errors.IsValidationError(err) { + return nil, ing_errors.NewLocationDenied("validation error") + } if len(hstr) != 0 { harr := strings.Split(hstr, ",") for _, header := range harr { @@ -279,9 +404,28 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { } } - proxySetHeaderMap, err := parser.GetStringAnnotation("auth-proxy-set-headers", ing) + proxySetHeaderMap, err := parser.GetStringAnnotation(authReqProxySetHeadersAnnotation, ing, a.annotationConfig.Annotations) if err != nil { - klog.V(3).InfoS("auth-set-proxy-headers annotation is undefined and will not be set") + klog.V(3).InfoS("auth-set-proxy-headers annotation is undefined and will not be set", "err", err) + } + + cns, _, err := cache.SplitMetaNamespaceKey(proxySetHeaderMap) + if err != nil { + return nil, ing_errors.LocationDenied{ + Reason: fmt.Errorf("error reading configmap name %s from annotation: %w", proxySetHeaderMap, err), + } + } + + if cns == "" { + cns = ing.Namespace + } + + secCfg := a.r.GetSecurityConfiguration() + // We don't accept different namespaces for secrets. + if !secCfg.AllowCrossNamespaceResources && cns != ing.Namespace { + return nil, ing_errors.LocationDenied{ + Reason: fmt.Errorf("cross namespace usage of secrets is not allowed"), + } } var proxySetHeaders map[string]string @@ -301,9 +445,15 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { proxySetHeaders = proxySetHeadersMapContents.Data } - requestRedirect, _ := parser.GetStringAnnotation("auth-request-redirect", ing) + requestRedirect, err := parser.GetStringAnnotation(authReqRequestRedirectAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && ing_errors.IsValidationError(err) { + return nil, fmt.Errorf("%s is invalid: %w", authReqRequestRedirectAnnotation, err) + } - alwaysSetCookie, _ := parser.GetBoolAnnotation("auth-always-set-cookie", ing) + alwaysSetCookie, err := parser.GetBoolAnnotation(authReqAlwaysSetCookieAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && ing_errors.IsValidationError(err) { + return nil, fmt.Errorf("%s is invalid: %w", authReqAlwaysSetCookieAnnotation, err) + } return &Config{ URL: urlString, @@ -348,3 +498,12 @@ func ParseStringToCacheDurations(input string) ([]string, error) { } return authCacheDuration, nil } + +func (a authReq) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a authReq) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, authReqAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/authreq/main_test.go b/internal/ingress/annotations/authreq/main_test.go index e1325235b..833bebe78 100644 --- a/internal/ingress/annotations/authreq/main_test.go +++ b/internal/ingress/annotations/authreq/main_test.go @@ -192,11 +192,13 @@ func TestHeaderAnnotations(t *testing.T) { i, err := NewParser(&resolver.Mock{}).Parse(ing) if test.expErr { if err == nil { - t.Error("expected error but retuned nil") + t.Errorf("%v expected error but retuned nil", test.title) } continue } - + if err != nil { + t.Errorf("no error was expected but %v happened in %s", err, test.title) + } u, ok := i.(*Config) if !ok { t.Errorf("%v: expected an External type", test.title) diff --git a/internal/ingress/annotations/authreqglobal/main.go b/internal/ingress/annotations/authreqglobal/main.go index 78dd7d6a5..a1641e085 100644 --- a/internal/ingress/annotations/authreqglobal/main.go +++ b/internal/ingress/annotations/authreqglobal/main.go @@ -23,23 +23,52 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + enableGlobalAuthAnnotation = "enable-global-auth" +) + +var globalAuthAnnotations = parser.Annotation{ + Group: "authentication", + Annotations: parser.AnnotationFields{ + enableGlobalAuthAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `Defines if the global external authentication should be enabled.`, + }, + }, +} + type authReqGlobal struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new authentication request annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return authReqGlobal{r} + return authReqGlobal{ + r: r, + annotationConfig: globalAuthAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress // rule used to enable or disable global external authentication func (a authReqGlobal) Parse(ing *networking.Ingress) (interface{}, error) { - enableGlobalAuth, err := parser.GetBoolAnnotation("enable-global-auth", ing) + enableGlobalAuth, err := parser.GetBoolAnnotation(enableGlobalAuthAnnotation, ing, a.annotationConfig.Annotations) if err != nil { enableGlobalAuth = true } return enableGlobalAuth, nil } + +func (a authReqGlobal) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a authReqGlobal) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, globalAuthAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/authtls/main.go b/internal/ingress/annotations/authtls/main.go index 2efd6d176..5d6763e8b 100644 --- a/internal/ingress/annotations/authtls/main.go +++ b/internal/ingress/annotations/authtls/main.go @@ -32,13 +32,64 @@ import ( const ( defaultAuthTLSDepth = 1 defaultAuthVerifyClient = "on" + + annotationAuthTLSSecret = "auth-tls-secret" //#nosec G101 + annotationAuthTLSVerifyClient = "auth-tls-verify-client" + annotationAuthTLSVerifyDepth = "auth-tls-verify-depth" + annotationAuthTLSErrorPage = "auth-tls-error-page" + annotationAuthTLSPassCertToUpstream = "auth-tls-pass-certificate-to-upstream" //#nosec G101 + annotationAuthTLSMatchCN = "auth-tls-match-cn" ) var ( + regexChars = regexp.QuoteMeta(`()|=`) authVerifyClientRegex = regexp.MustCompile(`on|off|optional|optional_no_ca`) - commonNameRegex = regexp.MustCompile(`CN=`) + commonNameRegex = regexp.MustCompile(`^CN=[/\-.\_\~a-zA-Z0-9` + regexChars + `]*$`) + redirectRegex = regexp.MustCompile(`^((https?://)?[A-Za-z0-9\-\.]*(:[0-9]+)?/[A-Za-z0-9\-\.]*)?$`) ) +var authTLSAnnotations = parser.Annotation{ + Group: "authentication", + Annotations: parser.AnnotationFields{ + annotationAuthTLSSecret: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars + Documentation: `This annotation defines the secret that contains the certificate chain of allowed certs`, + }, + annotationAuthTLSVerifyClient: { + Validator: parser.ValidateRegex(*authVerifyClientRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars + Documentation: `This annotation enables verification of client certificates. Can be "on", "off", "optional" or "optional_no_ca"`, + }, + annotationAuthTLSVerifyDepth: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines validation depth between the provided client certificate and the Certification Authority chain.`, + }, + annotationAuthTLSErrorPage: { + Validator: parser.ValidateRegex(*redirectRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation defines the URL/Page that user should be redirected in case of a Certificate Authentication Error`, + }, + annotationAuthTLSPassCertToUpstream: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if the received certificates should be passed or not to the upstream server in the header "ssl-client-cert"`, + }, + annotationAuthTLSMatchCN: { + Validator: parser.ValidateRegex(*commonNameRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation adds a sanity check for the CN of the client certificate that is sent over using a string / regex starting with "CN="`, + }, + }, +} + // Config contains the AuthSSLCert used for mutual authentication // and the configured ValidationDepth type Config struct { @@ -80,11 +131,15 @@ func (assl1 *Config) Equal(assl2 *Config) bool { // NewParser creates a new TLS authentication annotation parser func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { - return authTLS{resolver} + return authTLS{ + r: resolver, + annotationConfig: authTLSAnnotations, + } } type authTLS struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Parse parses the annotations contained in the ingress @@ -93,15 +148,23 @@ func (a authTLS) Parse(ing *networking.Ingress) (interface{}, error) { var err error config := &Config{} - tlsauthsecret, err := parser.GetStringAnnotation("auth-tls-secret", ing) + tlsauthsecret, err := parser.GetStringAnnotation(annotationAuthTLSSecret, ing, a.annotationConfig.Annotations) if err != nil { return &Config{}, err } - _, _, err = k8s.ParseNameNS(tlsauthsecret) + ns, _, err := k8s.ParseNameNS(tlsauthsecret) if err != nil { return &Config{}, ing_errors.NewLocationDenied(err.Error()) } + if ns == "" { + ns = ing.Namespace + } + secCfg := a.r.GetSecurityConfiguration() + // We don't accept different namespaces for secrets. + if !secCfg.AllowCrossNamespaceResources && ns != ing.Namespace { + return &Config{}, ing_errors.NewLocationDenied("cross namespace secrets are not supported") + } authCert, err := a.r.GetAuthCertificate(tlsauthsecret) if err != nil { @@ -110,30 +173,50 @@ func (a authTLS) Parse(ing *networking.Ingress) (interface{}, error) { } config.AuthSSLCert = *authCert - config.VerifyClient, err = parser.GetStringAnnotation("auth-tls-verify-client", ing) + config.VerifyClient, err = parser.GetStringAnnotation(annotationAuthTLSVerifyClient, ing, a.annotationConfig.Annotations) + // We can set a default value here in case of validation error if err != nil || !authVerifyClientRegex.MatchString(config.VerifyClient) { config.VerifyClient = defaultAuthVerifyClient } - config.ValidationDepth, err = parser.GetIntAnnotation("auth-tls-verify-depth", ing) + config.ValidationDepth, err = parser.GetIntAnnotation(annotationAuthTLSVerifyDepth, ing, a.annotationConfig.Annotations) + // We can set a default value here in case of validation error if err != nil || config.ValidationDepth == 0 { config.ValidationDepth = defaultAuthTLSDepth } - config.ErrorPage, err = parser.GetStringAnnotation("auth-tls-error-page", ing) + config.ErrorPage, err = parser.GetStringAnnotation(annotationAuthTLSErrorPage, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + return &Config{}, err + } config.ErrorPage = "" } - config.PassCertToUpstream, err = parser.GetBoolAnnotation("auth-tls-pass-certificate-to-upstream", ing) + config.PassCertToUpstream, err = parser.GetBoolAnnotation(annotationAuthTLSPassCertToUpstream, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + return &Config{}, err + } config.PassCertToUpstream = false } - config.MatchCN, err = parser.GetStringAnnotation("auth-tls-match-cn", ing) - if err != nil || !commonNameRegex.MatchString(config.MatchCN) { + config.MatchCN, err = parser.GetStringAnnotation(annotationAuthTLSMatchCN, ing, a.annotationConfig.Annotations) + if err != nil { + if ing_errors.IsValidationError(err) { + return &Config{}, err + } config.MatchCN = "" } return config, nil } + +func (a authTLS) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a authTLS) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, authTLSAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/authtls/main_test.go b/internal/ingress/annotations/authtls/main_test.go index 569f3865b..a1f3f0f92 100644 --- a/internal/ingress/annotations/authtls/main_test.go +++ b/internal/ingress/annotations/authtls/main_test.go @@ -93,7 +93,7 @@ func TestAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("auth-tls-secret")] = "default/demo-secret" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "default/demo-secret" ing.SetAnnotations(data) @@ -132,11 +132,11 @@ func TestAnnotations(t *testing.T) { t.Errorf("expected empty string, but got %v", u.MatchCN) } - data[parser.GetAnnotationWithPrefix("auth-tls-verify-client")] = "off" - data[parser.GetAnnotationWithPrefix("auth-tls-verify-depth")] = "2" - data[parser.GetAnnotationWithPrefix("auth-tls-error-page")] = "ok.com/error" - data[parser.GetAnnotationWithPrefix("auth-tls-pass-certificate-to-upstream")] = "true" - data[parser.GetAnnotationWithPrefix("auth-tls-match-cn")] = "CN=hello-app" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyClient)] = "off" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyDepth)] = "2" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSErrorPage)] = "ok.com/error" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSPassCertToUpstream)] = "true" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSMatchCN)] = "CN=(hello-app|ok|goodbye)" ing.SetAnnotations(data) @@ -165,8 +165,8 @@ func TestAnnotations(t *testing.T) { if u.PassCertToUpstream != true { t.Errorf("expected %v but got %v", true, u.PassCertToUpstream) } - if u.MatchCN != "CN=hello-app" { - t.Errorf("expected %v but got %v", "CN=hello-app", u.MatchCN) + if u.MatchCN != "CN=(hello-app|ok|goodbye)" { + t.Errorf("expected %v but got %v", "CN=(hello-app|ok|goodbye)", u.MatchCN) } } @@ -182,15 +182,24 @@ func TestInvalidAnnotations(t *testing.T) { } // Invalid NameSpace - data[parser.GetAnnotationWithPrefix("auth-tls-secret")] = "demo-secret" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "demo-secret" ing.SetAnnotations(data) _, err = NewParser(fakeSecret).Parse(ing) if err == nil { t.Errorf("Expected error with ingress but got nil") } + // Invalid Cross NameSpace + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "nondefault/demo-secret" + ing.SetAnnotations(data) + _, err = NewParser(fakeSecret).Parse(ing) + expErr := errors.NewLocationDenied("cross namespace secrets are not supported") + if err.Error() != expErr.Error() { + t.Errorf("received error is different from cross namespace error: %s Expected %s", err, expErr) + } + // Invalid Auth Certificate - data[parser.GetAnnotationWithPrefix("auth-tls-secret")] = "default/invalid-demo-secret" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "default/invalid-demo-secret" ing.SetAnnotations(data) _, err = NewParser(fakeSecret).Parse(ing) if err == nil { @@ -198,11 +207,38 @@ func TestInvalidAnnotations(t *testing.T) { } // Invalid optional Annotations - data[parser.GetAnnotationWithPrefix("auth-tls-secret")] = "default/demo-secret" - data[parser.GetAnnotationWithPrefix("auth-tls-verify-client")] = "w00t" - data[parser.GetAnnotationWithPrefix("auth-tls-verify-depth")] = "abcd" - data[parser.GetAnnotationWithPrefix("auth-tls-pass-certificate-to-upstream")] = "nahh" - data[parser.GetAnnotationWithPrefix("auth-tls-match-cn")] = "" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "default/demo-secret" + + data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyClient)] = "w00t" + ing.SetAnnotations(data) + _, err = NewParser(fakeSecret).Parse(ing) + if err != nil { + t.Errorf("Error should be nil and verify client should be defaulted") + } + + data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyDepth)] = "abcd" + ing.SetAnnotations(data) + _, err = NewParser(fakeSecret).Parse(ing) + if err != nil { + t.Errorf("Error should be nil and verify depth should be defaulted") + } + + data[parser.GetAnnotationWithPrefix(annotationAuthTLSPassCertToUpstream)] = "nahh" + ing.SetAnnotations(data) + _, err = NewParser(fakeSecret).Parse(ing) + if err == nil { + t.Errorf("Expected error with ingress but got nil") + } + delete(data, parser.GetAnnotationWithPrefix(annotationAuthTLSPassCertToUpstream)) + + data[parser.GetAnnotationWithPrefix(annotationAuthTLSMatchCN)] = "" + ing.SetAnnotations(data) + _, err = NewParser(fakeSecret).Parse(ing) + if err == nil { + t.Errorf("Expected error with ingress CN but got nil") + } + delete(data, parser.GetAnnotationWithPrefix(annotationAuthTLSMatchCN)) + ing.SetAnnotations(data) i, err := NewParser(fakeSecret).Parse(ing) diff --git a/internal/ingress/annotations/backendprotocol/main.go b/internal/ingress/annotations/backendprotocol/main.go index c749072e3..2704ce9f6 100644 --- a/internal/ingress/annotations/backendprotocol/main.go +++ b/internal/ingress/annotations/backendprotocol/main.go @@ -17,49 +17,72 @@ limitations under the License. package backendprotocol import ( - "regexp" - "strings" - networking "k8s.io/api/networking/v1" "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) -// HTTP protocol -const HTTP = "HTTP" - var ( - validProtocols = regexp.MustCompile(`^(AUTO_HTTP|HTTP|HTTPS|GRPC|GRPCS|FCGI)$`) + validProtocols = []string{"auto_http", "http", "https", "grpc", "grpcs", "fcgi"} ) +const ( + http = "HTTP" + backendProtocolAnnotation = "backend-protocol" +) + +var backendProtocolConfig = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + backendProtocolAnnotation: { + Validator: parser.ValidateOptions(validProtocols, false, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `this annotation can be used to define which protocol should + be used to communicate with backends`, + }, + }, +} + type backendProtocol struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new backend protocol annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return backendProtocol{r} + return backendProtocol{ + r: r, + annotationConfig: backendProtocolConfig, + } +} + +func (a backendProtocol) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations } // ParseAnnotations parses the annotations contained in the ingress // rule used to indicate the backend protocol. func (a backendProtocol) Parse(ing *networking.Ingress) (interface{}, error) { if ing.GetAnnotations() == nil { - return HTTP, nil + return http, nil } - proto, err := parser.GetStringAnnotation("backend-protocol", ing) + proto, err := parser.GetStringAnnotation(backendProtocolAnnotation, ing, a.annotationConfig.Annotations) if err != nil { - return HTTP, nil - } - - proto = strings.TrimSpace(strings.ToUpper(proto)) - if !validProtocols.MatchString(proto) { - klog.Warningf("Protocol %v is not a valid value for the backend-protocol annotation. Using HTTP as protocol", proto) - return HTTP, nil + if errors.IsValidationError(err) { + klog.Warningf("validation error %s. Using HTTP as protocol", err) + } + return http, nil } return proto, nil } + +func (a backendProtocol) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, backendProtocolConfig.Annotations) +} diff --git a/internal/ingress/annotations/backendprotocol/main_test.go b/internal/ingress/annotations/backendprotocol/main_test.go index e8c018998..490be447b 100644 --- a/internal/ingress/annotations/backendprotocol/main_test.go +++ b/internal/ingress/annotations/backendprotocol/main_test.go @@ -77,7 +77,7 @@ func TestParseInvalidAnnotations(t *testing.T) { } // Test invalid annotation set - data[parser.GetAnnotationWithPrefix("backend-protocol")] = "INVALID" + data[parser.GetAnnotationWithPrefix(backendProtocolAnnotation)] = "INVALID" ing.SetAnnotations(data) i, err = NewParser(&resolver.Mock{}).Parse(ing) @@ -97,7 +97,7 @@ func TestParseAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("backend-protocol")] = "HTTPS" + data[parser.GetAnnotationWithPrefix(backendProtocolAnnotation)] = " HTTPS " ing.SetAnnotations(data) i, err := NewParser(&resolver.Mock{}).Parse(ing) diff --git a/internal/ingress/annotations/canary/main.go b/internal/ingress/annotations/canary/main.go index d9e53b3b8..119f09181 100644 --- a/internal/ingress/annotations/canary/main.go +++ b/internal/ingress/annotations/canary/main.go @@ -18,14 +18,82 @@ package canary import ( networking "k8s.io/api/networking/v1" + "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + canaryAnnotation = "canary" + canaryWeightAnnotation = "canary-weight" + canaryWeightTotalAnnotation = "canary-weight-total" + canaryByHeaderAnnotation = "canary-by-header" + canaryByHeaderValueAnnotation = "canary-by-header-value" + canaryByHeaderPatternAnnotation = "canary-by-header-pattern" + canaryByCookieAnnotation = "canary-by-cookie" +) + +var CanaryAnnotations = parser.Annotation{ + Group: "canary", + Annotations: parser.AnnotationFields{ + canaryAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables the Ingress spec to act as an alternative service for requests to route to depending on the rules applied`, + }, + canaryWeightAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines the integer based (0 - ) percent of random requests that should be routed to the service specified in the canary Ingress`, + }, + canaryWeightTotalAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation The total weight of traffic. If unspecified, it defaults to 100`, + }, + canaryByHeaderAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the header that should be used for notifying the Ingress to route the request to the service specified in the Canary Ingress. + When the request header is set to 'always', it will be routed to the canary. When the header is set to 'never', it will never be routed to the canary. + For any other value, the header will be ignored and the request compared against the other canary rules by precedence`, + }, + canaryByHeaderValueAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the header value to match for notifying the Ingress to route the request to the service specified in the Canary Ingress. + When the request header is set to this value, it will be routed to the canary. For any other header value, the header will be ignored and the request compared against the other canary rules by precedence. + This annotation has to be used together with 'canary-by-header'. The annotation is an extension of the 'canary-by-header' to allow customizing the header value instead of using hardcoded values. + It doesn't have any effect if the 'canary-by-header' annotation is not defined`, + }, + canaryByHeaderPatternAnnotation: { + Validator: parser.ValidateRegex(*parser.IsValidRegex, false), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation works the same way as canary-by-header-value except it does PCRE Regex matching. + Note that when 'canary-by-header-value' is set this annotation will be ignored. + When the given Regex causes error during request processing, the request will be considered as not matching.`, + }, + canaryByCookieAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the cookie that should be used for notifying the Ingress to route the request to the service specified in the Canary Ingress. + When the cookie is set to 'always', it will be routed to the canary. When the cookie is set to 'never', it will never be routed to the canary`, + }, + }, +} + type canary struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config returns the configuration rules for setting up the Canary @@ -41,7 +109,10 @@ type Config struct { // NewParser parses the ingress for canary related annotations func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return canary{r} + return canary{ + r: r, + annotationConfig: CanaryAnnotations, + } } // Parse parses the annotations contained in the ingress @@ -50,45 +121,75 @@ func (c canary) Parse(ing *networking.Ingress) (interface{}, error) { config := &Config{} var err error - config.Enabled, err = parser.GetBoolAnnotation("canary", ing) + config.Enabled, err = parser.GetBoolAnnotation(canaryAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to 'false'", canaryAnnotation) + } config.Enabled = false } - config.Weight, err = parser.GetIntAnnotation("canary-weight", ing) + config.Weight, err = parser.GetIntAnnotation(canaryWeightAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to '0'", canaryWeightAnnotation) + } config.Weight = 0 } - config.WeightTotal, err = parser.GetIntAnnotation("canary-weight-total", ing) + config.WeightTotal, err = parser.GetIntAnnotation(canaryWeightTotalAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to '100'", canaryWeightTotalAnnotation) + } config.WeightTotal = 100 } - config.Header, err = parser.GetStringAnnotation("canary-by-header", ing) + config.Header, err = parser.GetStringAnnotation(canaryByHeaderAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to ''", canaryByHeaderAnnotation) + } config.Header = "" } - config.HeaderValue, err = parser.GetStringAnnotation("canary-by-header-value", ing) + config.HeaderValue, err = parser.GetStringAnnotation(canaryByHeaderValueAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to ''", canaryByHeaderValueAnnotation) + } config.HeaderValue = "" } - config.HeaderPattern, err = parser.GetStringAnnotation("canary-by-header-pattern", ing) + config.HeaderPattern, err = parser.GetStringAnnotation(canaryByHeaderPatternAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to ''", canaryByHeaderPatternAnnotation) + } config.HeaderPattern = "" } - config.Cookie, err = parser.GetStringAnnotation("canary-by-cookie", ing) + config.Cookie, err = parser.GetStringAnnotation(canaryByCookieAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%s is invalid, defaulting to ''", canaryByCookieAnnotation) + } config.Cookie = "" } if !config.Enabled && (config.Weight > 0 || len(config.Header) > 0 || len(config.HeaderValue) > 0 || len(config.Cookie) > 0 || len(config.HeaderPattern) > 0) { - return nil, errors.NewInvalidAnnotationConfiguration("canary", "configured but not enabled") + return nil, errors.NewInvalidAnnotationConfiguration(canaryAnnotation, "configured but not enabled") } return config, nil } + +func (c canary) GetDocumentation() parser.AnnotationFields { + return c.annotationConfig.Annotations +} + +func (a canary) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, CanaryAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/clientbodybuffersize/main.go b/internal/ingress/annotations/clientbodybuffersize/main.go index 9020ee594..aa1485df2 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main.go +++ b/internal/ingress/annotations/clientbodybuffersize/main.go @@ -23,17 +23,49 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + clientBodyBufferSizeAnnotation = "client-body-buffer-size" +) + +var clientBodyBufferSizeConfig = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + clientBodyBufferSizeAnnotation: { + Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Sets buffer size for reading client request body per location. + In case the request body is larger than the buffer, the whole body or only its part is written to a temporary file. + By default, buffer size is equal to two memory pages. This is 8K on x86, other 32-bit platforms, and x86-64. + It is usually 16K on other 64-bit platforms. This annotation is applied to each location provided in the ingress rule.`, + }, + }, +} + type clientBodyBufferSize struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new clientBodyBufferSize annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return clientBodyBufferSize{r} + return clientBodyBufferSize{ + r: r, + annotationConfig: clientBodyBufferSizeConfig, + } +} + +func (cbbs clientBodyBufferSize) GetDocumentation() parser.AnnotationFields { + return cbbs.annotationConfig.Annotations } // Parse parses the annotations contained in the ingress rule // used to add an client-body-buffer-size to the provided locations func (cbbs clientBodyBufferSize) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("client-body-buffer-size", ing) + return parser.GetStringAnnotation(clientBodyBufferSizeAnnotation, ing, cbbs.annotationConfig.Annotations) +} + +func (a clientBodyBufferSize) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, clientBodyBufferSizeConfig.Annotations) } diff --git a/internal/ingress/annotations/clientbodybuffersize/main_test.go b/internal/ingress/annotations/clientbodybuffersize/main_test.go index 9932f8314..0f2c8474a 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main_test.go +++ b/internal/ingress/annotations/clientbodybuffersize/main_test.go @@ -39,6 +39,9 @@ func TestParse(t *testing.T) { }{ {map[string]string{annotation: "8k"}, "8k"}, {map[string]string{annotation: "16k"}, "16k"}, + {map[string]string{annotation: "10000"}, "10000"}, + {map[string]string{annotation: "16R"}, ""}, + {map[string]string{annotation: "16kkk"}, ""}, {map[string]string{annotation: ""}, ""}, {map[string]string{}, ""}, {nil, ""}, diff --git a/internal/ingress/annotations/connection/main.go b/internal/ingress/annotations/connection/main.go index e9b0c1865..9e96b6ab1 100644 --- a/internal/ingress/annotations/connection/main.go +++ b/internal/ingress/annotations/connection/main.go @@ -17,12 +17,34 @@ limitations under the License. package connection import ( + "regexp" + networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + connectionProxyHeaderAnnotation = "connection-proxy-header" +) + +var ( + validConnectionHeaderValue = regexp.MustCompile(`^(close|keep-alive)$`) +) + +var connectionHeadersAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + connectionProxyHeaderAnnotation: { + Validator: parser.ValidateRegex(*validConnectionHeaderValue, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows setting a specific value for "proxy_set_header Connection" directive. Right now it is restricted to "close" or "keep-alive"`, + }, + }, +} + // Config returns the connection header configuration for an Ingress rule type Config struct { Header string `json:"header"` @@ -30,18 +52,22 @@ type Config struct { } type connection struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new port in redirect annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return connection{r} + return connection{ + r: r, + annotationConfig: connectionHeadersAnnotations, + } } // Parse parses the annotations contained in the ingress // rule used to indicate if the connection header should be overridden. func (a connection) Parse(ing *networking.Ingress) (interface{}, error) { - cp, err := parser.GetStringAnnotation("connection-proxy-header", ing) + cp, err := parser.GetStringAnnotation(connectionProxyHeaderAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return &Config{ Enabled: false, @@ -70,3 +96,12 @@ func (r1 *Config) Equal(r2 *Config) bool { return true } + +func (a connection) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a connection) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, connectionHeadersAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/connection/main_test.go b/internal/ingress/annotations/connection/main_test.go index 011a2948c..a95288385 100644 --- a/internal/ingress/annotations/connection/main_test.go +++ b/internal/ingress/annotations/connection/main_test.go @@ -37,10 +37,12 @@ func TestParse(t *testing.T) { testCases := []struct { annotations map[string]string expected *Config + expectErr bool }{ - {map[string]string{annotation: "keep-alive"}, &Config{Enabled: true, Header: "keep-alive"}}, - {map[string]string{}, &Config{Enabled: false}}, - {nil, &Config{Enabled: false}}, + {map[string]string{annotation: "keep-alive"}, &Config{Enabled: true, Header: "keep-alive"}, false}, + {map[string]string{annotation: "not-allowed-value"}, &Config{Enabled: false}, true}, + {map[string]string{}, &Config{Enabled: false}, true}, + {nil, &Config{Enabled: false}, true}, } ing := &networking.Ingress{ @@ -53,11 +55,17 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - i, _ := ap.Parse(ing) - p, _ := i.(*Config) - + i, err := ap.Parse(ing) + if (err != nil) != testCase.expectErr { + t.Fatalf("expected error: %t got error: %t err value: %s. %+v", testCase.expectErr, err != nil, err, testCase.annotations) + } + p, ok := i.(*Config) + if !ok { + t.Fatalf("expected a Config type") + } if !p.Equal(testCase.expected) { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, p, testCase.annotations) } + } } diff --git a/internal/ingress/annotations/cors/main.go b/internal/ingress/annotations/cors/main.go index 3888f2909..cc30b8405 100644 --- a/internal/ingress/annotations/cors/main.go +++ b/internal/ingress/annotations/cors/main.go @@ -24,6 +24,7 @@ import ( "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) @@ -38,20 +39,87 @@ var ( // Regex are defined here to prevent information leak, if user tries to set anything not valid // that could cause the Response to contain some internal value/variable (like returning $pid, $upstream_addr, etc) // Origin must contain a http/s Origin (including or not the port) or the value '*' + // This Regex is composed of the following: + // * Sets a group that can be (https?://)?*?.something.com:port? + // * Allows this to be repeated as much as possible, and separated by comma + // Otherwise it should be '*' + corsOriginRegexValidator = regexp.MustCompile(`^((((https?://)?(\*\.)?[A-Za-z0-9\-\.]*(:[0-9]+)?,?)+)|\*)?$`) + // corsOriginRegex defines the regex for validation inside Parse corsOriginRegex = regexp.MustCompile(`^(https?://(\*\.)?[A-Za-z0-9\-\.]*(:[0-9]+)?|\*)?$`) // Method must contain valid methods list (PUT, GET, POST, BLA) // May contain or not spaces between each verb corsMethodsRegex = regexp.MustCompile(`^([A-Za-z]+,?\s?)+$`) - // Headers must contain valid values only (X-HEADER12, X-ABC) - // May contain or not spaces between each Header - corsHeadersRegex = regexp.MustCompile(`^([A-Za-z0-9\-\_]+,?\s?)+$`) // Expose Headers must contain valid values only (*, X-HEADER12, X-ABC) // May contain or not spaces between each Header corsExposeHeadersRegex = regexp.MustCompile(`^(([A-Za-z0-9\-\_]+|\*),?\s?)+$`) ) +const ( + corsEnableAnnotation = "enable-cors" + corsAllowOriginAnnotation = "cors-allow-origin" + corsAllowHeadersAnnotation = "cors-allow-headers" + corsAllowMethodsAnnotation = "cors-allow-methods" + corsAllowCredentialsAnnotation = "cors-allow-credentials" //#nosec G101 + corsExposeHeadersAnnotation = "cors-expose-headers" + corsMaxAgeAnnotation = "cors-max-age" +) + +var corsAnnotation = parser.Annotation{ + Group: "cors", + Annotations: parser.AnnotationFields{ + corsEnableAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables Cross-Origin Resource Sharing (CORS) in an Ingress rule`, + }, + corsAllowOriginAnnotation: { + Validator: parser.ValidateRegex(*corsOriginRegexValidator, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation controls what's the accepted Origin for CORS. + This is a multi-valued field, separated by ','. It must follow this format: http(s)://origin-site.com or http(s)://origin-site.com:port + It also supports single level wildcard subdomains and follows this format: http(s)://*.foo.bar, http(s)://*.bar.foo:8080 or http(s)://*.abc.bar.foo:9000`, + }, + corsAllowHeadersAnnotation: { + Validator: parser.ValidateRegex(*parser.HeadersVariable, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation controls which headers are accepted. + This is a multi-valued field, separated by ',' and accepts letters, numbers, _ and -`, + }, + corsAllowMethodsAnnotation: { + Validator: parser.ValidateRegex(*corsMethodsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation controls which methods are accepted. + This is a multi-valued field, separated by ',' and accepts only letters (upper and lower case)`, + }, + corsAllowCredentialsAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation controls if credentials can be passed during CORS operations.`, + }, + corsExposeHeadersAnnotation: { + Validator: parser.ValidateRegex(*corsExposeHeadersRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation controls which headers are exposed to response. + This is a multi-valued field, separated by ',' and accepts letters, numbers, _, - and *.`, + }, + corsMaxAgeAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation controls how long, in seconds, preflight requests can be cached.`, + }, + }, +} + type cors struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the Cors configuration to be used in the Ingress @@ -67,7 +135,10 @@ type Config struct { // NewParser creates a new CORS annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return cors{r} + return cors{ + r: r, + annotationConfig: corsAnnotation, + } } // Equal tests for equality between two External types @@ -116,13 +187,16 @@ func (c cors) Parse(ing *networking.Ingress) (interface{}, error) { var err error config := &Config{} - config.CorsEnabled, err = parser.GetBoolAnnotation("enable-cors", ing) + config.CorsEnabled, err = parser.GetBoolAnnotation(corsEnableAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("enable-cors is invalid, defaulting to 'false'") + } config.CorsEnabled = false } config.CorsAllowOrigin = []string{} - unparsedOrigins, err := parser.GetStringAnnotation("cors-allow-origin", ing) + unparsedOrigins, err := parser.GetStringAnnotation(corsAllowOriginAnnotation, ing, c.annotationConfig.Annotations) if err == nil { origins := strings.Split(unparsedOrigins, ",") for _, origin := range origins { @@ -140,33 +214,53 @@ func (c cors) Parse(ing *networking.Ingress) (interface{}, error) { klog.Infof("Current config.corsAllowOrigin %v", config.CorsAllowOrigin) } } else { + if errors.IsValidationError(err) { + klog.Warningf("cors-allow-origin is invalid, defaulting to '*'") + } config.CorsAllowOrigin = []string{"*"} } - config.CorsAllowHeaders, err = parser.GetStringAnnotation("cors-allow-headers", ing) - if err != nil || !corsHeadersRegex.MatchString(config.CorsAllowHeaders) { + config.CorsAllowHeaders, err = parser.GetStringAnnotation(corsAllowHeadersAnnotation, ing, c.annotationConfig.Annotations) + if err != nil || !parser.HeadersVariable.MatchString(config.CorsAllowHeaders) { config.CorsAllowHeaders = defaultCorsHeaders } - config.CorsAllowMethods, err = parser.GetStringAnnotation("cors-allow-methods", ing) + config.CorsAllowMethods, err = parser.GetStringAnnotation(corsAllowMethodsAnnotation, ing, c.annotationConfig.Annotations) if err != nil || !corsMethodsRegex.MatchString(config.CorsAllowMethods) { config.CorsAllowMethods = defaultCorsMethods } - config.CorsAllowCredentials, err = parser.GetBoolAnnotation("cors-allow-credentials", ing) + config.CorsAllowCredentials, err = parser.GetBoolAnnotation(corsAllowCredentialsAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + if errors.IsValidationError(err) { + klog.Warningf("cors-allow-credentials is invalid, defaulting to 'true'") + } + } config.CorsAllowCredentials = true } - config.CorsExposeHeaders, err = parser.GetStringAnnotation("cors-expose-headers", ing) + config.CorsExposeHeaders, err = parser.GetStringAnnotation(corsExposeHeadersAnnotation, ing, c.annotationConfig.Annotations) if err != nil || !corsExposeHeadersRegex.MatchString(config.CorsExposeHeaders) { config.CorsExposeHeaders = "" } - config.CorsMaxAge, err = parser.GetIntAnnotation("cors-max-age", ing) + config.CorsMaxAge, err = parser.GetIntAnnotation(corsMaxAgeAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("cors-max-age is invalid, defaulting to %d", defaultCorsMaxAge) + } config.CorsMaxAge = defaultCorsMaxAge } return config, nil } + +func (c cors) GetDocumentation() parser.AnnotationFields { + return c.annotationConfig.Annotations +} + +func (a cors) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, corsAnnotation.Annotations) +} diff --git a/internal/ingress/annotations/cors/main_test.go b/internal/ingress/annotations/cors/main_test.go index 086a59d89..d371d183b 100644 --- a/internal/ingress/annotations/cors/main_test.go +++ b/internal/ingress/annotations/cors/main_test.go @@ -75,13 +75,13 @@ func TestIngressCorsConfigValid(t *testing.T) { data := map[string]string{} // Valid - data[parser.GetAnnotationWithPrefix("enable-cors")] = "true" - data[parser.GetAnnotationWithPrefix("cors-allow-headers")] = "DNT,X-CustomHeader, Keep-Alive,User-Agent" - data[parser.GetAnnotationWithPrefix("cors-allow-credentials")] = "false" - data[parser.GetAnnotationWithPrefix("cors-allow-methods")] = "GET, PATCH" - data[parser.GetAnnotationWithPrefix("cors-allow-origin")] = "https://origin123.test.com:4443" - data[parser.GetAnnotationWithPrefix("cors-expose-headers")] = "*, X-CustomResponseHeader" - data[parser.GetAnnotationWithPrefix("cors-max-age")] = "600" + data[parser.GetAnnotationWithPrefix(corsEnableAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(corsAllowHeadersAnnotation)] = "DNT,X-CustomHeader, Keep-Alive,User-Agent" + data[parser.GetAnnotationWithPrefix(corsAllowCredentialsAnnotation)] = "false" + data[parser.GetAnnotationWithPrefix(corsAllowMethodsAnnotation)] = "GET, PATCH" + data[parser.GetAnnotationWithPrefix(corsAllowOriginAnnotation)] = "https://origin123.test.com:4443" + data[parser.GetAnnotationWithPrefix(corsExposeHeadersAnnotation)] = "*, X-CustomResponseHeader" + data[parser.GetAnnotationWithPrefix(corsMaxAgeAnnotation)] = "600" ing.SetAnnotations(data) corst, err := NewParser(&resolver.Mock{}).Parse(ing) @@ -95,31 +95,31 @@ func TestIngressCorsConfigValid(t *testing.T) { } if !nginxCors.CorsEnabled { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("enable-cors")], nginxCors.CorsEnabled) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsEnableAnnotation)], nginxCors.CorsEnabled) } if nginxCors.CorsAllowCredentials { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-allow-credentials")], nginxCors.CorsAllowCredentials) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsAllowCredentialsAnnotation)], nginxCors.CorsAllowCredentials) } if nginxCors.CorsAllowHeaders != "DNT,X-CustomHeader, Keep-Alive,User-Agent" { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-allow-headers")], nginxCors.CorsAllowHeaders) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsAllowHeadersAnnotation)], nginxCors.CorsAllowHeaders) } if nginxCors.CorsAllowMethods != "GET, PATCH" { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-allow-methods")], nginxCors.CorsAllowMethods) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsAllowMethodsAnnotation)], nginxCors.CorsAllowMethods) } if nginxCors.CorsAllowOrigin[0] != "https://origin123.test.com:4443" { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-allow-origin")], nginxCors.CorsAllowOrigin) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsAllowOriginAnnotation)], nginxCors.CorsAllowOrigin) } if nginxCors.CorsExposeHeaders != "*, X-CustomResponseHeader" { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-expose-headers")], nginxCors.CorsExposeHeaders) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsExposeHeadersAnnotation)], nginxCors.CorsExposeHeaders) } if nginxCors.CorsMaxAge != 600 { - t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix("cors-max-age")], nginxCors.CorsMaxAge) + t.Errorf("expected %v but returned %v", data[parser.GetAnnotationWithPrefix(corsMaxAgeAnnotation)], nginxCors.CorsMaxAge) } } @@ -129,13 +129,13 @@ func TestIngressCorsConfigInvalid(t *testing.T) { data := map[string]string{} // Valid - data[parser.GetAnnotationWithPrefix("enable-cors")] = "yes" - data[parser.GetAnnotationWithPrefix("cors-allow-headers")] = "@alright, #ingress" - data[parser.GetAnnotationWithPrefix("cors-allow-credentials")] = "no" - data[parser.GetAnnotationWithPrefix("cors-allow-methods")] = "GET, PATCH, $nginx" - data[parser.GetAnnotationWithPrefix("cors-allow-origin")] = "origin123.test.com:4443" - data[parser.GetAnnotationWithPrefix("cors-expose-headers")] = "@alright, #ingress" - data[parser.GetAnnotationWithPrefix("cors-max-age")] = "abcd" + data[parser.GetAnnotationWithPrefix(corsEnableAnnotation)] = "yes" + data[parser.GetAnnotationWithPrefix(corsAllowHeadersAnnotation)] = "@alright, #ingress" + data[parser.GetAnnotationWithPrefix(corsAllowCredentialsAnnotation)] = "no" + data[parser.GetAnnotationWithPrefix(corsAllowMethodsAnnotation)] = "GET, PATCH, $nginx" + data[parser.GetAnnotationWithPrefix(corsAllowOriginAnnotation)] = "origin123.test.com:4443" + data[parser.GetAnnotationWithPrefix(corsExposeHeadersAnnotation)] = "@alright, #ingress" + data[parser.GetAnnotationWithPrefix(corsMaxAgeAnnotation)] = "abcd" ing.SetAnnotations(data) corst, err := NewParser(&resolver.Mock{}).Parse(ing) diff --git a/internal/ingress/annotations/customhttperrors/main.go b/internal/ingress/annotations/customhttperrors/main.go index a05fb16c8..c3c9b5be3 100644 --- a/internal/ingress/annotations/customhttperrors/main.go +++ b/internal/ingress/annotations/customhttperrors/main.go @@ -17,6 +17,7 @@ limitations under the License. package customhttperrors import ( + "regexp" "strconv" "strings" @@ -26,19 +27,46 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + customHTTPErrorsAnnotation = "custom-http-errors" +) + +var ( + // We accept anything between 400 and 599, on a comma separated. + arrayOfHTTPErrors = regexp.MustCompile(`^(?:[4,5][0-9][0-9],?)*$`) +) + +var customHTTPErrorsAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + customHTTPErrorsAnnotation: { + Validator: parser.ValidateRegex(*arrayOfHTTPErrors, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `If a default backend annotation is specified on the ingress, the errors code specified on this annotation + will be routed to that annotation's default backend service. Otherwise they will be routed to the global default backend. + A comma-separated list of error codes is accepted (anything between 400 and 599, like 403, 503)`, + }, + }, +} + type customhttperrors struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new custom http errors annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return customhttperrors{r} + return customhttperrors{ + r: r, + annotationConfig: customHTTPErrorsAnnotations, + } } // Parse parses the annotations contained in the ingress to use // custom http errors func (e customhttperrors) Parse(ing *networking.Ingress) (interface{}, error) { - c, err := parser.GetStringAnnotation("custom-http-errors", ing) + c, err := parser.GetStringAnnotation(customHTTPErrorsAnnotation, ing, e.annotationConfig.Annotations) if err != nil { return nil, err } @@ -55,3 +83,12 @@ func (e customhttperrors) Parse(ing *networking.Ingress) (interface{}, error) { return codes, nil } + +func (e customhttperrors) GetDocumentation() parser.AnnotationFields { + return e.annotationConfig.Annotations +} + +func (a customhttperrors) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, customHTTPErrorsAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/defaultbackend/main.go b/internal/ingress/annotations/defaultbackend/main.go index b1685015e..f3ca004dd 100644 --- a/internal/ingress/annotations/defaultbackend/main.go +++ b/internal/ingress/annotations/defaultbackend/main.go @@ -25,19 +25,40 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + defaultBackendAnnotation = "default-backend" +) + +var defaultBackendAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + defaultBackendAnnotation: { + Validator: parser.ValidateServiceName, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This service will be used to handle the response when the configured service in the Ingress rule does not have any active endpoints. + It will also be used to handle the error responses if both this annotation and the custom-http-errors annotation are set.`, + }, + }, +} + type backend struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new default backend annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return backend{r} + return backend{ + r: r, + annotationConfig: defaultBackendAnnotations, + } } // Parse parses the annotations contained in the ingress to use // a custom default backend func (db backend) Parse(ing *networking.Ingress) (interface{}, error) { - s, err := parser.GetStringAnnotation("default-backend", ing) + s, err := parser.GetStringAnnotation(defaultBackendAnnotation, ing, db.annotationConfig.Annotations) if err != nil { return nil, err } @@ -50,3 +71,12 @@ func (db backend) Parse(ing *networking.Ingress) (interface{}, error) { return svc, nil } + +func (db backend) GetDocumentation() parser.AnnotationFields { + return db.annotationConfig.Annotations +} + +func (a backend) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, defaultBackendAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/defaultbackend/main_test.go b/internal/ingress/annotations/defaultbackend/main_test.go index ec23d32c2..214d07803 100644 --- a/internal/ingress/annotations/defaultbackend/main_test.go +++ b/internal/ingress/annotations/defaultbackend/main_test.go @@ -91,21 +91,51 @@ func (m mockService) GetService(name string) (*api.Service, error) { func TestAnnotations(t *testing.T) { ing := buildIngress() - data := map[string]string{} - data[parser.GetAnnotationWithPrefix("default-backend")] = "demo-service" - ing.SetAnnotations(data) - - fakeService := &mockService{} - i, err := NewParser(fakeService).Parse(ing) - if err != nil { - t.Errorf("unexpected error %v", err) + tests := map[string]struct { + expectErr bool + serviceName string + }{ + "valid name": { + serviceName: "demo-service", + expectErr: false, + }, + "not in backend": { + serviceName: "demo1-service", + expectErr: true, + }, + "invalid dns name": { + serviceName: "demo-service.something.tld", + expectErr: true, + }, + "invalid name": { + serviceName: "something/xpto", + expectErr: true, + }, + "invalid characters": { + serviceName: "something;xpto", + expectErr: true, + }, } - svc, ok := i.(*api.Service) - if !ok { - t.Errorf("expected *api.Service but got %v", svc) - } - if svc.Name != "demo-service" { - t.Errorf("expected %v but got %v", "demo-service", svc.Name) + for _, test := range tests { + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(defaultBackendAnnotation)] = test.serviceName + ing.SetAnnotations(data) + + fakeService := &mockService{} + i, err := NewParser(fakeService).Parse(ing) + if (err != nil) != test.expectErr { + t.Errorf("expected error: %t got error: %t err value: %s. %+v", test.expectErr, err != nil, err, i) + } + + if !test.expectErr { + svc, ok := i.(*api.Service) + if !ok { + t.Errorf("expected *api.Service but got %v", svc) + } + if svc.Name != test.serviceName { + t.Errorf("expected %v but got %v", test.serviceName, svc.Name) + } + } } } diff --git a/internal/ingress/annotations/fastcgi/main.go b/internal/ingress/annotations/fastcgi/main.go index 84bac4109..96dbc7159 100644 --- a/internal/ingress/annotations/fastcgi/main.go +++ b/internal/ingress/annotations/fastcgi/main.go @@ -19,17 +19,49 @@ package fastcgi import ( "fmt" "reflect" + "regexp" networking "k8s.io/api/networking/v1" "k8s.io/client-go/tools/cache" + "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + fastCGIIndexAnnotation = "fastcgi-index" + fastCGIParamsAnnotation = "fastcgi-params-configmap" +) + +var ( + // fast-cgi valid parameters is just a single file name (like index.php) + regexValidIndexAnnotationAndKey = regexp.MustCompile(`^[A-Za-z0-9\.\-\_]+$`) +) + +var fastCGIAnnotations = parser.Annotation{ + Group: "fastcgi", + Annotations: parser.AnnotationFields{ + fastCGIIndexAnnotation: { + Validator: parser.ValidateRegex(*regexValidIndexAnnotationAndKey, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation can be used to specify an index file`, + }, + fastCGIParamsAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation can be used to specify a ConfigMap containing the fastcgi parameters as a key/value. + Only ConfigMaps on the same namespace of ingress can be used. They key and value from ConfigMap are validated for unauthorized characters.`, + }, + }, +} + type fastcgi struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config describes the per location fastcgi config @@ -57,7 +89,10 @@ func (l1 *Config) Equal(l2 *Config) bool { // NewParser creates a new fastcgiConfig protocol annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return fastcgi{r} + return fastcgi{ + r: r, + annotationConfig: fastCGIAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -70,14 +105,21 @@ func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { return fcgiConfig, nil } - index, err := parser.GetStringAnnotation("fastcgi-index", ing) + index, err := parser.GetStringAnnotation(fastCGIIndexAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + return fcgiConfig, err + } index = "" } + fcgiConfig.Index = index - cm, err := parser.GetStringAnnotation("fastcgi-params-configmap", ing) + cm, err := parser.GetStringAnnotation(fastCGIParamsAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if ing_errors.IsValidationError(err) { + return fcgiConfig, err + } return fcgiConfig, nil } @@ -87,8 +129,10 @@ func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { Reason: fmt.Errorf("error reading configmap name from annotation: %w", err), } } + secCfg := a.r.GetSecurityConfiguration() - if cmns != "" && cmns != ing.Namespace { + // We don't accept different namespaces for secrets. + if cmns != "" && !secCfg.AllowCrossNamespaceResources && cmns != ing.Namespace { return fcgiConfig, fmt.Errorf("different namespace is not supported on fast_cgi param configmap") } @@ -100,7 +144,24 @@ func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { } } + for k, v := range cmap.Data { + if !regexValidIndexAnnotationAndKey.MatchString(k) || !parser.NGINXVariable.MatchString(v) { + klog.ErrorS(fmt.Errorf("fcgi contains invalid key or value"), "fcgi annotation error", "configmap", cmap.Name, "namespace", cmap.Namespace, "key", k, "value", v) + return fcgiConfig, ing_errors.NewValidationError(fastCGIParamsAnnotation) + } + } + + fcgiConfig.Index = index fcgiConfig.Params = cmap.Data return fcgiConfig, nil } + +func (a fastcgi) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a fastcgi) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, fastCGIAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/fastcgi/main_test.go b/internal/ingress/annotations/fastcgi/main_test.go index 35c5bbc12..3296ded65 100644 --- a/internal/ingress/annotations/fastcgi/main_test.go +++ b/internal/ingress/annotations/fastcgi/main_test.go @@ -18,6 +18,7 @@ package fastcgi import ( "fmt" + "reflect" "testing" api "k8s.io/api/core/v1" @@ -49,10 +50,16 @@ func buildIngress() *networking.Ingress { type mockConfigMap struct { resolver.Mock + extraConfigMap map[string]map[string]string } func (m mockConfigMap) GetConfigMap(name string) (*api.ConfigMap, error) { - if name != "default/demo-configmap" && name != "otherns/demo-configmap" { + if m.extraConfigMap == nil { + m.extraConfigMap = make(map[string]map[string]string) + } + cmdata, ok := m.extraConfigMap[name] + + if name != "default/demo-configmap" && name != "otherns/demo-configmap" && !ok { return nil, fmt.Errorf("there is no configmap with name %v", name) } @@ -61,12 +68,17 @@ func (m mockConfigMap) GetConfigMap(name string) (*api.ConfigMap, error) { return nil, fmt.Errorf("invalid configmap name") } + data := map[string]string{"REDIRECT_STATUS": "200", "SERVER_NAME": "$server_name"} + if ok { + data = cmdata + } + return &api.ConfigMap{ ObjectMeta: meta_v1.ObjectMeta{ Namespace: cmns, Name: cmn, }, - Data: map[string]string{"REDIRECT_STATUS": "200", "SERVER_NAME": "$server_name"}, + Data: data, }, nil } @@ -283,3 +295,111 @@ func TestConfigEquality(t *testing.T) { t.Errorf("config4 should be equal to config") } } + +func Test_fastcgi_Parse(t *testing.T) { + + tests := []struct { + name string + index string + configmapname string + configmap map[string]string + want interface{} + wantErr bool + }{ + { + name: "valid configuration", + index: "indexxpto-92123.php", + configmapname: "default/fcgiconfig", + configmap: map[string]string{ + "REQUEST_METHOD": "$request_method", + "SCRIPT_FILENAME": "$document_root$fastcgi_script_name", + }, + want: Config{ + Index: "indexxpto-92123.php", + Params: map[string]string{ + "REQUEST_METHOD": "$request_method", + "SCRIPT_FILENAME": "$document_root$fastcgi_script_name", + }, + }, + }, + { + name: "invalid index name", + index: "indexxpto-92123$xx.php", + configmapname: "default/fcgiconfig", + configmap: map[string]string{ + "REQUEST_METHOD": "$request_method", + "SCRIPT_FILENAME": "$document_root$fastcgi_script_name", + }, + want: Config{}, + wantErr: true, + }, + { + name: "invalid configmap namespace", + index: "indexxpto-92123.php", + configmapname: "otherns/fcgiconfig", + configmap: map[string]string{ + "REQUEST_METHOD": "$request_method", + "SCRIPT_FILENAME": "$document_root$fastcgi_script_name", + }, + want: Config{Index: "indexxpto-92123.php"}, + wantErr: true, + }, + { + name: "invalid configmap namespace name", + index: "indexxpto-92123.php", + configmapname: "otherns/fcgicon;{fig", + configmap: map[string]string{ + "REQUEST_METHOD": "$request_method", + "SCRIPT_FILENAME": "$document_root$fastcgi_script_name", + }, + want: Config{Index: "indexxpto-92123.php"}, + wantErr: true, + }, + { + name: "invalid configmap values key", + index: "indexxpto-92123.php", + configmapname: "default/fcgiconfig", + configmap: map[string]string{ + "REQUEST_METHOD$XPTO": "$request_method", + }, + want: Config{Index: "indexxpto-92123.php"}, + wantErr: true, + }, + { + name: "invalid configmap values val", + index: "indexxpto-92123.php", + configmapname: "default/fcgiconfig", + configmap: map[string]string{ + "REQUEST_METHOD_XPTO": "$request_method{test};a", + }, + want: Config{Index: "indexxpto-92123.php"}, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix("fastcgi-index")] = tt.index + data[parser.GetAnnotationWithPrefix("fastcgi-params-configmap")] = tt.configmapname + ing.SetAnnotations(data) + + m := &mockConfigMap{ + extraConfigMap: map[string]map[string]string{ + tt.configmapname: tt.configmap, + }, + } + + got, err := NewParser(m).Parse(ing) + if (err != nil) != tt.wantErr { + t.Errorf("fastcgi.Parse() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("fastcgi.Parse() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/internal/ingress/annotations/globalratelimit/main.go b/internal/ingress/annotations/globalratelimit/main.go index ea9fc4678..41f58fd57 100644 --- a/internal/ingress/annotations/globalratelimit/main.go +++ b/internal/ingress/annotations/globalratelimit/main.go @@ -22,8 +22,10 @@ import ( "time" networking "k8s.io/api/networking/v1" + "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/ingress-nginx/internal/net" @@ -32,6 +34,46 @@ import ( const defaultKey = "$remote_addr" +const ( + globalRateLimitAnnotation = "global-rate-limit" + globalRateLimitWindowAnnotation = "global-rate-limit-window" + globalRateLimitKeyAnnotation = "global-rate-limit-key" + globalRateLimitIgnoredCidrsAnnotation = "global-rate-limit-ignored-cidrs" +) + +var globalRateLimitAnnotationConfig = parser.Annotation{ + Group: "ratelimit", + Annotations: parser.AnnotationFields{ + globalRateLimitAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation configures maximum allowed number of requests per window`, + }, + globalRateLimitWindowAnnotation: { + Validator: parser.ValidateDuration, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `Configures a time window (i.e 1m) that the limit is applied`, + }, + globalRateLimitKeyAnnotation: { + Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation Configures a key for counting the samples. Defaults to $remote_addr. + You can also combine multiple NGINX variables here, like ${remote_addr}-${http_x_api_client} which would mean the limit will be applied to + requests coming from the same API client (indicated by X-API-Client HTTP request header) with the same source IP address`, + }, + globalRateLimitIgnoredCidrsAnnotation: { + Validator: parser.ValidateCIDRs, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines a comma separated list of IPs and CIDRs to match client IP against. + When there's a match request is not considered for rate limiting.`, + }, + }, +} + // Config encapsulates all global rate limit attributes type Config struct { Namespace string `json:"namespace"` @@ -63,12 +105,16 @@ func (l *Config) Equal(r *Config) bool { } type globalratelimit struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new globalratelimit annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return globalratelimit{r} + return globalratelimit{ + r: r, + annotationConfig: globalRateLimitAnnotationConfig, + } } // Parse extracts globalratelimit annotations from the given ingress @@ -76,8 +122,16 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { config := &Config{} - limit, _ := parser.GetIntAnnotation("global-rate-limit", ing) - rawWindowSize, _ := parser.GetStringAnnotation("global-rate-limit-window", ing) + limit, err := parser.GetIntAnnotation(globalRateLimitAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsInvalidContent(err) { + return nil, err + } + rawWindowSize, err := parser.GetStringAnnotation(globalRateLimitWindowAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsValidationError(err) { + return config, ing_errors.LocationDenied{ + Reason: fmt.Errorf("failed to parse 'global-rate-limit-window' value: %w", err), + } + } if limit == 0 || len(rawWindowSize) == 0 { return config, nil @@ -90,12 +144,18 @@ func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { } } - key, _ := parser.GetStringAnnotation("global-rate-limit-key", ing) + key, err := parser.GetStringAnnotation(globalRateLimitKeyAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + klog.Warningf("invalid %s, defaulting to %s", globalRateLimitKeyAnnotation, defaultKey) + } if len(key) == 0 { key = defaultKey } - rawIgnoredCIDRs, _ := parser.GetStringAnnotation("global-rate-limit-ignored-cidrs", ing) + rawIgnoredCIDRs, err := parser.GetStringAnnotation(globalRateLimitIgnoredCidrsAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsInvalidContent(err) { + return nil, err + } ignoredCIDRs, err := net.ParseCIDRs(rawIgnoredCIDRs) if err != nil { return nil, err @@ -109,3 +169,12 @@ func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { return config, nil } + +func (a globalratelimit) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a globalratelimit) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, globalRateLimitAnnotationConfig.Annotations) +} diff --git a/internal/ingress/annotations/globalratelimit/main_test.go b/internal/ingress/annotations/globalratelimit/main_test.go index 815d6cfff..5d7922666 100644 --- a/internal/ingress/annotations/globalratelimit/main_test.go +++ b/internal/ingress/annotations/globalratelimit/main_test.go @@ -149,6 +149,22 @@ func TestGlobalRateLimiting(t *testing.T) { }, nil, }, + { + "global-rate-limit-complex-key", + map[string]string{ + annRateLimit: "100", + annRateLimitWindow: "2m", + annRateLimitKey: "${http_x_api_user}${otherinfo}", + }, + &Config{ + Namespace: expectedUID, + Limit: 100, + WindowSize: 120, + Key: "${http_x_api_user}${otherinfo}", + IgnoredCIDRs: make([]string, 0), + }, + nil, + }, { "incorrect duration for window", map[string]string{ @@ -157,8 +173,8 @@ func TestGlobalRateLimiting(t *testing.T) { annRateLimitKey: "$http_x_api_user", }, &Config{}, - ing_errors.LocationDenied{ - Reason: fmt.Errorf("failed to parse 'global-rate-limit-window' value: time: unknown unit \"mb\" in duration \"2mb\""), + ing_errors.ValidationError{ + Reason: fmt.Errorf("failed to parse 'global-rate-limit-window' value: annotation nginx.ingress.kubernetes.io/global-rate-limit-window contains invalid value"), }, }, } @@ -168,7 +184,7 @@ func TestGlobalRateLimiting(t *testing.T) { i, actualErr := NewParser(mockBackend{}).Parse(ing) if (testCase.expectedErr == nil || actualErr == nil) && testCase.expectedErr != actualErr { - t.Errorf("expected error 'nil' but got '%v'", actualErr) + t.Errorf("%s expected error '%v' but got '%v'", testCase.title, testCase.expectedErr, actualErr) } else if testCase.expectedErr != nil && actualErr != nil && testCase.expectedErr.Error() != actualErr.Error() { t.Errorf("expected error '%v' but got '%v'", testCase.expectedErr, actualErr) diff --git a/internal/ingress/annotations/http2pushpreload/main.go b/internal/ingress/annotations/http2pushpreload/main.go index 27d3368f4..af9f90aa9 100644 --- a/internal/ingress/annotations/http2pushpreload/main.go +++ b/internal/ingress/annotations/http2pushpreload/main.go @@ -23,17 +23,46 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + http2PushPreloadAnnotation = "http2-push-preload" +) + +var http2PushPreloadAnnotations = parser.Annotation{ + Group: "http2", + Annotations: parser.AnnotationFields{ + http2PushPreloadAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `Enables automatic conversion of preload links specified in the “Link” response header fields into push requests`, + }, + }, +} + type http2PushPreload struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new http2PushPreload annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return http2PushPreload{r} + return http2PushPreload{ + r: r, + annotationConfig: http2PushPreloadAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to add http2 push preload to the server func (h2pp http2PushPreload) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetBoolAnnotation("http2-push-preload", ing) + return parser.GetBoolAnnotation(http2PushPreloadAnnotation, ing, h2pp.annotationConfig.Annotations) +} + +func (h2pp http2PushPreload) GetDocumentation() parser.AnnotationFields { + return h2pp.annotationConfig.Annotations +} + +func (a http2PushPreload) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, http2PushPreloadAnnotations.Annotations) } diff --git a/internal/ingress/annotations/http2pushpreload/main_test.go b/internal/ingress/annotations/http2pushpreload/main_test.go index bb98af93f..eb6e9111d 100644 --- a/internal/ingress/annotations/http2pushpreload/main_test.go +++ b/internal/ingress/annotations/http2pushpreload/main_test.go @@ -23,11 +23,12 @@ import ( networking "k8s.io/api/networking/v1" meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("http2-push-preload") + annotation := parser.GetAnnotationWithPrefix(http2PushPreloadAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") @@ -36,12 +37,14 @@ func TestParse(t *testing.T) { testCases := []struct { annotations map[string]string expected bool + expectErr bool }{ - {map[string]string{annotation: "true"}, true}, - {map[string]string{annotation: "1"}, true}, - {map[string]string{annotation: ""}, false}, - {map[string]string{}, false}, - {nil, false}, + {map[string]string{annotation: "true"}, true, false}, + {map[string]string{annotation: "1"}, true, false}, + {map[string]string{annotation: "xpto"}, false, true}, + {map[string]string{annotation: ""}, false, false}, + {map[string]string{}, false, false}, + {nil, false, false}, } ing := &networking.Ingress{ @@ -54,7 +57,10 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) + result, err := ap.Parse(ing) + if ((err != nil) != testCase.expectErr) && !errors.IsInvalidContent(err) && !errors.IsMissingAnnotations(err) { + t.Fatalf("expected error: %t got error: %t err value: %s. %+v", testCase.expectErr, err != nil, err, testCase.annotations) + } if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) } diff --git a/internal/ingress/annotations/ipwhitelist/main.go b/internal/ingress/annotations/ipallowlist/main.go similarity index 53% rename from internal/ingress/annotations/ipwhitelist/main.go rename to internal/ingress/annotations/ipallowlist/main.go index 63c049fef..d9d454c97 100644 --- a/internal/ingress/annotations/ipwhitelist/main.go +++ b/internal/ingress/annotations/ipallowlist/main.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ipwhitelist +package ipallowlist import ( "fmt" @@ -30,6 +30,24 @@ import ( "k8s.io/ingress-nginx/pkg/util/sets" ) +const ( + ipWhitelistAnnotation = "whitelist-source-range" + ipAllowlistAnnotation = "allowlist-source-range" +) + +var allowlistAnnotations = parser.Annotation{ + Group: "acl", + Annotations: parser.AnnotationFields{ + ipAllowlistAnnotation: { + Validator: parser.ValidateCIDRs, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Failure on parsing this may cause undesired access + Documentation: `This annotation allows setting a list of IPs and networks allowed to access this Location`, + AnnotationAliases: []string{ipWhitelistAnnotation}, + }, + }, +} + // SourceRange returns the CIDR type SourceRange struct { CIDR []string `json:"cidr,omitempty"` @@ -47,36 +65,47 @@ func (sr1 *SourceRange) Equal(sr2 *SourceRange) bool { return sets.StringElementsMatch(sr1.CIDR, sr2.CIDR) } -type ipwhitelist struct { - r resolver.Resolver +type ipallowlist struct { + r resolver.Resolver + annotationConfig parser.Annotation } -// NewParser creates a new whitelist annotation parser +// NewParser creates a new ipallowlist annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return ipwhitelist{r} + return ipallowlist{ + r: r, + annotationConfig: allowlistAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress // rule used to limit access to certain client addresses or networks. // Multiple ranges can specified using commas as separator // e.g. `18.0.0.0/8,56.0.0.0/8` -func (a ipwhitelist) Parse(ing *networking.Ingress) (interface{}, error) { +func (a ipallowlist) Parse(ing *networking.Ingress) (interface{}, error) { defBackend := a.r.GetDefaultBackend() - defaultWhitelistSourceRange := make([]string, len(defBackend.WhitelistSourceRange)) - copy(defaultWhitelistSourceRange, defBackend.WhitelistSourceRange) - sort.Strings(defaultWhitelistSourceRange) + defaultAllowlistSourceRange := make([]string, len(defBackend.WhitelistSourceRange)) + copy(defaultAllowlistSourceRange, defBackend.WhitelistSourceRange) + sort.Strings(defaultAllowlistSourceRange) - val, err := parser.GetStringAnnotation("whitelist-source-range", ing) + val, err := parser.GetStringAnnotation(ipAllowlistAnnotation, ing, a.annotationConfig.Annotations) // A missing annotation is not a problem, just use the default - if err == ing_errors.ErrMissingAnnotations { - return &SourceRange{CIDR: defaultWhitelistSourceRange}, nil + if err != nil { + if err == ing_errors.ErrMissingAnnotations { + return &SourceRange{CIDR: defaultAllowlistSourceRange}, nil + } + + return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDenied{ + Reason: err, + } + } values := strings.Split(val, ",") ipnets, ips, err := net.ParseIPNets(values...) if err != nil && len(ips) == 0 { - return &SourceRange{CIDR: defaultWhitelistSourceRange}, ing_errors.LocationDenied{ + return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDenied{ Reason: fmt.Errorf("the annotation does not contain a valid IP address or network: %w", err), } } @@ -93,3 +122,12 @@ func (a ipwhitelist) Parse(ing *networking.Ingress) (interface{}, error) { return &SourceRange{cidrs}, nil } + +func (a ipallowlist) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a ipallowlist) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, allowlistAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/ipwhitelist/main_test.go b/internal/ingress/annotations/ipallowlist/main_test.go similarity index 64% rename from internal/ingress/annotations/ipwhitelist/main_test.go rename to internal/ingress/annotations/ipallowlist/main_test.go index 5042bb200..b16b25a5b 100644 --- a/internal/ingress/annotations/ipwhitelist/main_test.go +++ b/internal/ingress/annotations/ipallowlist/main_test.go @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package ipwhitelist +package ipallowlist import ( "testing" @@ -86,12 +86,12 @@ func TestParseAnnotations(t *testing.T) { "test parse a invalid net": { net: "ww", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ww", + errOut: "annotation nginx.ingress.kubernetes.io/allowlist-source-range contains invalid value", }, "test parse a empty net": { net: "", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ", + errOut: "the annotation nginx.ingress.kubernetes.io/allowlist-source-range does not contain a valid value ()", }, "test parse multiple valid cidr": { net: "2.2.2.2/32,1.1.1.1/32,3.3.3.0/24", @@ -102,16 +102,16 @@ func TestParseAnnotations(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[parser.GetAnnotationWithPrefix("whitelist-source-range")] = test.net + data[parser.GetAnnotationWithPrefix(ipAllowlistAnnotation)] = test.net ing.SetAnnotations(data) p := NewParser(&resolver.Mock{}) i, err := p.Parse(ing) - if err != nil && !test.expectErr { - t.Errorf("%v:unexpected error: %v", testName, err) + if (err != nil) != test.expectErr { + t.Errorf("%s expected error: %t got error: %t err value: %s. %+v", testName, test.expectErr, err != nil, err, i) } - if test.expectErr { + if test.expectErr && err != nil { if err.Error() != test.errOut { - t.Errorf("%v:expected error: %v but %v return", testName, test.errOut, err.Error()) + t.Errorf("expected error %s but got %s", test.errOut, err) } } if !test.expectErr { @@ -137,7 +137,7 @@ func (m mockBackend) GetDefaultBackend() defaults.Backend { } } -// Test that when we have a whitelist set on the Backend that is used when we +// Test that when we have a allowlist set on the Backend that is used when we // don't have the annotation func TestParseAnnotationsWithDefaultConfig(t *testing.T) { ing := buildIngress() @@ -158,12 +158,12 @@ func TestParseAnnotationsWithDefaultConfig(t *testing.T) { "test parse a invalid net": { net: "ww", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ww", + errOut: "annotation nginx.ingress.kubernetes.io/allowlist-source-range contains invalid value", }, "test parse a empty net": { net: "", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ", + errOut: "the annotation nginx.ingress.kubernetes.io/allowlist-source-range does not contain a valid value ()", }, "test parse multiple valid cidr": { net: "2.2.2.2/32,1.1.1.1/32,3.3.3.0/24", @@ -174,16 +174,67 @@ func TestParseAnnotationsWithDefaultConfig(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[parser.GetAnnotationWithPrefix("whitelist-source-range")] = test.net + data[parser.GetAnnotationWithPrefix(ipAllowlistAnnotation)] = test.net ing.SetAnnotations(data) p := NewParser(mockBackend) i, err := p.Parse(ing) - if err != nil && !test.expectErr { - t.Errorf("%v:unexpected error: %v", testName, err) + if (err != nil) != test.expectErr { + t.Errorf("expected error: %t got error: %t err value: %s. %+v", test.expectErr, err != nil, err, i) } - if test.expectErr { + if test.expectErr && err != nil { if err.Error() != test.errOut { - t.Errorf("%v:expected error: %v but %v return", testName, test.errOut, err.Error()) + t.Errorf("expected error %s but got %s", test.errOut, err) + } + } + if !test.expectErr { + sr, ok := i.(*SourceRange) + if !ok { + t.Errorf("%v:expected a SourceRange type", testName) + } + if !strsEquals(sr.CIDR, test.expectCidr) { + t.Errorf("%v:expected %v CIDR but %v returned", testName, test.expectCidr, sr.CIDR) + } + } + } +} + +// Test that when we have a whitelist set on the Backend that is used when we +// don't have the annotation +func TestLegacyAnnotation(t *testing.T) { + ing := buildIngress() + + mockBackend := mockBackend{} + + tests := map[string]struct { + net string + expectCidr []string + expectErr bool + errOut string + }{ + "test parse a valid net": { + net: "10.0.0.0/24", + expectCidr: []string{"10.0.0.0/24"}, + expectErr: false, + }, + "test parse multiple valid cidr": { + net: "2.2.2.2/32,1.1.1.1/32,3.3.3.0/24", + expectCidr: []string{"1.1.1.1/32", "2.2.2.2/32", "3.3.3.0/24"}, + expectErr: false, + }, + } + + for testName, test := range tests { + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(ipWhitelistAnnotation)] = test.net + ing.SetAnnotations(data) + p := NewParser(mockBackend) + i, err := p.Parse(ing) + if (err != nil) != test.expectErr { + t.Errorf("expected error: %t got error: %t err value: %s. %+v", test.expectErr, err != nil, err, i) + } + if test.expectErr && err != nil { + if err.Error() != test.errOut { + t.Errorf("expected error %s but got %s", test.errOut, err) } } if !test.expectErr { diff --git a/internal/ingress/annotations/ipdenylist/main.go b/internal/ingress/annotations/ipdenylist/main.go index f6a0e10f1..f17ce079a 100644 --- a/internal/ingress/annotations/ipdenylist/main.go +++ b/internal/ingress/annotations/ipdenylist/main.go @@ -30,6 +30,22 @@ import ( "k8s.io/ingress-nginx/pkg/util/sets" ) +const ( + ipDenylistAnnotation = "denylist-source-range" +) + +var denylistAnnotations = parser.Annotation{ + Group: "acl", + Annotations: parser.AnnotationFields{ + ipDenylistAnnotation: { + Validator: parser.ValidateCIDRs, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Failure on parsing this may cause undesired access + Documentation: `This annotation allows setting a list of IPs and networks that should be blocked to access this Location`, + }, + }, +} + // SourceRange returns the CIDR type SourceRange struct { CIDR []string `json:"cidr,omitempty"` @@ -48,12 +64,16 @@ func (sr1 *SourceRange) Equal(sr2 *SourceRange) bool { } type ipdenylist struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new denylist annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return ipdenylist{r} + return ipdenylist{ + r: r, + annotationConfig: denylistAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -67,10 +87,16 @@ func (a ipdenylist) Parse(ing *networking.Ingress) (interface{}, error) { copy(defaultDenylistSourceRange, defBackend.DenylistSourceRange) sort.Strings(defaultDenylistSourceRange) - val, err := parser.GetStringAnnotation("denylist-source-range", ing) - // A missing annotation is not a problem, just use the default - if err == ing_errors.ErrMissingAnnotations { - return &SourceRange{CIDR: defaultDenylistSourceRange}, nil + val, err := parser.GetStringAnnotation(ipDenylistAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + if err == ing_errors.ErrMissingAnnotations { + return &SourceRange{CIDR: defaultDenylistSourceRange}, nil + } + + return &SourceRange{CIDR: defaultDenylistSourceRange}, ing_errors.LocationDenied{ + Reason: err, + } + } values := strings.Split(val, ",") @@ -93,3 +119,12 @@ func (a ipdenylist) Parse(ing *networking.Ingress) (interface{}, error) { return &SourceRange{cidrs}, nil } + +func (a ipdenylist) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a ipdenylist) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, denylistAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/ipdenylist/main_test.go b/internal/ingress/annotations/ipdenylist/main_test.go index eb69aa520..ebd81179a 100644 --- a/internal/ingress/annotations/ipdenylist/main_test.go +++ b/internal/ingress/annotations/ipdenylist/main_test.go @@ -86,17 +86,17 @@ func TestParseAnnotations(t *testing.T) { "test parse a invalid net": { net: "ww", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ww", + errOut: "annotation nginx.ingress.kubernetes.io/denylist-source-range contains invalid value", }, "test parse a empty net": { net: "", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ", + errOut: "the annotation nginx.ingress.kubernetes.io/denylist-source-range does not contain a valid value ()", }, "test parse a malicious escaped string": { net: `10.0.0.0/8"rm /tmp",11.0.0.0/8`, expectErr: true, - errOut: `the annotation does not contain a valid IP address or network: invalid CIDR address: 10.0.0.0/8"rm /tmp"`, + errOut: `annotation nginx.ingress.kubernetes.io/denylist-source-range contains invalid value`, }, "test parse multiple valid cidr": { net: "2.2.2.2/32,1.1.1.1/32,3.3.3.0/24", @@ -107,16 +107,16 @@ func TestParseAnnotations(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[parser.GetAnnotationWithPrefix("denylist-source-range")] = test.net + data[parser.GetAnnotationWithPrefix(ipDenylistAnnotation)] = test.net ing.SetAnnotations(data) p := NewParser(&resolver.Mock{}) i, err := p.Parse(ing) - if err != nil && !test.expectErr { - t.Errorf("%v:unexpected error: %v", testName, err) + if (err != nil) != test.expectErr { + t.Errorf("expected error: %t got error: %t err value: %s. %+v", test.expectErr, err != nil, err, i) } - if test.expectErr { + if test.expectErr && err != nil { if err.Error() != test.errOut { - t.Errorf("%v:expected error: %v but %v return", testName, test.errOut, err.Error()) + t.Errorf("expected error %s but got %s", test.errOut, err) } } if !test.expectErr { @@ -163,12 +163,12 @@ func TestParseAnnotationsWithDefaultConfig(t *testing.T) { "test parse a invalid net": { net: "ww", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ww", + errOut: "annotation nginx.ingress.kubernetes.io/denylist-source-range contains invalid value", }, "test parse a empty net": { net: "", expectErr: true, - errOut: "the annotation does not contain a valid IP address or network: invalid CIDR address: ", + errOut: "the annotation nginx.ingress.kubernetes.io/denylist-source-range does not contain a valid value ()", }, "test parse multiple valid cidr": { net: "2.2.2.2/32,1.1.1.1/32,3.3.3.0/24", @@ -179,16 +179,16 @@ func TestParseAnnotationsWithDefaultConfig(t *testing.T) { for testName, test := range tests { data := map[string]string{} - data[parser.GetAnnotationWithPrefix("denylist-source-range")] = test.net + data[parser.GetAnnotationWithPrefix(ipDenylistAnnotation)] = test.net ing.SetAnnotations(data) p := NewParser(mockBackend) i, err := p.Parse(ing) - if err != nil && !test.expectErr { - t.Errorf("%v:unexpected error: %v", testName, err) + if (err != nil) != test.expectErr { + t.Errorf("expected error: %t got error: %t err value: %s. %+v", test.expectErr, err != nil, err, i) } - if test.expectErr { + if test.expectErr && err != nil { if err.Error() != test.errOut { - t.Errorf("%v:expected error: %v but %v return", testName, test.errOut, err.Error()) + t.Errorf("expected error %s but got %s", test.errOut, err) } } if !test.expectErr { diff --git a/internal/ingress/annotations/loadbalancing/main.go b/internal/ingress/annotations/loadbalancing/main.go index a8b4335e6..ee89d2c1b 100644 --- a/internal/ingress/annotations/loadbalancing/main.go +++ b/internal/ingress/annotations/loadbalancing/main.go @@ -23,18 +23,52 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -type loadbalancing struct { - r resolver.Resolver +// LB Alghorithms are defined in https://github.com/kubernetes/ingress-nginx/blob/d3e75b056f77be54e01bdb18675f1bb46caece31/rootfs/etc/nginx/lua/balancer.lua#L28 + +const ( + loadBalanceAlghoritmAnnotation = "load-balance" +) + +var loadBalanceAlghoritms = []string{"round_robin", "chash", "chashsubset", "sticky_balanced", "sticky_persistent", "ewma"} + +var loadBalanceAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + loadBalanceAlghoritmAnnotation: { + Validator: parser.ValidateOptions(loadBalanceAlghoritms, true, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows setting the load balancing alghorithm that should be used. If none is specified, defaults to + the default configured by Ingress admin, otherwise to round_robin`, + }, + }, } -// NewParser creates a new CORS annotation parser +type loadbalancing struct { + r resolver.Resolver + annotationConfig parser.Annotation +} + +// NewParser creates a new Load Balancer annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return loadbalancing{r} + return loadbalancing{ + r: r, + annotationConfig: loadBalanceAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a loadbalancing) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("load-balance", ing) + return parser.GetStringAnnotation(loadBalanceAlghoritmAnnotation, ing, a.annotationConfig.Annotations) +} + +func (a loadbalancing) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a loadbalancing) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, loadBalanceAnnotations.Annotations) } diff --git a/internal/ingress/annotations/loadbalancing/main_test.go b/internal/ingress/annotations/loadbalancing/main_test.go index e2be5c0ae..b0442c37f 100644 --- a/internal/ingress/annotations/loadbalancing/main_test.go +++ b/internal/ingress/annotations/loadbalancing/main_test.go @@ -38,7 +38,8 @@ func TestParse(t *testing.T) { annotations map[string]string expected string }{ - {map[string]string{annotation: "ip_hash"}, "ip_hash"}, + {map[string]string{annotation: "ewma"}, "ewma"}, + {map[string]string{annotation: "ip_hash"}, ""}, // This is invalid and should not return anything {map[string]string{}, ""}, {nil, ""}, } diff --git a/internal/ingress/annotations/log/main.go b/internal/ingress/annotations/log/main.go index 4bc76dcf7..ec08292a9 100644 --- a/internal/ingress/annotations/log/main.go +++ b/internal/ingress/annotations/log/main.go @@ -23,8 +23,32 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + enableAccessLogAnnotation = "enable-access-log" + enableRewriteLogAnnotation = "enable-rewrite-log" +) + +var logAnnotations = parser.Annotation{ + Group: "log", + Annotations: parser.AnnotationFields{ + enableAccessLogAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This configuration setting allows you to control if this location should generate an access_log`, + }, + enableRewriteLogAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This configuration setting allows you to control if this location should generate logs from the rewrite feature usage`, + }, + }, +} + type log struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the configuration to be used in the Ingress @@ -48,7 +72,10 @@ func (bd1 *Config) Equal(bd2 *Config) bool { // NewParser creates a new log annotations parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return log{r} + return log{ + r: r, + annotationConfig: logAnnotations, + } } // Parse parses the annotations contained in the ingress @@ -57,15 +84,24 @@ func (l log) Parse(ing *networking.Ingress) (interface{}, error) { var err error config := &Config{} - config.Access, err = parser.GetBoolAnnotation("enable-access-log", ing) + config.Access, err = parser.GetBoolAnnotation(enableAccessLogAnnotation, ing, l.annotationConfig.Annotations) if err != nil { config.Access = true } - config.Rewrite, err = parser.GetBoolAnnotation("enable-rewrite-log", ing) + config.Rewrite, err = parser.GetBoolAnnotation(enableRewriteLogAnnotation, ing, l.annotationConfig.Annotations) if err != nil { config.Rewrite = false } return config, nil } + +func (l log) GetDocumentation() parser.AnnotationFields { + return l.annotationConfig.Annotations +} + +func (a log) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, logAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/log/main_test.go b/internal/ingress/annotations/log/main_test.go index c4632b010..df97c2e5b 100644 --- a/internal/ingress/annotations/log/main_test.go +++ b/internal/ingress/annotations/log/main_test.go @@ -73,7 +73,7 @@ func TestIngressAccessLogConfig(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-access-log")] = "false" + data[parser.GetAnnotationWithPrefix(enableAccessLogAnnotation)] = "false" ing.SetAnnotations(data) log, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -91,7 +91,7 @@ func TestIngressRewriteLogConfig(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-rewrite-log")] = "true" + data[parser.GetAnnotationWithPrefix(enableRewriteLogAnnotation)] = "true" ing.SetAnnotations(data) log, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -104,3 +104,21 @@ func TestIngressRewriteLogConfig(t *testing.T) { t.Errorf("expected rewrite log to be enabled but it is disabled") } } + +func TestInvalidBoolConfig(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(enableRewriteLogAnnotation)] = "blo" + ing.SetAnnotations(data) + + log, _ := NewParser(&resolver.Mock{}).Parse(ing) + nginxLogs, ok := log.(*Config) + if !ok { + t.Errorf("expected a Config type") + } + + if !nginxLogs.Access { + t.Errorf("expected access log to be enabled due to invalid config, but it is disabled") + } +} diff --git a/internal/ingress/annotations/mirror/main.go b/internal/ingress/annotations/mirror/main.go index 9cb1b0ede..2d417dece 100644 --- a/internal/ingress/annotations/mirror/main.go +++ b/internal/ingress/annotations/mirror/main.go @@ -18,13 +18,50 @@ package mirror import ( "fmt" + "regexp" "strings" networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/klog/v2" ) +const ( + mirrorRequestBodyAnnotation = "mirror-request-body" + mirrorTargetAnnotation = "mirror-target" + mirrorHostAnnotation = "mirror-host" +) + +var ( + OnOffRegex = regexp.MustCompile(`^(on|off)$`) +) + +var mirrorAnnotation = parser.Annotation{ + Group: "mirror", + Annotations: parser.AnnotationFields{ + mirrorRequestBodyAnnotation: { + Validator: parser.ValidateRegex(*OnOffRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if the request-body should be sent to the mirror backend. Can be 'on' or 'off'`, + }, + mirrorTargetAnnotation: { + Validator: parser.ValidateServerName, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation enables a request to be mirrored to a mirror backend.`, + }, + mirrorHostAnnotation: { + Validator: parser.ValidateServerName, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation defines if a specific Host header should be set for mirrored request.`, + }, + }, +} + // Config returns the mirror to use in a given location type Config struct { Source string `json:"source"` @@ -63,12 +100,16 @@ func (m1 *Config) Equal(m2 *Config) bool { } type mirror struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new mirror configuration annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return mirror{r} + return mirror{ + r: r, + annotationConfig: mirrorAnnotation, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -79,19 +120,29 @@ func (a mirror) Parse(ing *networking.Ingress) (interface{}, error) { } var err error - config.RequestBody, err = parser.GetStringAnnotation("mirror-request-body", ing) + config.RequestBody, err = parser.GetStringAnnotation(mirrorRequestBodyAnnotation, ing, a.annotationConfig.Annotations) if err != nil || config.RequestBody != "off" { + if errors.IsValidationError(err) { + klog.Warningf("annotation %s contains invalid value", mirrorRequestBodyAnnotation) + } config.RequestBody = "on" } - config.Target, err = parser.GetStringAnnotation("mirror-target", ing) + config.Target, err = parser.GetStringAnnotation(mirrorTargetAnnotation, ing, a.annotationConfig.Annotations) if err != nil { - config.Target = "" - config.Source = "" + if errors.IsValidationError(err) { + klog.Warningf("annotation %s contains invalid value, defaulting", mirrorTargetAnnotation) + } else { + config.Target = "" + config.Source = "" + } } - config.Host, err = parser.GetStringAnnotation("mirror-host", ing) + config.Host, err = parser.GetStringAnnotation(mirrorHostAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("annotation %s contains invalid value, defaulting", mirrorHostAnnotation) + } if config.Target != "" { target := strings.Split(config.Target, "$") @@ -106,3 +157,12 @@ func (a mirror) Parse(ing *networking.Ingress) (interface{}, error) { return config, nil } + +func (a mirror) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a mirror) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, mirrorAnnotation.Annotations) +} diff --git a/internal/ingress/annotations/mirror/main_test.go b/internal/ingress/annotations/mirror/main_test.go index add90d768..1f6b44d61 100644 --- a/internal/ingress/annotations/mirror/main_test.go +++ b/internal/ingress/annotations/mirror/main_test.go @@ -94,13 +94,13 @@ func TestParse(t *testing.T) { Source: ngxURI, RequestBody: "on", Target: "http://some.test.env.com", - Host: "someInvalidParm.%^&*()_=!@#'\"", + Host: "some.test.env.com", }}, {map[string]string{backendURL: "http://some.test.env.com", host: "_sbrubles-i\"@xpto:12345"}, &Config{ Source: ngxURI, RequestBody: "on", Target: "http://some.test.env.com", - Host: "_sbrubles-i\"@xpto:12345", + Host: "some.test.env.com", }}, } @@ -115,9 +115,12 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) + result, err := ap.Parse(ing) + if err != nil { + t.Errorf(err.Error()) + } if !reflect.DeepEqual(result, testCase.expected) { - t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) + t.Errorf("expected %+v but returned %+v, annotations: %s", testCase.expected, result, testCase.annotations) } } } diff --git a/internal/ingress/annotations/modsecurity/main.go b/internal/ingress/annotations/modsecurity/main.go index c53739441..5a9aaa729 100644 --- a/internal/ingress/annotations/modsecurity/main.go +++ b/internal/ingress/annotations/modsecurity/main.go @@ -19,9 +19,48 @@ package modsecurity import ( networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" + "k8s.io/klog/v2" ) +const ( + modsecEnableAnnotation = "enable-modsecurity" + modsecEnableOwaspCoreAnnotation = "enable-owasp-core-rules" + modesecTransactionIdAnnotation = "modsecurity-transaction-id" + modsecSnippetAnnotation = "modsecurity-snippet" +) + +var modsecurityAnnotation = parser.Annotation{ + Group: "modsecurity", + Annotations: parser.AnnotationFields{ + modsecEnableAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables ModSecurity`, + }, + modsecEnableOwaspCoreAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables the OWASP Core Rule Set`, + }, + modesecTransactionIdAnnotation: { + Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation enables passing an NGINX variable to ModSecurity.`, + }, + modsecSnippetAnnotation: { + Validator: parser.ValidateNull, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskCritical, + Documentation: `This annotation enables adding a specific snippet configuration for ModSecurity`, + }, + }, +} + // Config contains ModSecurity Configuration items type Config struct { Enable bool `json:"enable-modsecurity"` @@ -60,11 +99,15 @@ func (modsec1 *Config) Equal(modsec2 *Config) bool { // NewParser creates a new ModSecurity annotation parser func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { - return modSecurity{resolver} + return modSecurity{ + r: resolver, + annotationConfig: modsecurityAnnotation, + } } type modSecurity struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Parse parses the annotations contained in the ingress @@ -74,26 +117,44 @@ func (a modSecurity) Parse(ing *networking.Ingress) (interface{}, error) { config := &Config{} config.EnableSet = true - config.Enable, err = parser.GetBoolAnnotation("enable-modsecurity", ing) + config.Enable, err = parser.GetBoolAnnotation(modsecEnableAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsInvalidContent(err) { + klog.Warningf("annotation %s contains invalid directive, defaulting to false", modsecEnableAnnotation) + } config.Enable = false config.EnableSet = false } - config.OWASPRules, err = parser.GetBoolAnnotation("enable-owasp-core-rules", ing) + config.OWASPRules, err = parser.GetBoolAnnotation(modsecEnableOwaspCoreAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsInvalidContent(err) { + klog.Warningf("annotation %s contains invalid directive, defaulting to false", modsecEnableOwaspCoreAnnotation) + } config.OWASPRules = false } - config.TransactionID, err = parser.GetStringAnnotation("modsecurity-transaction-id", ing) + config.TransactionID, err = parser.GetStringAnnotation(modesecTransactionIdAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsInvalidContent(err) { + klog.Warningf("annotation %s contains invalid directive, defaulting", modesecTransactionIdAnnotation) + } config.TransactionID = "" } - config.Snippet, err = parser.GetStringAnnotation("modsecurity-snippet", ing) + config.Snippet, err = parser.GetStringAnnotation("modsecurity-snippet", ing, a.annotationConfig.Annotations) if err != nil { config.Snippet = "" } return config, nil } + +func (a modSecurity) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a modSecurity) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, modsecurityAnnotation.Annotations) +} diff --git a/internal/ingress/annotations/opentelemetry/main.go b/internal/ingress/annotations/opentelemetry/main.go index 7dd292322..a029087da 100644 --- a/internal/ingress/annotations/opentelemetry/main.go +++ b/internal/ingress/annotations/opentelemetry/main.go @@ -17,14 +17,51 @@ limitations under the License. package opentelemetry import ( + "regexp" + networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + enableOpenTelemetryAnnotation = "enable-opentelemetry" + otelTrustSpanAnnotation = "opentelemetry-trust-incoming-span" + otelOperationNameAnnotation = "opentelemetry-operation-name" +) + +var regexOperationName = regexp.MustCompile(`^[A-Za-z0-9_\-]*$`) + +var otelAnnotations = parser.Annotation{ + Group: "opentelemetry", + Annotations: parser.AnnotationFields{ + enableOpenTelemetryAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if Open Telemetry collector should be enable for this location. OpenTelemetry should + already be configured by Ingress administrator`, + }, + otelTrustSpanAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables or disables using spans from incoming requests as parent for created ones`, + }, + otelOperationNameAnnotation: { + Validator: parser.ValidateRegex(*regexOperationName, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines what operation name should be added to the span`, + }, + }, +} + type opentelemetry struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the configuration to be used in the Ingress @@ -64,13 +101,16 @@ func (bd1 *Config) Equal(bd2 *Config) bool { // NewParser creates a new serviceUpstream annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return opentelemetry{r} + return opentelemetry{ + r: r, + annotationConfig: otelAnnotations, + } } // Parse parses the annotations to look for opentelemetry configurations func (c opentelemetry) Parse(ing *networking.Ingress) (interface{}, error) { cfg := Config{} - enabled, err := parser.GetBoolAnnotation("enable-opentelemetry", ing) + enabled, err := parser.GetBoolAnnotation(enableOpenTelemetryAnnotation, ing, c.annotationConfig.Annotations) if err != nil { return &cfg, nil } @@ -80,10 +120,13 @@ func (c opentelemetry) Parse(ing *networking.Ingress) (interface{}, error) { return &cfg, nil } - trustEnabled, err := parser.GetBoolAnnotation("opentelemetry-trust-incoming-span", ing) + trustEnabled, err := parser.GetBoolAnnotation(otelTrustSpanAnnotation, ing, c.annotationConfig.Annotations) if err != nil { - operationName, err := parser.GetStringAnnotation("opentelemetry-operation-name", ing) + operationName, err := parser.GetStringAnnotation(otelOperationNameAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + return nil, err + } return &cfg, nil } cfg.OperationName = operationName @@ -92,10 +135,22 @@ func (c opentelemetry) Parse(ing *networking.Ingress) (interface{}, error) { cfg.TrustSet = true cfg.TrustEnabled = trustEnabled - operationName, err := parser.GetStringAnnotation("opentelemetry-operation-name", ing) + operationName, err := parser.GetStringAnnotation(otelOperationNameAnnotation, ing, c.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + return nil, err + } return &cfg, nil } cfg.OperationName = operationName return &cfg, nil } + +func (c opentelemetry) GetDocumentation() parser.AnnotationFields { + return c.annotationConfig.Annotations +} + +func (a opentelemetry) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, otelAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/opentelemetry/main_test.go b/internal/ingress/annotations/opentelemetry/main_test.go index 619108fa6..c78ebc8b3 100644 --- a/internal/ingress/annotations/opentelemetry/main_test.go +++ b/internal/ingress/annotations/opentelemetry/main_test.go @@ -73,7 +73,7 @@ func TestIngressAnnotationOpentelemetrySetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-opentelemetry")] = "true" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -100,7 +100,7 @@ func TestIngressAnnotationOpentelemetrySetFalse(t *testing.T) { // Test with explicitly set to false data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-opentelemetry")] = "false" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "false" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -123,12 +123,15 @@ func TestIngressAnnotationOpentelemetryTrustSetTrue(t *testing.T) { data := map[string]string{} opName := "foo-op" - data[parser.GetAnnotationWithPrefix("enable-opentelemetry")] = "true" - data[parser.GetAnnotationWithPrefix("opentelemetry-trust-incoming-span")] = "true" - data[parser.GetAnnotationWithPrefix("opentelemetry-operation-name")] = opName + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(otelTrustSpanAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(otelOperationNameAnnotation)] = opName ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Fatal(err) + } openTelemetry, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -155,6 +158,21 @@ func TestIngressAnnotationOpentelemetryTrustSetTrue(t *testing.T) { } } +func TestIngressAnnotationOpentelemetryWithBadOpName(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + opName := "fooxpto_123$la;" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(otelOperationNameAnnotation)] = opName + ing.SetAnnotations(data) + + _, err := NewParser(&resolver.Mock{}).Parse(ing) + if err == nil { + t.Fatalf("This operation should return an error but no error was returned") + } +} + func TestIngressAnnotationOpentelemetryUnset(t *testing.T) { ing := buildIngress() diff --git a/internal/ingress/annotations/opentracing/main.go b/internal/ingress/annotations/opentracing/main.go index 17ba7eb9f..7c8671f9d 100644 --- a/internal/ingress/annotations/opentracing/main.go +++ b/internal/ingress/annotations/opentracing/main.go @@ -23,8 +23,33 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + enableOpentracingAnnotation = "enable-opentracing" + opentracingTrustSpanAnnotation = "opentracing-trust-incoming-span" +) + +var opentracingAnnotations = parser.Annotation{ + Group: "opentracing", + Annotations: parser.AnnotationFields{ + enableOpentracingAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if Opentracing collector should be enable for this location. Opentracing should + already be configured by Ingress administrator`, + }, + opentracingTrustSpanAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables or disables using spans from incoming requests as parent for created ones`, + }, + }, +} + type opentracing struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the configuration to be used in the Ingress @@ -58,19 +83,31 @@ func (bd1 *Config) Equal(bd2 *Config) bool { // NewParser creates a new serviceUpstream annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return opentracing{r} + return opentracing{ + r: r, + annotationConfig: opentracingAnnotations, + } } func (s opentracing) Parse(ing *networking.Ingress) (interface{}, error) { - enabled, err := parser.GetBoolAnnotation("enable-opentracing", ing) + enabled, err := parser.GetBoolAnnotation(enableOpentracingAnnotation, ing, s.annotationConfig.Annotations) if err != nil { return &Config{}, nil } - trustSpan, err := parser.GetBoolAnnotation("opentracing-trust-incoming-span", ing) + trustSpan, err := parser.GetBoolAnnotation(opentracingTrustSpanAnnotation, ing, s.annotationConfig.Annotations) if err != nil { return &Config{Set: true, Enabled: enabled}, nil } return &Config{Set: true, Enabled: enabled, TrustSet: true, TrustEnabled: trustSpan}, nil } + +func (s opentracing) GetDocumentation() parser.AnnotationFields { + return s.annotationConfig.Annotations +} + +func (a opentracing) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, opentracingAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/opentracing/main_test.go b/internal/ingress/annotations/opentracing/main_test.go index 7bd9d31ff..b7b62ac9d 100644 --- a/internal/ingress/annotations/opentracing/main_test.go +++ b/internal/ingress/annotations/opentracing/main_test.go @@ -73,7 +73,7 @@ func TestIngressAnnotationOpentracingSetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-opentracing")] = "true" + data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "true" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -92,7 +92,7 @@ func TestIngressAnnotationOpentracingSetFalse(t *testing.T) { // Test with explicitly set to false data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-opentracing")] = "false" + data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "false" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -110,8 +110,8 @@ func TestIngressAnnotationOpentracingTrustSetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("enable-opentracing")] = "true" - data[parser.GetAnnotationWithPrefix("opentracing-trust-incoming-span")] = "true" + data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(opentracingTrustSpanAnnotation)] = "true" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) diff --git a/internal/ingress/annotations/parser/main.go b/internal/ingress/annotations/parser/main.go index 107a278b0..951970e27 100644 --- a/internal/ingress/annotations/parser/main.go +++ b/internal/ingress/annotations/parser/main.go @@ -29,20 +29,79 @@ import ( ) // DefaultAnnotationsPrefix defines the common prefix used in the nginx ingress controller -const DefaultAnnotationsPrefix = "nginx.ingress.kubernetes.io" +const ( + DefaultAnnotationsPrefix = "nginx.ingress.kubernetes.io" + DefaultEnableAnnotationValidation = true +) var ( // AnnotationsPrefix is the mutable attribute that the controller explicitly refers to AnnotationsPrefix = DefaultAnnotationsPrefix + // Enable is the mutable attribute for enabling or disabling the validation functions + EnableAnnotationValidation = DefaultEnableAnnotationValidation ) +// AnnotationGroup defines the group that this annotation may belong +// eg.: Security, Snippets, Rewrite, etc +type AnnotationGroup string + +// AnnotationScope defines which scope this annotation applies. May be to the whole +// ingress, per location, etc +type AnnotationScope string + +var ( + AnnotationScopeLocation AnnotationScope = "location" + AnnotationScopeIngress AnnotationScope = "ingress" +) + +// AnnotationRisk is a subset of risk that an annotation may represent. +// Based on the Risk, the admin will be able to allow or disallow users to set it +// on their ingress objects +type AnnotationRisk int + +type AnnotationFields map[string]AnnotationConfig + +// AnnotationConfig defines the configuration that a single annotation field +// has, with the Validator and the documentation of this field. +type AnnotationConfig struct { + // Validator defines a function to validate the annotation value + Validator AnnotationValidator + // Documentation defines a user facing documentation for this annotation. This + // field will be used to auto generate documentations + Documentation string + // Risk defines a risk of this annotation being exposed to the user. Annotations + // with bool fields, or to set timeout are usually low risk. Annotations that allows + // string input without a limited set of options may represent a high risk + Risk AnnotationRisk + + // Scope defines which scope this annotation applies, may be to location, to an Ingress object, etc + Scope AnnotationScope + + // AnnotationAliases defines other names this annotation may have. + AnnotationAliases []string +} + +// Annotation defines an annotation feature an Ingress may have. +// It should contain the internal resolver, and all the annotations +// with configs and Validators that should be used for each Annotation +type Annotation struct { + // Annotations contains all the annotations that belong to this feature + Annotations AnnotationFields + // Group defines which annotation group this feature belongs to + Group AnnotationGroup +} + // IngressAnnotation has a method to parse annotations located in Ingress type IngressAnnotation interface { Parse(ing *networking.Ingress) (interface{}, error) + GetDocumentation() AnnotationFields + Validate(anns map[string]string) error } type ingAnnotations map[string]string +// TODO: We already parse all of this on checkAnnotation and can just do a parse over the +// value func (a ingAnnotations) parseBool(name string) (bool, error) { val, ok := a[name] if ok { @@ -92,21 +151,9 @@ func (a ingAnnotations) parseFloat32(name string) (float32, error) { return 0, errors.ErrMissingAnnotations } -func checkAnnotation(name string, ing *networking.Ingress) error { - if ing == nil || len(ing.GetAnnotations()) == 0 { - return errors.ErrMissingAnnotations - } - if name == "" { - return errors.ErrInvalidAnnotationName - } - - return nil -} - // GetBoolAnnotation extracts a boolean from an Ingress annotation -func GetBoolAnnotation(name string, ing *networking.Ingress) (bool, error) { - v := GetAnnotationWithPrefix(name) - err := checkAnnotation(v, ing) +func GetBoolAnnotation(name string, ing *networking.Ingress, fields AnnotationFields) (bool, error) { + v, err := checkAnnotation(name, ing, fields) if err != nil { return false, err } @@ -114,9 +161,8 @@ func GetBoolAnnotation(name string, ing *networking.Ingress) (bool, error) { } // GetStringAnnotation extracts a string from an Ingress annotation -func GetStringAnnotation(name string, ing *networking.Ingress) (string, error) { - v := GetAnnotationWithPrefix(name) - err := checkAnnotation(v, ing) +func GetStringAnnotation(name string, ing *networking.Ingress, fields AnnotationFields) (string, error) { + v, err := checkAnnotation(name, ing, fields) if err != nil { return "", err } @@ -125,9 +171,8 @@ func GetStringAnnotation(name string, ing *networking.Ingress) (string, error) { } // GetIntAnnotation extracts an int from an Ingress annotation -func GetIntAnnotation(name string, ing *networking.Ingress) (int, error) { - v := GetAnnotationWithPrefix(name) - err := checkAnnotation(v, ing) +func GetIntAnnotation(name string, ing *networking.Ingress, fields AnnotationFields) (int, error) { + v, err := checkAnnotation(name, ing, fields) if err != nil { return 0, err } @@ -135,9 +180,8 @@ func GetIntAnnotation(name string, ing *networking.Ingress) (int, error) { } // GetFloatAnnotation extracts a float32 from an Ingress annotation -func GetFloatAnnotation(name string, ing *networking.Ingress) (float32, error) { - v := GetAnnotationWithPrefix(name) - err := checkAnnotation(v, ing) +func GetFloatAnnotation(name string, ing *networking.Ingress, fields AnnotationFields) (float32, error) { + v, err := checkAnnotation(name, ing, fields) if err != nil { return 0, err } @@ -149,6 +193,23 @@ func GetAnnotationWithPrefix(suffix string) string { return fmt.Sprintf("%v/%v", AnnotationsPrefix, suffix) } +func TrimAnnotationPrefix(annotation string) string { + return strings.TrimPrefix(annotation, AnnotationsPrefix+"/") +} + +func StringRiskToRisk(risk string) AnnotationRisk { + switch strings.ToLower(risk) { + case "critical": + return AnnotationRiskCritical + case "high": + return AnnotationRiskHigh + case "medium": + return AnnotationRiskMedium + default: + return AnnotationRiskLow + } +} + func normalizeString(input string) string { trimmedContent := []string{} for _, line := range strings.Split(input, "\n") { diff --git a/internal/ingress/annotations/parser/main_test.go b/internal/ingress/annotations/parser/main_test.go index 318e024d3..beca49370 100644 --- a/internal/ingress/annotations/parser/main_test.go +++ b/internal/ingress/annotations/parser/main_test.go @@ -38,7 +38,7 @@ func buildIngress() *networking.Ingress { func TestGetBoolAnnotation(t *testing.T) { ing := buildIngress() - _, err := GetBoolAnnotation("", nil) + _, err := GetBoolAnnotation("", nil, nil) if err == nil { t.Errorf("expected error but retuned nil") } @@ -59,8 +59,8 @@ func TestGetBoolAnnotation(t *testing.T) { for _, test := range tests { data[GetAnnotationWithPrefix(test.field)] = test.value - - u, err := GetBoolAnnotation(test.field, ing) + ing.SetAnnotations(data) + u, err := GetBoolAnnotation(test.field, ing, nil) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) @@ -68,7 +68,7 @@ func TestGetBoolAnnotation(t *testing.T) { continue } if u != test.exp { - t.Errorf("%v: expected \"%v\" but \"%v\" was returned", test.name, test.exp, u) + t.Errorf("%v: expected \"%v\" but \"%v\" was returned, %+v", test.name, test.exp, u, ing) } delete(data, test.field) @@ -78,7 +78,7 @@ func TestGetBoolAnnotation(t *testing.T) { func TestGetStringAnnotation(t *testing.T) { ing := buildIngress() - _, err := GetStringAnnotation("", nil) + _, err := GetStringAnnotation("", nil, nil) if err == nil { t.Errorf("expected error but none returned") } @@ -109,7 +109,7 @@ rewrite (?i)/arcgis/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/serv for _, test := range tests { data[GetAnnotationWithPrefix(test.field)] = test.value - s, err := GetStringAnnotation(test.field, ing) + s, err := GetStringAnnotation(test.field, ing, nil) if test.expErr { if err == nil { t.Errorf("%v: expected error but none returned", test.name) @@ -133,7 +133,7 @@ rewrite (?i)/arcgis/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/serv func TestGetFloatAnnotation(t *testing.T) { ing := buildIngress() - _, err := GetFloatAnnotation("", nil) + _, err := GetFloatAnnotation("", nil, nil) if err == nil { t.Errorf("expected error but retuned nil") } @@ -156,7 +156,7 @@ func TestGetFloatAnnotation(t *testing.T) { for _, test := range tests { data[GetAnnotationWithPrefix(test.field)] = test.value - s, err := GetFloatAnnotation(test.field, ing) + s, err := GetFloatAnnotation(test.field, ing, nil) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) @@ -174,7 +174,7 @@ func TestGetFloatAnnotation(t *testing.T) { func TestGetIntAnnotation(t *testing.T) { ing := buildIngress() - _, err := GetIntAnnotation("", nil) + _, err := GetIntAnnotation("", nil, nil) if err == nil { t.Errorf("expected error but retuned nil") } @@ -196,7 +196,7 @@ func TestGetIntAnnotation(t *testing.T) { for _, test := range tests { data[GetAnnotationWithPrefix(test.field)] = test.value - s, err := GetIntAnnotation(test.field, ing) + s, err := GetIntAnnotation(test.field, ing, nil) if test.expErr { if err == nil { t.Errorf("%v: expected error but retuned nil", test.name) @@ -224,6 +224,7 @@ func TestStringToURL(t *testing.T) { }{ {"empty", "", "url scheme is empty", nil, true}, {"no scheme", "bar", "url scheme is empty", nil, true}, + {"invalid parse", "://lala.com", "://lala.com is not a valid URL: parse \"://lala.com\": missing protocol scheme", nil, true}, {"invalid host", "http://", "url host is empty", nil, true}, {"invalid host (multiple dots)", "http://foo..bar.com", "invalid url host", nil, true}, {"valid URL", validURL, "", validParsedURL, false}, diff --git a/internal/ingress/annotations/parser/validators.go b/internal/ingress/annotations/parser/validators.go new file mode 100644 index 000000000..e14b486eb --- /dev/null +++ b/internal/ingress/annotations/parser/validators.go @@ -0,0 +1,239 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package parser + +import ( + "errors" + "fmt" + "regexp" + "strconv" + "strings" + "time" + + networking "k8s.io/api/networking/v1" + machineryvalidation "k8s.io/apimachinery/pkg/api/validation" + ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" + "k8s.io/ingress-nginx/internal/net" + "k8s.io/klog/v2" +) + +type AnnotationValidator func(string) error + +const ( + AnnotationRiskLow AnnotationRisk = iota + AnnotationRiskMedium + AnnotationRiskHigh + AnnotationRiskCritical +) + +var ( + alphaNumericChars = `\-\.\_\~a-zA-Z0-9\/:` + extendedAlphaNumeric = alphaNumericChars + ", " + regexEnabledChars = regexp.QuoteMeta(`^$[](){}*+?|&=\`) + urlEnabledChars = regexp.QuoteMeta(`:?&=`) +) + +// IsValidRegex checks if the tested string can be used as a regex, but without any weird character. +// It includes regex characters for paths that may contain regexes +var IsValidRegex = regexp.MustCompile("^[/" + alphaNumericChars + regexEnabledChars + "]*$") + +// SizeRegex validates sizes understood by NGINX, like 1000, 100k, 1000M +var SizeRegex = regexp.MustCompile("^(?i)[0-9]+[bkmg]?$") + +// URLRegex is used to validate a URL but with only a specific set of characters: +// It is alphanumericChar + ":", "?", "&" +// A valid URL would be proto://something.com:port/something?arg=param +var ( + // URLIsValidRegex is used on full URLs, containing query strings (:, ? and &) + URLIsValidRegex = regexp.MustCompile("^[" + alphaNumericChars + urlEnabledChars + "]*$") + // BasicChars is alphanumeric and ".", "-", "_", "~" and ":", usually used on simple host:port/path composition. + // This combination can also be used on fields that may contain characters like / (as ns/name) + BasicCharsRegex = regexp.MustCompile("^[/" + alphaNumericChars + "]*$") + // ExtendedChars is alphanumeric and ".", "-", "_", "~" and ":" plus "," and spaces, usually used on simple host:port/path composition + ExtendedCharsRegex = regexp.MustCompile("^[/" + extendedAlphaNumeric + "]*$") + // CharsWithSpace is like basic chars, but includes the space character + CharsWithSpace = regexp.MustCompile("^[/" + alphaNumericChars + " ]*$") + // NGINXVariable allows entries with alphanumeric characters, -, _ and the special "$" + NGINXVariable = regexp.MustCompile(`^[A-Za-z0-9\-\_\$\{\}]*$`) + // RegexPathWithCapture allows entries that SHOULD start with "/" and may contain alphanumeric + capture + // character for regex based paths, like /something/$1/anything/$2 + RegexPathWithCapture = regexp.MustCompile(`^/[` + alphaNumericChars + `\/\$]*$`) + // HeadersVariable defines a regex that allows headers separated by comma + HeadersVariable = regexp.MustCompile(`^[A-Za-z0-9-_, ]*$`) + // URLWithNginxVariableRegex defines a url that can contain nginx variables. + // It is a risky operation + URLWithNginxVariableRegex = regexp.MustCompile("^[" + alphaNumericChars + urlEnabledChars + "$]*$") +) + +// ValidateArrayOfServerName validates if all fields on a Server name annotation are +// regexes. They can be *.something*, ~^www\d+\.example\.com$ but not fancy character +func ValidateArrayOfServerName(value string) error { + for _, fqdn := range strings.Split(value, ",") { + if err := ValidateServerName(fqdn); err != nil { + return err + } + } + return nil +} + +// ValidateServerName validates if the passed value is an acceptable server name. The server name +// can contain regex characters, as those are accepted values on nginx configuration +func ValidateServerName(value string) error { + value = strings.TrimSpace(value) + if !IsValidRegex.MatchString(value) { + return fmt.Errorf("value %s is invalid server name", value) + } + return nil +} + +// ValidateRegex receives a regex as an argument and uses it to validate +// the value of the field. +// Annotation can define if the spaces should be trimmed before validating the value +func ValidateRegex(regex regexp.Regexp, removeSpace bool) AnnotationValidator { + return func(s string) error { + if removeSpace { + s = strings.ReplaceAll(s, " ", "") + } + if !regex.MatchString(s) { + return fmt.Errorf("value %s is invalid", s) + } + return nil + } +} + +// ValidateOptions receives an array of valid options that can be the value of annotation. +// If no valid option is found, it will return an error +func ValidateOptions(options []string, caseSensitive bool, trimSpace bool) AnnotationValidator { + return func(s string) error { + if trimSpace { + s = strings.TrimSpace(s) + } + if !caseSensitive { + s = strings.ToLower(s) + } + for _, option := range options { + if s == option { + return nil + } + } + return fmt.Errorf("value does not match any valid option") + } +} + +// ValidateBool validates if the specified value is a bool +func ValidateBool(value string) error { + _, err := strconv.ParseBool(value) + return err +} + +// ValidateInt validates if the specified value is an integer +func ValidateInt(value string) error { + _, err := strconv.Atoi(value) + return err +} + +// ValidateCIDRs validates if the specified value is an array of IPs and CIDRs +func ValidateCIDRs(value string) error { + _, err := net.ParseCIDRs(value) + return err +} + +// ValidateDuration validates if the specified value is a valid time +func ValidateDuration(value string) error { + _, err := time.ParseDuration(value) + return err +} + +// ValidateNull always return null values and should not be widely used. +// It is used on the "snippet" annotations, as it is up to the admin to allow its +// usage, knowing it can be critical! +func ValidateNull(value string) error { + return nil +} + +// ValidateServiceName validates if a provided service name is a valid string +func ValidateServiceName(value string) error { + errs := machineryvalidation.NameIsDNS1035Label(value, false) + if len(errs) != 0 { + return fmt.Errorf("annotation does not contain a valid service name: %+v", errs) + } + return nil +} + +// checkAnnotations will check each annotation for: +// 1 - Does it contain the internal validation and docs config? +// 2 - Does the ingress contains annotations? (validate null pointers) +// 3 - Does it contains a validator? Should it contain a validator (not containing is a bug!) +// 4 - Does the annotation contain aliases? So we should use if the alias is defined an the annotation not. +// 4 - Runs the validator on the value +// It will return the full annotation name if all is fine +func checkAnnotation(name string, ing *networking.Ingress, fields AnnotationFields) (string, error) { + var validateFunc AnnotationValidator + if fields != nil { + config, ok := fields[name] + if !ok { + return "", fmt.Errorf("annotation does not contain a valid internal configuration, this is an Ingress Controller issue! Please raise an issue on github.com/kubernetes/ingress-nginx") + } + validateFunc = config.Validator + } + + if ing == nil || len(ing.GetAnnotations()) == 0 { + return "", ing_errors.ErrMissingAnnotations + } + + annotationFullName := GetAnnotationWithPrefix(name) + if annotationFullName == "" { + return "", ing_errors.ErrInvalidAnnotationName + } + + annotationValue := ing.GetAnnotations()[annotationFullName] + if fields != nil { + if validateFunc == nil { + return "", fmt.Errorf("annotation does not contain a validator. This is an ingress-controller bug. Please open an issue") + } + if annotationValue == "" { + for _, annotationAlias := range fields[name].AnnotationAliases { + tempAnnotationFullName := GetAnnotationWithPrefix(annotationAlias) + if aliasVal := ing.GetAnnotations()[tempAnnotationFullName]; aliasVal != "" { + annotationValue = aliasVal + annotationFullName = tempAnnotationFullName + break + } + } + } + // We don't run validation against empty values + if EnableAnnotationValidation && annotationValue != "" { + if err := validateFunc(annotationValue); err != nil { + klog.Warningf("validation error on ingress %s/%s: annotation %s contains invalid value %s", ing.GetNamespace(), ing.GetName(), name, annotationValue) + return "", ing_errors.NewValidationError(annotationFullName) + } + } + } + + return annotationFullName, nil +} + +func CheckAnnotationRisk(annotations map[string]string, maxrisk AnnotationRisk, config AnnotationFields) error { + var err error + for annotation := range annotations { + annPure := TrimAnnotationPrefix(annotation) + if cfg, ok := config[annPure]; ok && cfg.Risk > maxrisk { + err = errors.Join(err, fmt.Errorf("annotation %s is too risky for environment", annotation)) + } + } + return err +} diff --git a/internal/ingress/annotations/parser/validators_test.go b/internal/ingress/annotations/parser/validators_test.go new file mode 100644 index 000000000..2aa6cec37 --- /dev/null +++ b/internal/ingress/annotations/parser/validators_test.go @@ -0,0 +1,310 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package parser + +import ( + "fmt" + "testing" + + networking "k8s.io/api/networking/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +func TestValidateArrayOfServerName(t *testing.T) { + tests := []struct { + name string + value string + wantErr bool + }{ + { + name: "should accept common name", + value: "something.com,anything.com", + wantErr: false, + }, + { + name: "should accept wildcard name", + value: "*.something.com,otherthing.com", + wantErr: false, + }, + { + name: "should allow names with spaces between array and some regexes", + value: `~^www\d+\.example\.com$,something.com`, + wantErr: false, + }, + { + name: "should allow names with regexes", + value: `http://some.test.env.com:2121/$someparam=1&$someotherparam=2`, + wantErr: false, + }, + { + name: "should allow names with wildcard in middle common name", + value: "*.so*mething.com,bla.com", + wantErr: false, + }, + { + name: "should deny names with weird characters", + value: "something.com,lolo;xpto.com,nothing.com", + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := ValidateArrayOfServerName(tt.value); (err != nil) != tt.wantErr { + t.Errorf("ValidateArrayOfServerName() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_checkAnnotation(t *testing.T) { + type args struct { + name string + ing *networking.Ingress + fields AnnotationFields + } + tests := []struct { + name string + args args + want string + wantErr bool + }{ + { + name: "null ingress should error", + want: "", + args: args{ + name: "some-random-annotation", + }, + wantErr: true, + }, + { + name: "not having a validator for a specific annotation is a bug", + want: "", + args: args{ + name: "some-new-invalid-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{ + GetAnnotationWithPrefix("some-new-invalid-annotation"): "xpto", + }, + }, + }, + fields: AnnotationFields{ + "otherannotation": AnnotationConfig{ + Validator: func(value string) error { return nil }, + }, + }, + }, + wantErr: true, + }, + { + name: "annotationconfig found and no validation func defined on annotation is a bug", + want: "", + args: args{ + name: "some-new-invalid-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{ + GetAnnotationWithPrefix("some-new-invalid-annotation"): "xpto", + }, + }, + }, + fields: AnnotationFields{ + "some-new-invalid-annotation": AnnotationConfig{}, + }, + }, + wantErr: true, + }, + { + name: "no annotation can turn into a null pointer and should fail", + want: "", + args: args{ + name: "some-new-invalid-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{}, + }, + fields: AnnotationFields{ + "some-new-invalid-annotation": AnnotationConfig{}, + }, + }, + wantErr: true, + }, + { + name: "no AnnotationField config should bypass validations", + want: GetAnnotationWithPrefix("some-valid-annotation"), + args: args{ + name: "some-valid-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{ + GetAnnotationWithPrefix("some-valid-annotation"): "xpto", + }, + }, + }, + }, + wantErr: false, + }, + { + name: "annotation with invalid value should fail", + want: "", + args: args{ + name: "some-new-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{ + GetAnnotationWithPrefix("some-new-annotation"): "xpto1", + }, + }, + }, + fields: AnnotationFields{ + "some-new-annotation": AnnotationConfig{ + Validator: func(value string) error { + if value != "xpto" { + return fmt.Errorf("this is an error") + } + return nil + }, + }, + }, + }, + wantErr: true, + }, + { + name: "annotation with valid value should pass", + want: GetAnnotationWithPrefix("some-other-annotation"), + args: args{ + name: "some-other-annotation", + ing: &networking.Ingress{ + ObjectMeta: v1.ObjectMeta{ + Annotations: map[string]string{ + GetAnnotationWithPrefix("some-other-annotation"): "xpto", + }, + }, + }, + fields: AnnotationFields{ + "some-other-annotation": AnnotationConfig{ + Validator: func(value string) error { + if value != "xpto" { + return fmt.Errorf("this is an error") + } + return nil + }, + }, + }, + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := checkAnnotation(tt.args.name, tt.args.ing, tt.args.fields) + if (err != nil) != tt.wantErr { + t.Errorf("checkAnnotation() error = %v, wantErr %v", err, tt.wantErr) + return + } + if got != tt.want { + t.Errorf("checkAnnotation() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCheckAnnotationRisk(t *testing.T) { + + tests := []struct { + name string + annotations map[string]string + maxrisk AnnotationRisk + config AnnotationFields + wantErr bool + }{ + { + name: "high risk should not be accepted with maximum medium", + maxrisk: AnnotationRiskMedium, + annotations: map[string]string{ + "nginx.ingress.kubernetes.io/bla": "blo", + "nginx.ingress.kubernetes.io/bli": "bl3", + }, + config: AnnotationFields{ + "bla": { + Risk: AnnotationRiskHigh, + }, + "bli": { + Risk: AnnotationRiskMedium, + }, + }, + wantErr: true, + }, + { + name: "high risk should be accepted with maximum critical", + maxrisk: AnnotationRiskCritical, + annotations: map[string]string{ + "nginx.ingress.kubernetes.io/bla": "blo", + "nginx.ingress.kubernetes.io/bli": "bl3", + }, + config: AnnotationFields{ + "bla": { + Risk: AnnotationRiskHigh, + }, + "bli": { + Risk: AnnotationRiskMedium, + }, + }, + wantErr: false, + }, + { + name: "low risk should be accepted with maximum low", + maxrisk: AnnotationRiskLow, + annotations: map[string]string{ + "nginx.ingress.kubernetes.io/bla": "blo", + "nginx.ingress.kubernetes.io/bli": "bl3", + }, + config: AnnotationFields{ + "bla": { + Risk: AnnotationRiskLow, + }, + "bli": { + Risk: AnnotationRiskLow, + }, + }, + wantErr: false, + }, + { + name: "critical risk should be accepted with maximum critical", + maxrisk: AnnotationRiskCritical, + annotations: map[string]string{ + "nginx.ingress.kubernetes.io/bla": "blo", + "nginx.ingress.kubernetes.io/bli": "bl3", + }, + config: AnnotationFields{ + "bla": { + Risk: AnnotationRiskCritical, + }, + "bli": { + Risk: AnnotationRiskCritical, + }, + }, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if err := CheckAnnotationRisk(tt.annotations, tt.maxrisk, tt.config); (err != nil) != tt.wantErr { + t.Errorf("CheckAnnotationRisk() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/internal/ingress/annotations/portinredirect/main.go b/internal/ingress/annotations/portinredirect/main.go index 25d665558..7392ea3a6 100644 --- a/internal/ingress/annotations/portinredirect/main.go +++ b/internal/ingress/annotations/portinredirect/main.go @@ -23,22 +23,51 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + portsInRedirectAnnotation = "use-port-in-redirects" +) + +var portsInRedirectAnnotations = parser.Annotation{ + Group: "redirect", + Annotations: parser.AnnotationFields{ + portsInRedirectAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Enables or disables specifying the port in absolute redirects issued by nginx.`, + }, + }, +} + type portInRedirect struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new port in redirect annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return portInRedirect{r} + return portInRedirect{ + r: r, + annotationConfig: portsInRedirectAnnotations, + } } // Parse parses the annotations contained in the ingress // rule used to indicate if the redirects must func (a portInRedirect) Parse(ing *networking.Ingress) (interface{}, error) { - up, err := parser.GetBoolAnnotation("use-port-in-redirects", ing) + up, err := parser.GetBoolAnnotation(portsInRedirectAnnotation, ing, a.annotationConfig.Annotations) if err != nil { return a.r.GetDefaultBackend().UsePortInRedirects, nil } return up, nil } + +func (a portInRedirect) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a portInRedirect) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, portsInRedirectAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/portinredirect/main_test.go b/internal/ingress/annotations/portinredirect/main_test.go index 71afd4cdf..f5806e01a 100644 --- a/internal/ingress/annotations/portinredirect/main_test.go +++ b/internal/ingress/annotations/portinredirect/main_test.go @@ -17,7 +17,6 @@ limitations under the License. package portinredirect import ( - "fmt" "testing" api "k8s.io/api/core/v1" @@ -84,23 +83,24 @@ func (m mockBackend) GetDefaultBackend() defaults.Backend { func TestPortInRedirect(t *testing.T) { tests := []struct { title string - usePort *bool + usePort string def bool exp bool }{ - {"false - default false", newFalse(), false, false}, - {"false - default true", newFalse(), true, false}, - {"no annotation - default false", nil, false, false}, - {"no annotation - default true", nil, true, true}, - {"true - default true", newTrue(), true, true}, + {"false - default false", "false", false, false}, + {"false - default true", "false", true, false}, + {"no annotation - default false", "", false, false}, + {"no annotation - default false", "not-a-bool", false, false}, + {"no annotation - default true", "", true, true}, + {"true - default true", "true", true, true}, } for _, test := range tests { ing := buildIngress() data := map[string]string{} - if test.usePort != nil { - data[parser.GetAnnotationWithPrefix("use-port-in-redirects")] = fmt.Sprintf("%v", *test.usePort) + if test.usePort != "" { + data[parser.GetAnnotationWithPrefix(portsInRedirectAnnotation)] = test.usePort } ing.SetAnnotations(data) @@ -118,13 +118,3 @@ func TestPortInRedirect(t *testing.T) { } } } - -func newTrue() *bool { - b := true - return &b -} - -func newFalse() *bool { - b := false - return &b -} diff --git a/internal/ingress/annotations/proxy/main.go b/internal/ingress/annotations/proxy/main.go index 3a89b8855..a2d10ca90 100644 --- a/internal/ingress/annotations/proxy/main.go +++ b/internal/ingress/annotations/proxy/main.go @@ -17,12 +17,150 @@ limitations under the License. package proxy import ( + "regexp" + networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + proxyConnectTimeoutAnnotation = "proxy-connect-timeout" + proxySendTimeoutAnnotation = "proxy-send-timeout" + proxyReadTimeoutAnnotation = "proxy-read-timeout" + proxyBuffersNumberAnnotation = "proxy-buffers-number" + proxyBufferSizeAnnotation = "proxy-buffer-size" + proxyCookiePathAnnotation = "proxy-cookie-path" + proxyCookieDomainAnnotation = "proxy-cookie-domain" + proxyBodySizeAnnotation = "proxy-body-size" + proxyNextUpstreamAnnotation = "proxy-next-upstream" + proxyNextUpstreamTimeoutAnnotation = "proxy-next-upstream-timeout" + proxyNextUpstreamTriesAnnotation = "proxy-next-upstream-tries" + proxyRequestBufferingAnnotation = "proxy-request-buffering" + proxyRedirectFromAnnotation = "proxy-redirect-from" + proxyRedirectToAnnotation = "proxy-redirect-to" + proxyBufferingAnnotation = "proxy-buffering" + proxyHTTPVersionAnnotation = "proxy-http-version" + proxyMaxTempFileSizeAnnotation = "proxy-max-temp-file-size" +) + +var ( + validUpstreamAnnotation = regexp.MustCompile(`^((error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_403|http_404|http_429|non_idempotent|off)\s?)+$`) +) + +var proxyAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + proxyConnectTimeoutAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows setting the timeout in seconds of the connect operation to the backend.`, + }, + proxySendTimeoutAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows setting the timeout in seconds of the send operation to the backend.`, + }, + proxyReadTimeoutAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation allows setting the timeout in seconds of the read operation to the backend.`, + }, + proxyBuffersNumberAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation sets the number of the buffers in proxy_buffers used for reading the first part of the response received from the proxied server. + By default proxy buffers number is set as 4`, + }, + proxyBufferSizeAnnotation: { + Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation sets the size of the buffer proxy_buffer_size used for reading the first part of the response received from the proxied server. + By default proxy buffer size is set as "4k".`, + }, + proxyCookiePathAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation sets a text that should be changed in the path attribute of the "Set-Cookie" header fields of a proxied server response.`, + }, + proxyCookieDomainAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation ets a text that should be changed in the domain attribute of the "Set-Cookie" header fields of a proxied server response.`, + }, + proxyBodySizeAnnotation: { + Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows setting the maximum allowed size of a client request body.`, + }, + proxyNextUpstreamAnnotation: { + Validator: parser.ValidateRegex(*validUpstreamAnnotation, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines when the next upstream should be used. + This annotation reflect the directive https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_next_upstream + and only the allowed values on upstream are allowed here.`, + }, + proxyNextUpstreamTimeoutAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation limits the time during which a request can be passed to the next server`, + }, + proxyNextUpstreamTriesAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation limits the number of possible tries for passing a request to the next server`, + }, + proxyRequestBufferingAnnotation: { + Validator: parser.ValidateOptions([]string{"on", "off"}, true, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables or disables buffering of a client request body.`, + }, + proxyRedirectFromAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `The annotations proxy-redirect-from and proxy-redirect-to will set the first and second parameters of NGINX's proxy_redirect directive respectively`, + }, + proxyRedirectToAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `The annotations proxy-redirect-from and proxy-redirect-to will set the first and second parameters of NGINX's proxy_redirect directive respectively`, + }, + proxyBufferingAnnotation: { + Validator: parser.ValidateOptions([]string{"on", "off"}, true, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables or disables buffering of responses from the proxied server. It can be "on" or "off"`, + }, + proxyHTTPVersionAnnotation: { + Validator: parser.ValidateOptions([]string{"1.0", "1.1"}, true, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotations sets the HTTP protocol version for proxying. Can be "1.0" or "1.1".`, + }, + proxyMaxTempFileSizeAnnotation: { + Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines the maximum size of a temporary file when buffering responses.`, + }, + }, +} + // Config returns the proxy timeout to use in the upstream server/s type Config struct { BodySize string `json:"bodySize"` @@ -109,12 +247,15 @@ func (l1 *Config) Equal(l2 *Config) bool { } type proxy struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new reverse proxy configuration annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return proxy{r} + return proxy{r: r, + annotationConfig: proxyAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -125,90 +266,99 @@ func (a proxy) Parse(ing *networking.Ingress) (interface{}, error) { var err error - config.ConnectTimeout, err = parser.GetIntAnnotation("proxy-connect-timeout", ing) + config.ConnectTimeout, err = parser.GetIntAnnotation(proxyConnectTimeoutAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ConnectTimeout = defBackend.ProxyConnectTimeout } - config.SendTimeout, err = parser.GetIntAnnotation("proxy-send-timeout", ing) + config.SendTimeout, err = parser.GetIntAnnotation(proxySendTimeoutAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.SendTimeout = defBackend.ProxySendTimeout } - config.ReadTimeout, err = parser.GetIntAnnotation("proxy-read-timeout", ing) + config.ReadTimeout, err = parser.GetIntAnnotation(proxyReadTimeoutAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ReadTimeout = defBackend.ProxyReadTimeout } - config.BuffersNumber, err = parser.GetIntAnnotation("proxy-buffers-number", ing) + config.BuffersNumber, err = parser.GetIntAnnotation(proxyBuffersNumberAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.BuffersNumber = defBackend.ProxyBuffersNumber } - config.BufferSize, err = parser.GetStringAnnotation("proxy-buffer-size", ing) + config.BufferSize, err = parser.GetStringAnnotation(proxyBufferSizeAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.BufferSize = defBackend.ProxyBufferSize } - config.CookiePath, err = parser.GetStringAnnotation("proxy-cookie-path", ing) + config.CookiePath, err = parser.GetStringAnnotation(proxyCookiePathAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.CookiePath = defBackend.ProxyCookiePath } - config.CookieDomain, err = parser.GetStringAnnotation("proxy-cookie-domain", ing) + config.CookieDomain, err = parser.GetStringAnnotation(proxyCookieDomainAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.CookieDomain = defBackend.ProxyCookieDomain } - config.BodySize, err = parser.GetStringAnnotation("proxy-body-size", ing) + config.BodySize, err = parser.GetStringAnnotation(proxyBodySizeAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.BodySize = defBackend.ProxyBodySize } - config.NextUpstream, err = parser.GetStringAnnotation("proxy-next-upstream", ing) + config.NextUpstream, err = parser.GetStringAnnotation(proxyNextUpstreamAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.NextUpstream = defBackend.ProxyNextUpstream } - config.NextUpstreamTimeout, err = parser.GetIntAnnotation("proxy-next-upstream-timeout", ing) + config.NextUpstreamTimeout, err = parser.GetIntAnnotation(proxyNextUpstreamTimeoutAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.NextUpstreamTimeout = defBackend.ProxyNextUpstreamTimeout } - config.NextUpstreamTries, err = parser.GetIntAnnotation("proxy-next-upstream-tries", ing) + config.NextUpstreamTries, err = parser.GetIntAnnotation(proxyNextUpstreamTriesAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.NextUpstreamTries = defBackend.ProxyNextUpstreamTries } - config.RequestBuffering, err = parser.GetStringAnnotation("proxy-request-buffering", ing) + config.RequestBuffering, err = parser.GetStringAnnotation(proxyRequestBufferingAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.RequestBuffering = defBackend.ProxyRequestBuffering } - config.ProxyRedirectFrom, err = parser.GetStringAnnotation("proxy-redirect-from", ing) + config.ProxyRedirectFrom, err = parser.GetStringAnnotation(proxyRedirectFromAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ProxyRedirectFrom = defBackend.ProxyRedirectFrom } - config.ProxyRedirectTo, err = parser.GetStringAnnotation("proxy-redirect-to", ing) + config.ProxyRedirectTo, err = parser.GetStringAnnotation(proxyRedirectToAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ProxyRedirectTo = defBackend.ProxyRedirectTo } - config.ProxyBuffering, err = parser.GetStringAnnotation("proxy-buffering", ing) + config.ProxyBuffering, err = parser.GetStringAnnotation(proxyBufferingAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ProxyBuffering = defBackend.ProxyBuffering } - config.ProxyHTTPVersion, err = parser.GetStringAnnotation("proxy-http-version", ing) + config.ProxyHTTPVersion, err = parser.GetStringAnnotation(proxyHTTPVersionAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ProxyHTTPVersion = defBackend.ProxyHTTPVersion } - config.ProxyMaxTempFileSize, err = parser.GetStringAnnotation("proxy-max-temp-file-size", ing) + config.ProxyMaxTempFileSize, err = parser.GetStringAnnotation(proxyMaxTempFileSizeAnnotation, ing, a.annotationConfig.Annotations) if err != nil { config.ProxyMaxTempFileSize = defBackend.ProxyMaxTempFileSize } return config, nil } + +func (a proxy) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a proxy) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, proxyAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/proxy/main_test.go b/internal/ingress/annotations/proxy/main_test.go index e377ccb19..fa185551b 100644 --- a/internal/ingress/annotations/proxy/main_test.go +++ b/internal/ingress/annotations/proxy/main_test.go @@ -161,6 +161,74 @@ func TestProxy(t *testing.T) { } } +func TestProxyComplex(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix("proxy-connect-timeout")] = "1" + data[parser.GetAnnotationWithPrefix("proxy-send-timeout")] = "2" + data[parser.GetAnnotationWithPrefix("proxy-read-timeout")] = "3" + data[parser.GetAnnotationWithPrefix("proxy-buffers-number")] = "8" + data[parser.GetAnnotationWithPrefix("proxy-buffer-size")] = "1k" + data[parser.GetAnnotationWithPrefix("proxy-body-size")] = "2k" + data[parser.GetAnnotationWithPrefix("proxy-next-upstream")] = "error http_502" + data[parser.GetAnnotationWithPrefix("proxy-next-upstream-timeout")] = "5" + data[parser.GetAnnotationWithPrefix("proxy-next-upstream-tries")] = "3" + data[parser.GetAnnotationWithPrefix("proxy-request-buffering")] = "off" + data[parser.GetAnnotationWithPrefix("proxy-buffering")] = "on" + data[parser.GetAnnotationWithPrefix("proxy-http-version")] = "1.0" + data[parser.GetAnnotationWithPrefix("proxy-max-temp-file-size")] = "128k" + ing.SetAnnotations(data) + + i, err := NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Fatalf("unexpected error parsing a valid") + } + p, ok := i.(*Config) + if !ok { + t.Fatalf("expected a Config type") + } + if p.ConnectTimeout != 1 { + t.Errorf("expected 1 as connect-timeout but returned %v", p.ConnectTimeout) + } + if p.SendTimeout != 2 { + t.Errorf("expected 2 as send-timeout but returned %v", p.SendTimeout) + } + if p.ReadTimeout != 3 { + t.Errorf("expected 3 as read-timeout but returned %v", p.ReadTimeout) + } + if p.BuffersNumber != 8 { + t.Errorf("expected 8 as proxy-buffers-number but returned %v", p.BuffersNumber) + } + if p.BufferSize != "1k" { + t.Errorf("expected 1k as buffer-size but returned %v", p.BufferSize) + } + if p.BodySize != "2k" { + t.Errorf("expected 2k as body-size but returned %v", p.BodySize) + } + if p.NextUpstream != "error http_502" { + t.Errorf("expected off as next-upstream but returned %v", p.NextUpstream) + } + if p.NextUpstreamTimeout != 5 { + t.Errorf("expected 5 as next-upstream-timeout but returned %v", p.NextUpstreamTimeout) + } + if p.NextUpstreamTries != 3 { + t.Errorf("expected 3 as next-upstream-tries but returned %v", p.NextUpstreamTries) + } + if p.RequestBuffering != "off" { + t.Errorf("expected off as request-buffering but returned %v", p.RequestBuffering) + } + if p.ProxyBuffering != "on" { + t.Errorf("expected on as proxy-buffering but returned %v", p.ProxyBuffering) + } + if p.ProxyHTTPVersion != "1.0" { + t.Errorf("expected 1.0 as proxy-http-version but returned %v", p.ProxyHTTPVersion) + } + if p.ProxyMaxTempFileSize != "128k" { + t.Errorf("expected 128k as proxy-max-temp-file-size but returned %v", p.ProxyMaxTempFileSize) + } +} + func TestProxyWithNoAnnotation(t *testing.T) { ing := buildIngress() diff --git a/internal/ingress/annotations/proxyssl/main.go b/internal/ingress/annotations/proxyssl/main.go index 22f49b3eb..40ee18aa0 100644 --- a/internal/ingress/annotations/proxyssl/main.go +++ b/internal/ingress/annotations/proxyssl/main.go @@ -24,9 +24,11 @@ import ( networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/ingress-nginx/internal/k8s" + "k8s.io/klog/v2" ) const ( @@ -39,9 +41,73 @@ const ( var ( proxySSLOnOffRegex = regexp.MustCompile(`^(on|off)$`) - proxySSLProtocolRegex = regexp.MustCompile(`^(SSLv2|SSLv3|TLSv1|TLSv1\.1|TLSv1\.2|TLSv1\.3)$`) + proxySSLProtocolRegex = regexp.MustCompile(`^(SSLv2|SSLv3|TLSv1|TLSv1\.1|TLSv1\.2|TLSv1\.3| )*$`) + proxySSLCiphersRegex = regexp.MustCompile(`^[A-Za-z0-9\+\:\_\-\!]*$`) ) +const ( + proxySSLSecretAnnotation = "proxy-ssl-secret" + proxySSLCiphersAnnotation = "proxy-ssl-ciphers" + proxySSLProtocolsAnnotation = "proxy-ssl-protocols" + proxySSLNameAnnotation = "proxy-ssl-name" + proxySSLVerifyAnnotation = "proxy-ssl-verify" + proxySSLVerifyDepthAnnotation = "proxy-ssl-verify-depth" + proxySSLServerNameAnnotation = "proxy-ssl-server-name" +) + +var proxySSLAnnotation = parser.Annotation{ + Group: "proxy", + Annotations: parser.AnnotationFields{ + proxySSLSecretAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation specifies a Secret with the certificate tls.crt, key tls.key in PEM format used for authentication to a proxied HTTPS server. + It should also contain trusted CA certificates ca.crt in PEM format used to verify the certificate of the proxied HTTPS server. + This annotation expects the Secret name in the form "namespace/secretName" + Just secrets on the same namespace of the ingress can be used.`, + }, + proxySSLCiphersAnnotation: { + Validator: parser.ValidateRegex(*proxySSLCiphersRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation Specifies the enabled ciphers for requests to a proxied HTTPS server. + The ciphers are specified in the format understood by the OpenSSL library.`, + }, + proxySSLProtocolsAnnotation: { + Validator: parser.ValidateRegex(*proxySSLProtocolRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables the specified protocols for requests to a proxied HTTPS server.`, + }, + proxySSLNameAnnotation: { + Validator: parser.ValidateServerName, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskHigh, + Documentation: `This annotation allows to set proxy_ssl_name. This allows overriding the server name used to verify the certificate of the proxied HTTPS server. + This value is also passed through SNI when a connection is established to the proxied HTTPS server.`, + }, + proxySSLVerifyAnnotation: { + Validator: parser.ValidateRegex(*proxySSLOnOffRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables or disables verification of the proxied HTTPS server certificate. (default: off)`, + }, + proxySSLVerifyDepthAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation Sets the verification depth in the proxied HTTPS server certificates chain. (default: 1).`, + }, + proxySSLServerNameAnnotation: { + Validator: parser.ValidateRegex(*proxySSLOnOffRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables passing of the server name through TLS Server Name Indication extension (SNI, RFC 6066) when establishing a connection with the proxied HTTPS server.`, + }, + }, +} + // Config contains the AuthSSLCert used for mutual authentication // and the configured VerifyDepth type Config struct { @@ -85,11 +151,14 @@ func (pssl1 *Config) Equal(pssl2 *Config) bool { // NewParser creates a new TLS authentication annotation parser func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { - return proxySSL{resolver} + return proxySSL{ + r: resolver, + annotationConfig: proxySSLAnnotation} } type proxySSL struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } func sortProtocols(protocols string) string { @@ -120,16 +189,22 @@ func (p proxySSL) Parse(ing *networking.Ingress) (interface{}, error) { var err error config := &Config{} - proxysslsecret, err := parser.GetStringAnnotation("proxy-ssl-secret", ing) + proxysslsecret, err := parser.GetStringAnnotation(proxySSLSecretAnnotation, ing, p.annotationConfig.Annotations) if err != nil { return &Config{}, err } - _, _, err = k8s.ParseNameNS(proxysslsecret) + ns, _, err := k8s.ParseNameNS(proxysslsecret) if err != nil { return &Config{}, ing_errors.NewLocationDenied(err.Error()) } + secCfg := p.r.GetSecurityConfiguration() + // We don't accept different namespaces for secrets. + if !secCfg.AllowCrossNamespaceResources && ns != ing.Namespace { + return &Config{}, ing_errors.NewLocationDenied("cross namespace secrets are not supported") + } + proxyCert, err := p.r.GetAuthCertificate(proxysslsecret) if err != nil { e := fmt.Errorf("error obtaining certificate: %w", err) @@ -137,37 +212,55 @@ func (p proxySSL) Parse(ing *networking.Ingress) (interface{}, error) { } config.AuthSSLCert = *proxyCert - config.Ciphers, err = parser.GetStringAnnotation("proxy-ssl-ciphers", ing) + config.Ciphers, err = parser.GetStringAnnotation(proxySSLCiphersAnnotation, ing, p.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("invalid value passed to proxy-ssl-ciphers, defaulting to %s", defaultProxySSLCiphers) + } config.Ciphers = defaultProxySSLCiphers } - config.Protocols, err = parser.GetStringAnnotation("proxy-ssl-protocols", ing) + config.Protocols, err = parser.GetStringAnnotation(proxySSLProtocolsAnnotation, ing, p.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("invalid value passed to proxy-ssl-protocols, defaulting to %s", defaultProxySSLProtocols) + } config.Protocols = defaultProxySSLProtocols } else { config.Protocols = sortProtocols(config.Protocols) } - config.ProxySSLName, err = parser.GetStringAnnotation("proxy-ssl-name", ing) + config.ProxySSLName, err = parser.GetStringAnnotation(proxySSLNameAnnotation, ing, p.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("invalid value passed to proxy-ssl-name, defaulting to empty") + } config.ProxySSLName = "" } - config.Verify, err = parser.GetStringAnnotation("proxy-ssl-verify", ing) + config.Verify, err = parser.GetStringAnnotation(proxySSLVerifyAnnotation, ing, p.annotationConfig.Annotations) if err != nil || !proxySSLOnOffRegex.MatchString(config.Verify) { config.Verify = defaultProxySSLVerify } - config.VerifyDepth, err = parser.GetIntAnnotation("proxy-ssl-verify-depth", ing) + config.VerifyDepth, err = parser.GetIntAnnotation(proxySSLVerifyDepthAnnotation, ing, p.annotationConfig.Annotations) if err != nil || config.VerifyDepth == 0 { config.VerifyDepth = defaultProxySSLVerifyDepth } - config.ProxySSLServerName, err = parser.GetStringAnnotation("proxy-ssl-server-name", ing) + config.ProxySSLServerName, err = parser.GetStringAnnotation(proxySSLServerNameAnnotation, ing, p.annotationConfig.Annotations) if err != nil || !proxySSLOnOffRegex.MatchString(config.ProxySSLServerName) { config.ProxySSLServerName = defaultProxySSLServerName } return config, nil } + +func (p proxySSL) GetDocumentation() parser.AnnotationFields { + return p.annotationConfig.Annotations +} + +func (a proxySSL) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, proxySSLAnnotation.Annotations) +} diff --git a/internal/ingress/annotations/proxyssl/main_test.go b/internal/ingress/annotations/proxyssl/main_test.go index 29949796c..edd65343e 100644 --- a/internal/ingress/annotations/proxyssl/main_test.go +++ b/internal/ingress/annotations/proxyssl/main_test.go @@ -93,7 +93,7 @@ func TestAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("proxy-ssl-secret")] = "default/demo-secret" + data[parser.GetAnnotationWithPrefix(proxySSLSecretAnnotation)] = "default/demo-secret" data[parser.GetAnnotationWithPrefix("proxy-ssl-ciphers")] = "HIGH:-SHA" data[parser.GetAnnotationWithPrefix("proxy-ssl-name")] = "$host" data[parser.GetAnnotationWithPrefix("proxy-ssl-protocols")] = "TLSv1.3 SSLv2 TLSv1 TLSv1.2" diff --git a/internal/ingress/annotations/ratelimit/main.go b/internal/ingress/annotations/ratelimit/main.go index 84a5f10f0..39161a2c0 100644 --- a/internal/ingress/annotations/ratelimit/main.go +++ b/internal/ingress/annotations/ratelimit/main.go @@ -24,6 +24,7 @@ import ( networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/ingress-nginx/internal/net" "k8s.io/ingress-nginx/pkg/util/sets" @@ -58,7 +59,7 @@ type Config struct { ID string `json:"id"` - Whitelist []string `json:"whitelist"` + Allowlist []string `json:"allowlist"` } // Equal tests for equality between two RateLimit types @@ -90,11 +91,11 @@ func (rt1 *Config) Equal(rt2 *Config) bool { if rt1.Name != rt2.Name { return false } - if len(rt1.Whitelist) != len(rt2.Whitelist) { + if len(rt1.Allowlist) != len(rt2.Allowlist) { return false } - return sets.StringElementsMatch(rt1.Whitelist, rt2.Whitelist) + return sets.StringElementsMatch(rt1.Allowlist, rt2.Allowlist) } // Zone returns information about the NGINX rate limit (limit_req_zone) @@ -131,43 +132,121 @@ func (z1 *Zone) Equal(z2 *Zone) bool { return true } +const ( + limitRateAnnotation = "limit-rate" + limitRateAfterAnnotation = "limit-rate-after" + limitRateRPMAnnotation = "limit-rpm" + limitRateRPSAnnotation = "limit-rps" + limitRateConnectionsAnnotation = "limit-connections" + limitRateBurstMultiplierAnnotation = "limit-burst-multiplier" + limitWhitelistAnnotation = "limit-whitelist" // This annotation is an alias for limit-allowlist + limitAllowlistAnnotation = "limit-allowlist" +) + +var rateLimitAnnotations = parser.Annotation{ + Group: "rate-limit", + Annotations: parser.AnnotationFields{ + limitRateAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Limits the rate of response transmission to a client. The rate is specified in bytes per second. + The zero value disables rate limiting. The limit is set per a request, and so if a client simultaneously opens two connections, the overall rate will be twice as much as the specified limit. + References: https://nginx.org/en/docs/http/ngx_http_core_module.html#limit_rate`, + }, + limitRateAfterAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Sets the initial amount after which the further transmission of a response to a client will be rate limited.`, + }, + limitRateRPMAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Requests per minute that will be allowed.`, + }, + limitRateRPSAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Requests per second that will be allowed.`, + }, + limitRateConnectionsAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Number of connections that will be allowed`, + }, + limitRateBurstMultiplierAnnotation: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `Burst multiplier for a limit-rate enabled location.`, + }, + limitAllowlistAnnotation: { + Validator: parser.ValidateCIDRs, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `List of CIDR/IP addresses that will not be rate-limited.`, + AnnotationAliases: []string{limitWhitelistAnnotation}, + }, + }, +} + type ratelimit struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new ratelimit annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return ratelimit{r} + return ratelimit{ + r: r, + annotationConfig: rateLimitAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress // rule used to rewrite the defined paths func (a ratelimit) Parse(ing *networking.Ingress) (interface{}, error) { defBackend := a.r.GetDefaultBackend() - lr, err := parser.GetIntAnnotation("limit-rate", ing) + lr, err := parser.GetIntAnnotation(limitRateAnnotation, ing, a.annotationConfig.Annotations) if err != nil { lr = defBackend.LimitRate } - lra, err := parser.GetIntAnnotation("limit-rate-after", ing) + lra, err := parser.GetIntAnnotation(limitRateAfterAnnotation, ing, a.annotationConfig.Annotations) if err != nil { lra = defBackend.LimitRateAfter } - rpm, _ := parser.GetIntAnnotation("limit-rpm", ing) - rps, _ := parser.GetIntAnnotation("limit-rps", ing) - conn, _ := parser.GetIntAnnotation("limit-connections", ing) - burstMultiplier, err := parser.GetIntAnnotation("limit-burst-multiplier", ing) + rpm, err := parser.GetIntAnnotation(limitRateRPMAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsValidationError(err) { + return nil, err + } + rps, err := parser.GetIntAnnotation(limitRateRPSAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsValidationError(err) { + return nil, err + } + conn, err := parser.GetIntAnnotation(limitRateConnectionsAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsValidationError(err) { + return nil, err + } + burstMultiplier, err := parser.GetIntAnnotation(limitRateBurstMultiplierAnnotation, ing, a.annotationConfig.Annotations) if err != nil { burstMultiplier = defBurst } - val, _ := parser.GetStringAnnotation("limit-whitelist", ing) - - cidrs, err := net.ParseCIDRs(val) - if err != nil { + val, err := parser.GetStringAnnotation(limitAllowlistAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && errors.IsValidationError(err) { return nil, err } + cidrs, errCidr := net.ParseCIDRs(val) + if errCidr != nil { + return nil, errCidr + } + if rpm == 0 && rps == 0 && conn == 0 { return &Config{ Connections: Zone{}, @@ -203,7 +282,7 @@ func (a ratelimit) Parse(ing *networking.Ingress) (interface{}, error) { LimitRateAfter: lra, Name: zoneName, ID: encode(zoneName), - Whitelist: cidrs, + Allowlist: cidrs, }, nil } @@ -211,3 +290,12 @@ func encode(s string) string { str := base64.URLEncoding.EncodeToString([]byte(s)) return strings.Replace(str, "=", "", -1) } + +func (a ratelimit) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a ratelimit) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, rateLimitAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/ratelimit/main_test.go b/internal/ingress/annotations/ratelimit/main_test.go index 9f101cc3b..d3a2cc0e9 100644 --- a/internal/ingress/annotations/ratelimit/main_test.go +++ b/internal/ingress/annotations/ratelimit/main_test.go @@ -25,6 +25,7 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/defaults" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) @@ -85,8 +86,8 @@ func (m mockBackend) GetDefaultBackend() defaults.Backend { func TestWithoutAnnotations(t *testing.T) { ing := buildIngress() _, err := NewParser(mockBackend{}).Parse(ing) - if err != nil { - t.Error("unexpected error with ingress without annotations") + if err != nil && !errors.IsMissingAnnotations(err) { + t.Errorf("unexpected error with ingress without annotations: %s", err) } } @@ -94,22 +95,22 @@ func TestRateLimiting(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("limit-connections")] = "0" - data[parser.GetAnnotationWithPrefix("limit-rps")] = "0" - data[parser.GetAnnotationWithPrefix("limit-rpm")] = "0" + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "0" + data[parser.GetAnnotationWithPrefix(limitRateRPSAnnotation)] = "0" + data[parser.GetAnnotationWithPrefix(limitRateRPMAnnotation)] = "0" ing.SetAnnotations(data) _, err := NewParser(mockBackend{}).Parse(ing) if err != nil { - t.Errorf("unexpected error with invalid limits (0)") + t.Errorf("unexpected error with invalid limits (0): %s", err) } data = map[string]string{} - data[parser.GetAnnotationWithPrefix("limit-connections")] = "5" - data[parser.GetAnnotationWithPrefix("limit-rps")] = "100" - data[parser.GetAnnotationWithPrefix("limit-rpm")] = "10" - data[parser.GetAnnotationWithPrefix("limit-rate-after")] = "100" - data[parser.GetAnnotationWithPrefix("limit-rate")] = "10" + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "5" + data[parser.GetAnnotationWithPrefix(limitRateRPSAnnotation)] = "100" + data[parser.GetAnnotationWithPrefix(limitRateRPMAnnotation)] = "10" + data[parser.GetAnnotationWithPrefix(limitRateAfterAnnotation)] = "100" + data[parser.GetAnnotationWithPrefix(limitRateAnnotation)] = "10" ing.SetAnnotations(data) @@ -147,12 +148,12 @@ func TestRateLimiting(t *testing.T) { } data = map[string]string{} - data[parser.GetAnnotationWithPrefix("limit-connections")] = "5" - data[parser.GetAnnotationWithPrefix("limit-rps")] = "100" - data[parser.GetAnnotationWithPrefix("limit-rpm")] = "10" - data[parser.GetAnnotationWithPrefix("limit-rate-after")] = "100" - data[parser.GetAnnotationWithPrefix("limit-rate")] = "10" - data[parser.GetAnnotationWithPrefix("limit-burst-multiplier")] = "3" + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "5" + data[parser.GetAnnotationWithPrefix(limitRateRPSAnnotation)] = "100" + data[parser.GetAnnotationWithPrefix(limitRateRPMAnnotation)] = "10" + data[parser.GetAnnotationWithPrefix(limitRateAfterAnnotation)] = "100" + data[parser.GetAnnotationWithPrefix(limitRateAnnotation)] = "10" + data[parser.GetAnnotationWithPrefix(limitRateBurstMultiplierAnnotation)] = "3" ing.SetAnnotations(data) @@ -189,3 +190,61 @@ func TestRateLimiting(t *testing.T) { t.Errorf("expected 10 in limit by limitrate but %v was returned", rateLimit.LimitRate) } } + +func TestAnnotationCIDR(t *testing.T) { + ing := buildIngress() + + data := map[string]string{} + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "5" + data[parser.GetAnnotationWithPrefix(limitAllowlistAnnotation)] = "192.168.0.5, 192.168.50.32/24" + ing.SetAnnotations(data) + + i, err := NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + + rateLimit, ok := i.(*Config) + if !ok { + t.Errorf("expected a RateLimit type") + } + if len(rateLimit.Allowlist) != 2 { + t.Errorf("expected 2 cidrs in limit by ip but %v was returned", len(rateLimit.Allowlist)) + } + + data = map[string]string{} + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "5" + data[parser.GetAnnotationWithPrefix(limitWhitelistAnnotation)] = "192.168.0.5, 192.168.50.32/24, 10.10.10.1" + ing.SetAnnotations(data) + + i, err = NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + rateLimit, ok = i.(*Config) + if !ok { + t.Errorf("expected a RateLimit type") + } + if len(rateLimit.Allowlist) != 3 { + t.Errorf("expected 3 cidrs in limit by ip but %v was returned", len(rateLimit.Allowlist)) + } + + // Parent annotation surpasses any alias + data = map[string]string{} + data[parser.GetAnnotationWithPrefix(limitRateConnectionsAnnotation)] = "5" + data[parser.GetAnnotationWithPrefix(limitWhitelistAnnotation)] = "192.168.0.5, 192.168.50.32/24, 10.10.10.1" + data[parser.GetAnnotationWithPrefix(limitAllowlistAnnotation)] = "192.168.0.9" + ing.SetAnnotations(data) + + i, err = NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + rateLimit, ok = i.(*Config) + if !ok { + t.Errorf("expected a RateLimit type") + } + if len(rateLimit.Allowlist) != 1 { + t.Errorf("expected 1 cidrs in limit by ip but %v was returned", len(rateLimit.Allowlist)) + } +} diff --git a/internal/ingress/annotations/redirect/redirect.go b/internal/ingress/annotations/redirect/redirect.go index 11b08a4a2..89513c83c 100644 --- a/internal/ingress/annotations/redirect/redirect.go +++ b/internal/ingress/annotations/redirect/redirect.go @@ -37,13 +37,56 @@ type Config struct { FromToWWW bool `json:"fromToWWW"` } +const ( + fromToWWWRedirAnnotation = "from-to-www-redirect" + temporalRedirectAnnotation = "temporal-redirect" + permanentRedirectAnnotation = "permanent-redirect" + permanentRedirectAnnotationCode = "permanent-redirect-code" +) + +var redirectAnnotations = parser.Annotation{ + Group: "redirect", + Annotations: parser.AnnotationFields{ + fromToWWWRedirAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `In some scenarios is required to redirect from www.domain.com to domain.com or vice versa. To enable this feature use this annotation.`, + }, + temporalRedirectAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium, as it allows arbitrary URLs that needs to be validated + Documentation: `This annotation allows you to return a temporal redirect (Return Code 302) instead of sending data to the upstream. + For example setting this annotation to https://www.google.com would redirect everything to Google with a Return Code of 302 (Moved Temporarily).`, + }, + permanentRedirectAnnotation: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, // Medium, as it allows arbitrary URLs that needs to be validated + Documentation: `This annotation allows to return a permanent redirect (Return Code 301) instead of sending data to the upstream. + For example setting this annotation https://www.google.com would redirect everything to Google with a code 301`, + }, + permanentRedirectAnnotationCode: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options + Documentation: `This annotation allows you to modify the status code used for permanent redirects.`, + }, + }, +} + type redirect struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new redirect annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return redirect{r} + return redirect{ + r: r, + annotationConfig: redirectAnnotations, + } } // Parse parses the annotations contained in the ingress @@ -51,9 +94,12 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // If the Ingress contains both annotations the execution order is // temporal and then permanent func (r redirect) Parse(ing *networking.Ingress) (interface{}, error) { - r3w, _ := parser.GetBoolAnnotation("from-to-www-redirect", ing) + r3w, err := parser.GetBoolAnnotation(fromToWWWRedirAnnotation, ing, r.annotationConfig.Annotations) + if err != nil && !errors.IsMissingAnnotations(err) { + return nil, err + } - tr, err := parser.GetStringAnnotation("temporal-redirect", ing) + tr, err := parser.GetStringAnnotation(temporalRedirectAnnotation, ing, r.annotationConfig.Annotations) if err != nil && !errors.IsMissingAnnotations(err) { return nil, err } @@ -70,12 +116,12 @@ func (r redirect) Parse(ing *networking.Ingress) (interface{}, error) { }, nil } - pr, err := parser.GetStringAnnotation("permanent-redirect", ing) + pr, err := parser.GetStringAnnotation(permanentRedirectAnnotation, ing, r.annotationConfig.Annotations) if err != nil && !errors.IsMissingAnnotations(err) { return nil, err } - prc, err := parser.GetIntAnnotation("permanent-redirect-code", ing) + prc, err := parser.GetIntAnnotation(permanentRedirectAnnotationCode, ing, r.annotationConfig.Annotations) if err != nil && !errors.IsMissingAnnotations(err) { return nil, err } @@ -127,3 +173,12 @@ func isValidURL(s string) error { return nil } + +func (a redirect) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a redirect) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, redirectAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/redirect/redirect_test.go b/internal/ingress/annotations/redirect/redirect_test.go index b5a87a5d3..5a61f364d 100644 --- a/internal/ingress/annotations/redirect/redirect_test.go +++ b/internal/ingress/annotations/redirect/redirect_test.go @@ -43,7 +43,7 @@ func TestPermanentRedirectWithDefaultCode(t *testing.T) { ing := new(networking.Ingress) data := make(map[string]string, 1) - data[parser.GetAnnotationWithPrefix("permanent-redirect")] = defRedirectURL + data[parser.GetAnnotationWithPrefix(permanentRedirectAnnotation)] = defRedirectURL ing.SetAnnotations(data) i, err := rp.Parse(ing) @@ -81,8 +81,8 @@ func TestPermanentRedirectWithCustomCode(t *testing.T) { ing := new(networking.Ingress) data := make(map[string]string, 2) - data[parser.GetAnnotationWithPrefix("permanent-redirect")] = defRedirectURL - data[parser.GetAnnotationWithPrefix("permanent-redirect-code")] = strconv.Itoa(tc.input) + data[parser.GetAnnotationWithPrefix(permanentRedirectAnnotation)] = defRedirectURL + data[parser.GetAnnotationWithPrefix(permanentRedirectAnnotationCode)] = strconv.Itoa(tc.input) ing.SetAnnotations(data) i, err := rp.Parse(ing) @@ -112,8 +112,8 @@ func TestTemporalRedirect(t *testing.T) { ing := new(networking.Ingress) data := make(map[string]string, 1) - data[parser.GetAnnotationWithPrefix("from-to-www-redirect")] = "true" - data[parser.GetAnnotationWithPrefix("temporal-redirect")] = defRedirectURL + data[parser.GetAnnotationWithPrefix(fromToWWWRedirAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(temporalRedirectAnnotation)] = defRedirectURL ing.SetAnnotations(data) i, err := rp.Parse(ing) diff --git a/internal/ingress/annotations/rewrite/main.go b/internal/ingress/annotations/rewrite/main.go index f92d508dc..84dc93bf0 100644 --- a/internal/ingress/annotations/rewrite/main.go +++ b/internal/ingress/annotations/rewrite/main.go @@ -27,6 +27,59 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + rewriteTargetAnnotation = "rewrite-target" + sslRedirectAnnotation = "ssl-redirect" + preserveTrailingSlashAnnotation = "preserve-trailing-slash" + forceSSLRedirectAnnotation = "force-ssl-redirect" + useRegexAnnotation = "use-regex" + appRootAnnotation = "app-root" +) + +var rewriteAnnotations = parser.Annotation{ + Group: "rewrite", + Annotations: parser.AnnotationFields{ + rewriteTargetAnnotation: { + Validator: parser.ValidateRegex(*parser.RegexPathWithCapture, false), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows to specify the target URI where the traffic must be redirected. It can contain regular characters and captured + groups specified as '$1', '$2', etc.`, + }, + sslRedirectAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if the location section is only accessible via SSL`, + }, + preserveTrailingSlashAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines if the trailing slash should be preserved in the URI with 'ssl-redirect'`, + }, + forceSSLRedirectAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation forces the redirection to HTTPS even if the Ingress is not TLS Enabled`, + }, + useRegexAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines if the paths defined on an Ingress use regular expressions. To use regex on path + the pathType should also be defined as 'ImplementationSpecific'.`, + }, + appRootAnnotation: { + Validator: parser.ValidateRegex(*parser.RegexPathWithCapture, false), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the Application Root that the Controller must redirect if it's in / context`, + }, + }, +} + // Config describes the per location redirect config type Config struct { // Target URI where the traffic must be redirected @@ -71,12 +124,16 @@ func (r1 *Config) Equal(r2 *Config) bool { } type rewrite struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new rewrite annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return rewrite{r} + return rewrite{ + r: r, + annotationConfig: rewriteAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -85,24 +142,45 @@ func (a rewrite) Parse(ing *networking.Ingress) (interface{}, error) { var err error config := &Config{} - config.Target, _ = parser.GetStringAnnotation("rewrite-target", ing) - config.SSLRedirect, err = parser.GetBoolAnnotation("ssl-redirect", ing) + config.Target, err = parser.GetStringAnnotation(rewriteTargetAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%sis invalid, defaulting to empty", rewriteTargetAnnotation) + } + config.Target = "" + } + config.SSLRedirect, err = parser.GetBoolAnnotation(sslRedirectAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%sis invalid, defaulting to '%s'", sslRedirectAnnotation, a.r.GetDefaultBackend().SSLRedirect) + } config.SSLRedirect = a.r.GetDefaultBackend().SSLRedirect } - config.PreserveTrailingSlash, err = parser.GetBoolAnnotation("preserve-trailing-slash", ing) + config.PreserveTrailingSlash, err = parser.GetBoolAnnotation(preserveTrailingSlashAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%sis invalid, defaulting to '%s'", preserveTrailingSlashAnnotation, a.r.GetDefaultBackend().PreserveTrailingSlash) + } config.PreserveTrailingSlash = a.r.GetDefaultBackend().PreserveTrailingSlash } - config.ForceSSLRedirect, err = parser.GetBoolAnnotation("force-ssl-redirect", ing) + config.ForceSSLRedirect, err = parser.GetBoolAnnotation(forceSSLRedirectAnnotation, ing, a.annotationConfig.Annotations) if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%sis invalid, defaulting to '%s'", forceSSLRedirectAnnotation, a.r.GetDefaultBackend().ForceSSLRedirect) + } config.ForceSSLRedirect = a.r.GetDefaultBackend().ForceSSLRedirect } - config.UseRegex, _ = parser.GetBoolAnnotation("use-regex", ing) + config.UseRegex, err = parser.GetBoolAnnotation(useRegexAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + if errors.IsValidationError(err) { + klog.Warningf("%sis invalid, defaulting to 'false'", useRegexAnnotation) + } + config.UseRegex = false + } - config.AppRoot, err = parser.GetStringAnnotation("app-root", ing) + config.AppRoot, err = parser.GetStringAnnotation(appRootAnnotation, ing, a.annotationConfig.Annotations) if err != nil { if !errors.IsMissingAnnotations(err) && !errors.IsInvalidContent(err) { klog.Warningf("Annotation app-root contains an invalid value: %v", err) @@ -126,3 +204,12 @@ func (a rewrite) Parse(ing *networking.Ingress) (interface{}, error) { return config, nil } + +func (a rewrite) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a rewrite) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, rewriteAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/rewrite/main_test.go b/internal/ingress/annotations/rewrite/main_test.go index c2cb42c78..6b97d2e01 100644 --- a/internal/ingress/annotations/rewrite/main_test.go +++ b/internal/ingress/annotations/rewrite/main_test.go @@ -129,6 +129,30 @@ func TestSSLRedirect(t *testing.T) { t.Errorf("Expected true but returned false") } + data[parser.GetAnnotationWithPrefix("rewrite-target")] = "/xpto/$1/abc/$2" + ing.SetAnnotations(data) + + i, _ = NewParser(mockBackend{redirect: true}).Parse(ing) + redirect, ok = i.(*Config) + if !ok { + t.Errorf("expected a Redirect type") + } + if redirect.Target != "/xpto/$1/abc/$2" { + t.Errorf("Expected /xpto/$1/abc/$2 but returned %s", redirect.Target) + } + + data[parser.GetAnnotationWithPrefix("rewrite-target")] = "/xpto/xas{445}" + ing.SetAnnotations(data) + + i, _ = NewParser(mockBackend{redirect: true}).Parse(ing) + redirect, ok = i.(*Config) + if !ok { + t.Errorf("expected a Redirect type") + } + if redirect.Target != "" { + t.Errorf("Expected empty rewrite target but returned %s", redirect.Target) + } + data[parser.GetAnnotationWithPrefix("ssl-redirect")] = "false" ing.SetAnnotations(data) diff --git a/internal/ingress/annotations/satisfy/main.go b/internal/ingress/annotations/satisfy/main.go index 0d4fd4ff6..45187fe5c 100644 --- a/internal/ingress/annotations/satisfy/main.go +++ b/internal/ingress/annotations/satisfy/main.go @@ -23,18 +23,40 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + satisfyAnnotation = "satisfy" +) + +var satisfyAnnotations = parser.Annotation{ + Group: "authentication", + Annotations: parser.AnnotationFields{ + satisfyAnnotation: { + Validator: parser.ValidateOptions([]string{"any", "all"}, true, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `By default, a request would need to satisfy all authentication requirements in order to be allowed. + By using this annotation, requests that satisfy either any or all authentication requirements are allowed, based on the configuration value. + Valid options are "all" and "any"`, + }, + }, +} + type satisfy struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new SATISFY annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return satisfy{r} + return satisfy{ + r: r, + annotationConfig: satisfyAnnotations, + } } // Parse parses annotation contained in the ingress func (s satisfy) Parse(ing *networking.Ingress) (interface{}, error) { - satisfy, err := parser.GetStringAnnotation("satisfy", ing) + satisfy, err := parser.GetStringAnnotation(satisfyAnnotation, ing, s.annotationConfig.Annotations) if err != nil || (satisfy != "any" && satisfy != "all") { satisfy = "" @@ -42,3 +64,12 @@ func (s satisfy) Parse(ing *networking.Ingress) (interface{}, error) { return satisfy, nil } + +func (s satisfy) GetDocumentation() parser.AnnotationFields { + return s.annotationConfig.Annotations +} + +func (a satisfy) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, satisfyAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/satisfy/main_test.go b/internal/ingress/annotations/satisfy/main_test.go index b45205d9f..c8d5782f9 100644 --- a/internal/ingress/annotations/satisfy/main_test.go +++ b/internal/ingress/annotations/satisfy/main_test.go @@ -83,7 +83,7 @@ func TestSatisfyParser(t *testing.T) { annotations := map[string]string{} for input, expected := range data { - annotations[parser.GetAnnotationWithPrefix("satisfy")] = input + annotations[parser.GetAnnotationWithPrefix(satisfyAnnotation)] = input ing.SetAnnotations(annotations) satisfyt, err := NewParser(&resolver.Mock{}).Parse(ing) diff --git a/internal/ingress/annotations/serversnippet/main.go b/internal/ingress/annotations/serversnippet/main.go index 70f0af8e5..aa15608d0 100644 --- a/internal/ingress/annotations/serversnippet/main.go +++ b/internal/ingress/annotations/serversnippet/main.go @@ -23,18 +23,47 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + serverSnippetAnnotation = "server-snippet" +) + +var serverSnippetAnnotations = parser.Annotation{ + Group: "snippets", + Annotations: parser.AnnotationFields{ + serverSnippetAnnotation: { + Validator: parser.ValidateNull, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskCritical, // Critical, this annotation is not validated at all and allows arbitrary configutations + Documentation: `This annotation allows setting a custom NGINX configuration on a server block. This annotation does not contain any validation and it's usage is not recommended!`, + }, + }, +} + type serverSnippet struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new server snippet annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return serverSnippet{r} + return serverSnippet{ + r: r, + annotationConfig: serverSnippetAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a serverSnippet) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("server-snippet", ing) + return parser.GetStringAnnotation(serverSnippetAnnotation, ing, a.annotationConfig.Annotations) +} + +func (a serverSnippet) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a serverSnippet) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, serverSnippetAnnotations.Annotations) } diff --git a/internal/ingress/annotations/serversnippet/main_test.go b/internal/ingress/annotations/serversnippet/main_test.go index c9e0979ad..601e11a42 100644 --- a/internal/ingress/annotations/serversnippet/main_test.go +++ b/internal/ingress/annotations/serversnippet/main_test.go @@ -27,7 +27,7 @@ import ( ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("server-snippet") + annotation := parser.GetAnnotationWithPrefix(serverSnippetAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { diff --git a/internal/ingress/annotations/serviceupstream/main.go b/internal/ingress/annotations/serviceupstream/main.go index 4a4879682..e662f73c3 100644 --- a/internal/ingress/annotations/serviceupstream/main.go +++ b/internal/ingress/annotations/serviceupstream/main.go @@ -24,19 +24,39 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + serviceUpstreamAnnotation = "service-upstream" +) + +var serviceUpstreamAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + serviceUpstreamAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, // Critical, this annotation is not validated at all and allows arbitrary configutations + Documentation: `This annotation makes NGINX use Service's Cluster IP and Port instead of Endpoints as the backend endpoints`, + }, + }, +} + type serviceUpstream struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new serviceUpstream annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return serviceUpstream{r} + return serviceUpstream{ + r: r, + annotationConfig: serviceUpstreamAnnotations, + } } func (s serviceUpstream) Parse(ing *networking.Ingress) (interface{}, error) { defBackend := s.r.GetDefaultBackend() - val, err := parser.GetBoolAnnotation("service-upstream", ing) + val, err := parser.GetBoolAnnotation(serviceUpstreamAnnotation, ing, s.annotationConfig.Annotations) // A missing annotation is not a problem, just use the default if err == errors.ErrMissingAnnotations { return defBackend.ServiceUpstream, nil @@ -44,3 +64,12 @@ func (s serviceUpstream) Parse(ing *networking.Ingress) (interface{}, error) { return val, nil } + +func (s serviceUpstream) GetDocumentation() parser.AnnotationFields { + return s.annotationConfig.Annotations +} + +func (a serviceUpstream) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, serviceUpstreamAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/serviceupstream/main_test.go b/internal/ingress/annotations/serviceupstream/main_test.go index b773e9723..2751208ec 100644 --- a/internal/ingress/annotations/serviceupstream/main_test.go +++ b/internal/ingress/annotations/serviceupstream/main_test.go @@ -74,7 +74,7 @@ func TestIngressAnnotationServiceUpstreamEnabled(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("service-upstream")] = "true" + data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "true" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -93,7 +93,7 @@ func TestIngressAnnotationServiceUpstreamSetFalse(t *testing.T) { // Test with explicitly set to false data := map[string]string{} - data[parser.GetAnnotationWithPrefix("service-upstream")] = "false" + data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "false" ing.SetAnnotations(data) val, _ := NewParser(&resolver.Mock{}).Parse(ing) @@ -155,7 +155,7 @@ func TestParseAnnotationsOverridesDefaultConfig(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix("service-upstream")] = "false" + data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "false" ing.SetAnnotations(data) val, _ := NewParser(mockBackend{}).Parse(ing) diff --git a/internal/ingress/annotations/sessionaffinity/main.go b/internal/ingress/annotations/sessionaffinity/main.go index 98a0d64f8..0a4a59dbc 100644 --- a/internal/ingress/annotations/sessionaffinity/main.go +++ b/internal/ingress/annotations/sessionaffinity/main.go @@ -65,6 +65,90 @@ const ( annotationAffinityCookieChangeOnFailure = "session-cookie-change-on-failure" ) +var sessionAffinityAnnotations = parser.Annotation{ + Group: "affinity", + Annotations: parser.AnnotationFields{ + annotationAffinityType: { + Validator: parser.ValidateOptions([]string{"cookie"}, true, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation enables and sets the affinity type in all Upstreams of an Ingress. This way, a request will always be directed to the same upstream server. The only affinity type available for NGINX is cookie`, + }, + annotationAffinityMode: { + Validator: parser.ValidateOptions([]string{"balanced", "persistent"}, true, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the stickiness of a session. + Setting this to balanced (default) will redistribute some sessions if a deployment gets scaled up, therefore rebalancing the load on the servers. + Setting this to persistent will not rebalance sessions to new servers, therefore providing maximum stickiness.`, + }, + annotationAffinityCanaryBehavior: { + Validator: parser.ValidateOptions([]string{"sticky", "legacy"}, true, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation defines the behavior of canaries when session affinity is enabled. + Setting this to sticky (default) will ensure that users that were served by canaries, will continue to be served by canaries. + Setting this to legacy will restore original canary behavior, when session affinity was ignored.`, + }, + annotationAffinityCookieName: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation allows to specify the name of the cookie that will be used to route the requests`, + }, + annotationAffinityCookieSecure: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation set the cookie as secure regardless the protocol of the incoming request`, + }, + annotationAffinityCookieExpires: { + Validator: parser.ValidateRegex(*affinityCookieExpiresRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation is a legacy version of "session-cookie-max-age" for compatibility with older browsers, generates an "Expires" cookie directive by adding the seconds to the current date`, + }, + annotationAffinityCookieMaxAge: { + Validator: parser.ValidateRegex(*affinityCookieExpiresRegex, false), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation sets the time until the cookie expires`, + }, + annotationAffinityCookiePath: { + Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the Path that will be set on the cookie (required if your Ingress paths use regular expressions)`, + }, + annotationAffinityCookieDomain: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskMedium, + Documentation: `This annotation defines the Domain attribute of the sticky cookie.`, + }, + annotationAffinityCookieSameSite: { + Validator: parser.ValidateOptions([]string{"None", "Lax", "Strict"}, false, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation is used to apply a SameSite attribute to the sticky cookie. + Browser accepted values are None, Lax, and Strict`, + }, + annotationAffinityCookieConditionalSameSiteNone: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation is used to omit SameSite=None from browsers with SameSite attribute incompatibilities`, + }, + annotationAffinityCookieChangeOnFailure: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation, when set to false will send request to upstream pointed by sticky cookie even if previous attempt failed. + When set to true and previous attempt failed, sticky cookie will be changed to point to another upstream.`, + }, + }, +} + var ( affinityCookieExpiresRegex = regexp.MustCompile(`(^0|-?[1-9]\d*$)`) ) @@ -109,50 +193,50 @@ func (a affinity) cookieAffinityParse(ing *networking.Ingress) *Cookie { cookie := &Cookie{} - cookie.Name, err = parser.GetStringAnnotation(annotationAffinityCookieName, ing) + cookie.Name, err = parser.GetStringAnnotation(annotationAffinityCookieName, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieName, "default", defaultAffinityCookieName) cookie.Name = defaultAffinityCookieName } - cookie.Expires, err = parser.GetStringAnnotation(annotationAffinityCookieExpires, ing) + cookie.Expires, err = parser.GetStringAnnotation(annotationAffinityCookieExpires, ing, a.annotationConfig.Annotations) if err != nil || !affinityCookieExpiresRegex.MatchString(cookie.Expires) { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieExpires) cookie.Expires = "" } - cookie.MaxAge, err = parser.GetStringAnnotation(annotationAffinityCookieMaxAge, ing) + cookie.MaxAge, err = parser.GetStringAnnotation(annotationAffinityCookieMaxAge, ing, a.annotationConfig.Annotations) if err != nil || !affinityCookieExpiresRegex.MatchString(cookie.MaxAge) { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieMaxAge) cookie.MaxAge = "" } - cookie.Path, err = parser.GetStringAnnotation(annotationAffinityCookiePath, ing) + cookie.Path, err = parser.GetStringAnnotation(annotationAffinityCookiePath, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookiePath) } - cookie.Domain, err = parser.GetStringAnnotation(annotationAffinityCookieDomain, ing) + cookie.Domain, err = parser.GetStringAnnotation(annotationAffinityCookieDomain, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieDomain) } - cookie.SameSite, err = parser.GetStringAnnotation(annotationAffinityCookieSameSite, ing) + cookie.SameSite, err = parser.GetStringAnnotation(annotationAffinityCookieSameSite, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieSameSite) } - cookie.Secure, err = parser.GetBoolAnnotation(annotationAffinityCookieSecure, ing) + cookie.Secure, err = parser.GetBoolAnnotation(annotationAffinityCookieSecure, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieSecure) } - cookie.ConditionalSameSiteNone, err = parser.GetBoolAnnotation(annotationAffinityCookieConditionalSameSiteNone, ing) + cookie.ConditionalSameSiteNone, err = parser.GetBoolAnnotation(annotationAffinityCookieConditionalSameSiteNone, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieConditionalSameSiteNone) } - cookie.ChangeOnFailure, err = parser.GetBoolAnnotation(annotationAffinityCookieChangeOnFailure, ing) + cookie.ChangeOnFailure, err = parser.GetBoolAnnotation(annotationAffinityCookieChangeOnFailure, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("Invalid or no annotation value found. Ignoring", "ingress", klog.KObj(ing), "annotation", annotationAffinityCookieChangeOnFailure) } @@ -162,11 +246,15 @@ func (a affinity) cookieAffinityParse(ing *networking.Ingress) *Cookie { // NewParser creates a new Affinity annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return affinity{r} + return affinity{ + r: r, + annotationConfig: sessionAffinityAnnotations, + } } type affinity struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // ParseAnnotations parses the annotations contained in the ingress @@ -174,18 +262,18 @@ type affinity struct { func (a affinity) Parse(ing *networking.Ingress) (interface{}, error) { cookie := &Cookie{} // Check the type of affinity that will be used - at, err := parser.GetStringAnnotation(annotationAffinityType, ing) + at, err := parser.GetStringAnnotation(annotationAffinityType, ing, a.annotationConfig.Annotations) if err != nil { at = "" } // Check the affinity mode that will be used - am, err := parser.GetStringAnnotation(annotationAffinityMode, ing) + am, err := parser.GetStringAnnotation(annotationAffinityMode, ing, a.annotationConfig.Annotations) if err != nil { am = "" } - cb, err := parser.GetStringAnnotation(annotationAffinityCanaryBehavior, ing) + cb, err := parser.GetStringAnnotation(annotationAffinityCanaryBehavior, ing, a.annotationConfig.Annotations) if err != nil { cb = "" } @@ -205,3 +293,12 @@ func (a affinity) Parse(ing *networking.Ingress) (interface{}, error) { Cookie: *cookie, }, nil } + +func (a affinity) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a affinity) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, sessionAffinityAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/snippet/main.go b/internal/ingress/annotations/snippet/main.go index 93ec70cf9..2406093c5 100644 --- a/internal/ingress/annotations/snippet/main.go +++ b/internal/ingress/annotations/snippet/main.go @@ -23,18 +23,47 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + configurationSnippetAnnotation = "configuration-snippet" +) + +var configurationSnippetAnnotations = parser.Annotation{ + Group: "snippets", + Annotations: parser.AnnotationFields{ + configurationSnippetAnnotation: { + Validator: parser.ValidateNull, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskCritical, // Critical, this annotation is not validated at all and allows arbitrary configutations + Documentation: `This annotation allows setting a custom NGINX configuration on a location block. This annotation does not contain any validation and it's usage is not recommended!`, + }, + }, +} + type snippet struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new CORS annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return snippet{r} + return snippet{ + r: r, + annotationConfig: configurationSnippetAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a snippet) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("configuration-snippet", ing) + return parser.GetStringAnnotation(configurationSnippetAnnotation, ing, a.annotationConfig.Annotations) +} + +func (a snippet) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a snippet) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, configurationSnippetAnnotations.Annotations) } diff --git a/internal/ingress/annotations/snippet/main_test.go b/internal/ingress/annotations/snippet/main_test.go index 0defc3c1f..921afeea8 100644 --- a/internal/ingress/annotations/snippet/main_test.go +++ b/internal/ingress/annotations/snippet/main_test.go @@ -27,7 +27,7 @@ import ( ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("configuration-snippet") + annotation := parser.GetAnnotationWithPrefix(configurationSnippetAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { diff --git a/internal/ingress/annotations/sslcipher/main.go b/internal/ingress/annotations/sslcipher/main.go index e4e5baad2..c30f12424 100644 --- a/internal/ingress/annotations/sslcipher/main.go +++ b/internal/ingress/annotations/sslcipher/main.go @@ -17,14 +17,47 @@ limitations under the License. package sslcipher import ( + "regexp" + networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + sslPreferServerCipherAnnotation = "ssl-prefer-server-ciphers" + sslCipherAnnotation = "ssl-ciphers" +) + +var ( + // Should cover something like "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP" + regexValidSSLCipher = regexp.MustCompile(`^[A-Za-z0-9!:+\-]*$`) +) + +var sslCipherAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + sslPreferServerCipherAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `The following annotation will set the ssl_prefer_server_ciphers directive at the server level. + This configuration specifies that server ciphers should be preferred over client ciphers when using the SSLv3 and TLS protocols.`, + }, + sslCipherAnnotation: { + Validator: parser.ValidateRegex(*regexValidSSLCipher, true), + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, + Documentation: `Using this annotation will set the ssl_ciphers directive at the server level. This configuration is active for all the paths in the host.`, + }, + }, +} + type sslCipher struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the ssl-ciphers & ssl-prefer-server-ciphers configuration @@ -35,7 +68,10 @@ type Config struct { // NewParser creates a new sslCipher annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return sslCipher{r} + return sslCipher{ + r: r, + annotationConfig: sslCipherAnnotations, + } } // Parse parses the annotations contained in the ingress rule @@ -45,7 +81,7 @@ func (sc sslCipher) Parse(ing *networking.Ingress) (interface{}, error) { var err error var sslPreferServerCiphers bool - sslPreferServerCiphers, err = parser.GetBoolAnnotation("ssl-prefer-server-ciphers", ing) + sslPreferServerCiphers, err = parser.GetBoolAnnotation(sslPreferServerCipherAnnotation, ing, sc.annotationConfig.Annotations) if err != nil { config.SSLPreferServerCiphers = "" } else { @@ -56,7 +92,19 @@ func (sc sslCipher) Parse(ing *networking.Ingress) (interface{}, error) { } } - config.SSLCiphers, _ = parser.GetStringAnnotation("ssl-ciphers", ing) + config.SSLCiphers, err = parser.GetStringAnnotation(sslCipherAnnotation, ing, sc.annotationConfig.Annotations) + if err != nil && !errors.IsInvalidContent(err) && !errors.IsMissingAnnotations(err) { + return config, err + } return config, nil } + +func (sc sslCipher) GetDocumentation() parser.AnnotationFields { + return sc.annotationConfig.Annotations +} + +func (a sslCipher) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, sslCipherAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/sslcipher/main_test.go b/internal/ingress/annotations/sslcipher/main_test.go index 6eb9ec0c2..ac6808e06 100644 --- a/internal/ingress/annotations/sslcipher/main_test.go +++ b/internal/ingress/annotations/sslcipher/main_test.go @@ -33,22 +33,24 @@ func TestParse(t *testing.T) { t.Fatalf("expected a parser.IngressAnnotation but returned nil") } - annotationSSLCiphers := parser.GetAnnotationWithPrefix("ssl-ciphers") - annotationSSLPreferServerCiphers := parser.GetAnnotationWithPrefix("ssl-prefer-server-ciphers") + annotationSSLCiphers := parser.GetAnnotationWithPrefix(sslCipherAnnotation) + annotationSSLPreferServerCiphers := parser.GetAnnotationWithPrefix(sslPreferServerCipherAnnotation) testCases := []struct { annotations map[string]string expected Config + expectErr bool }{ - {map[string]string{annotationSSLCiphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP"}, Config{"ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", ""}}, + {map[string]string{annotationSSLCiphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP"}, Config{"ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", ""}, false}, {map[string]string{annotationSSLCiphers: "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"}, - Config{"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", ""}}, - {map[string]string{annotationSSLCiphers: ""}, Config{"", ""}}, - {map[string]string{annotationSSLPreferServerCiphers: "true"}, Config{"", "on"}}, - {map[string]string{annotationSSLPreferServerCiphers: "false"}, Config{"", "off"}}, - {map[string]string{annotationSSLCiphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", annotationSSLPreferServerCiphers: "true"}, Config{"ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", "on"}}, - {map[string]string{}, Config{"", ""}}, - {nil, Config{"", ""}}, + Config{"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", ""}, false}, + {map[string]string{annotationSSLCiphers: ""}, Config{"", ""}, false}, + {map[string]string{annotationSSLPreferServerCiphers: "true"}, Config{"", "on"}, false}, + {map[string]string{annotationSSLPreferServerCiphers: "false"}, Config{"", "off"}, false}, + {map[string]string{annotationSSLCiphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", annotationSSLPreferServerCiphers: "true"}, Config{"ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", "on"}, false}, + {map[string]string{annotationSSLCiphers: "ALL:SOMETHING:;locationXPTO"}, Config{"", ""}, true}, + {map[string]string{}, Config{"", ""}, false}, + {nil, Config{"", ""}, false}, } ing := &networking.Ingress{ @@ -61,7 +63,10 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) + result, err := ap.Parse(ing) + if (err != nil) != testCase.expectErr { + t.Fatalf("expected error: %t got error: %t err value: %s. %+v", testCase.expectErr, err != nil, err, testCase.annotations) + } if !reflect.DeepEqual(result, &testCase.expected) { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) } diff --git a/internal/ingress/annotations/sslpassthrough/main.go b/internal/ingress/annotations/sslpassthrough/main.go index d1def7172..1557d4243 100644 --- a/internal/ingress/annotations/sslpassthrough/main.go +++ b/internal/ingress/annotations/sslpassthrough/main.go @@ -24,13 +24,32 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + sslPassthroughAnnotation = "ssl-passthrough" +) + +var sslPassthroughAnnotations = parser.Annotation{ + Group: "", // TBD + Annotations: parser.AnnotationFields{ + sslPassthroughAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskLow, // Low, as it allows regexes but on a very limited set + Documentation: `This annotation instructs the controller to send TLS connections directly to the backend instead of letting NGINX decrypt the communication.`, + }, + }, +} + type sslpt struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new SSL passthrough annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return sslpt{r} + return sslpt{r: r, + annotationConfig: sslPassthroughAnnotations, + } } // ParseAnnotations parses the annotations contained in the ingress @@ -40,5 +59,14 @@ func (a sslpt) Parse(ing *networking.Ingress) (interface{}, error) { return false, ing_errors.ErrMissingAnnotations } - return parser.GetBoolAnnotation("ssl-passthrough", ing) + return parser.GetBoolAnnotation(sslPassthroughAnnotation, ing, a.annotationConfig.Annotations) +} + +func (a sslpt) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a sslpt) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, sslPassthroughAnnotations.Annotations) } diff --git a/internal/ingress/annotations/sslpassthrough/main_test.go b/internal/ingress/annotations/sslpassthrough/main_test.go index 5cf2f979a..b712fda19 100644 --- a/internal/ingress/annotations/sslpassthrough/main_test.go +++ b/internal/ingress/annotations/sslpassthrough/main_test.go @@ -54,7 +54,7 @@ func TestParseAnnotations(t *testing.T) { } data := map[string]string{} - data[parser.GetAnnotationWithPrefix("ssl-passthrough")] = "true" + data[parser.GetAnnotationWithPrefix(sslPassthroughAnnotation)] = "true" ing.SetAnnotations(data) // test ingress using the annotation without a TLS section _, err = NewParser(&resolver.Mock{}).Parse(ing) diff --git a/internal/ingress/annotations/streamsnippet/main.go b/internal/ingress/annotations/streamsnippet/main.go index fb22f754c..71ff3b140 100644 --- a/internal/ingress/annotations/streamsnippet/main.go +++ b/internal/ingress/annotations/streamsnippet/main.go @@ -23,18 +23,47 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + streamSnippetAnnotation = "stream-snippet" +) + +var streamSnippetAnnotations = parser.Annotation{ + Group: "snippets", + Annotations: parser.AnnotationFields{ + streamSnippetAnnotation: { + Validator: parser.ValidateNull, + Scope: parser.AnnotationScopeIngress, + Risk: parser.AnnotationRiskCritical, // Critical, this annotation is not validated at all and allows arbitrary configutations + Documentation: `This annotation allows setting a custom NGINX configuration on a stream block. This annotation does not contain any validation and it's usage is not recommended!`, + }, + }, +} + type streamSnippet struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new server snippet annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return streamSnippet{r} + return streamSnippet{ + r: r, + annotationConfig: streamSnippetAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a streamSnippet) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("stream-snippet", ing) + return parser.GetStringAnnotation("stream-snippet", ing, a.annotationConfig.Annotations) +} + +func (a streamSnippet) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a streamSnippet) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, streamSnippetAnnotations.Annotations) } diff --git a/internal/ingress/annotations/streamsnippet/main_test.go b/internal/ingress/annotations/streamsnippet/main_test.go index 0b8e3e3aa..997b7be70 100644 --- a/internal/ingress/annotations/streamsnippet/main_test.go +++ b/internal/ingress/annotations/streamsnippet/main_test.go @@ -27,7 +27,7 @@ import ( ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("stream-snippet") + annotation := parser.GetAnnotationWithPrefix(streamSnippetAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { diff --git a/internal/ingress/annotations/upstreamhashby/main.go b/internal/ingress/annotations/upstreamhashby/main.go index e6bbca6c3..bc07f70fb 100644 --- a/internal/ingress/annotations/upstreamhashby/main.go +++ b/internal/ingress/annotations/upstreamhashby/main.go @@ -17,14 +17,54 @@ limitations under the License. package upstreamhashby import ( + "regexp" + networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" + "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + upstreamHashByAnnotation = "upstream-hash-by" + upstreamHashBySubsetAnnotation = "upstream-hash-by-subset" + upstreamHashBySubsetSize = "upstream-hash-by-subset-size" +) + +var ( + specialChars = regexp.QuoteMeta("_${}") + hashByRegex = regexp.MustCompilePOSIX(`^[A-Za-z0-9\-` + specialChars + `]*$`) +) + +var upstreamHashByAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + upstreamHashByAnnotation: { + Validator: parser.ValidateRegex(*hashByRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskHigh, // High, this annotation allows accessing NGINX variables + Documentation: `This annotation defines the nginx variable, text value or any combination thereof to use for consistent hashing. + For example: nginx.ingress.kubernetes.io/upstream-hash-by: "$request_uri" or nginx.ingress.kubernetes.io/upstream-hash-by: "$request_uri$host" or nginx.ingress.kubernetes.io/upstream-hash-by: "${request_uri}-text-value" to consistently hash upstream requests by the current request URI.`, + }, + upstreamHashBySubsetAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation maps requests to subset of nodes instead of a single one.`, + }, + upstreamHashBySubsetSize: { + Validator: parser.ValidateInt, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation determines the size of each subset (default 3)`, + }, + }, +} + type upstreamhashby struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // Config contains the Consistent hash configuration to be used in the Ingress @@ -36,14 +76,26 @@ type Config struct { // NewParser creates a new UpstreamHashBy annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return upstreamhashby{r} + return upstreamhashby{ + r: r, + annotationConfig: upstreamHashByAnnotations, + } } // Parse parses the annotations contained in the ingress rule func (a upstreamhashby) Parse(ing *networking.Ingress) (interface{}, error) { - upstreamHashBy, _ := parser.GetStringAnnotation("upstream-hash-by", ing) - upstreamHashBySubset, _ := parser.GetBoolAnnotation("upstream-hash-by-subset", ing) - upstreamHashbySubsetSize, _ := parser.GetIntAnnotation("upstream-hash-by-subset-size", ing) + upstreamHashBy, err := parser.GetStringAnnotation(upstreamHashByAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && !errors.IsMissingAnnotations(err) { + return nil, err + } + upstreamHashBySubset, err := parser.GetBoolAnnotation(upstreamHashBySubsetAnnotation, ing, a.annotationConfig.Annotations) + if err != nil && !errors.IsMissingAnnotations(err) { + return nil, err + } + upstreamHashbySubsetSize, err := parser.GetIntAnnotation(upstreamHashBySubsetSize, ing, a.annotationConfig.Annotations) + if err != nil && !errors.IsMissingAnnotations(err) { + return nil, err + } if upstreamHashbySubsetSize == 0 { upstreamHashbySubsetSize = 3 @@ -51,3 +103,12 @@ func (a upstreamhashby) Parse(ing *networking.Ingress) (interface{}, error) { return &Config{upstreamHashBy, upstreamHashBySubset, upstreamHashbySubsetSize}, nil } + +func (a upstreamhashby) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a upstreamhashby) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, upstreamHashByAnnotations.Annotations) +} diff --git a/internal/ingress/annotations/upstreamhashby/main_test.go b/internal/ingress/annotations/upstreamhashby/main_test.go index d2c2644ca..bdbd9c350 100644 --- a/internal/ingress/annotations/upstreamhashby/main_test.go +++ b/internal/ingress/annotations/upstreamhashby/main_test.go @@ -27,7 +27,7 @@ import ( ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("upstream-hash-by") + annotation := parser.GetAnnotationWithPrefix(upstreamHashByAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { @@ -37,12 +37,15 @@ func TestParse(t *testing.T) { testCases := []struct { annotations map[string]string expected string + expectErr bool }{ - {map[string]string{annotation: "$request_uri"}, "$request_uri"}, - {map[string]string{annotation: "$request_uri$scheme"}, "$request_uri$scheme"}, - {map[string]string{annotation: "false"}, "false"}, - {map[string]string{}, ""}, - {nil, ""}, + {map[string]string{annotation: "$request_URI"}, "$request_URI", false}, + {map[string]string{annotation: "$request_uri$scheme"}, "$request_uri$scheme", false}, + {map[string]string{annotation: "xpto;[]"}, "", true}, + {map[string]string{annotation: "lalal${scheme_test}"}, "lalal${scheme_test}", false}, + {map[string]string{annotation: "false"}, "false", false}, + {map[string]string{}, "", false}, + {nil, "", false}, } ing := &networking.Ingress{ @@ -55,14 +58,19 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) - uc, ok := result.(*Config) - if !ok { - t.Fatalf("expected a Config type") + result, err := ap.Parse(ing) + if (err != nil) != testCase.expectErr { + t.Fatalf("expected error: %t got error: %t err value: %s. %+v", testCase.expectErr, err != nil, err, testCase.annotations) } + if !testCase.expectErr { + uc, ok := result.(*Config) + if !ok { + t.Fatalf("expected a Config type") + } - if uc.UpstreamHashBy != testCase.expected { - t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) + if uc.UpstreamHashBy != testCase.expected { + t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) + } } } } diff --git a/internal/ingress/annotations/upstreamvhost/main.go b/internal/ingress/annotations/upstreamvhost/main.go index 2eed5607e..052ca2344 100644 --- a/internal/ingress/annotations/upstreamvhost/main.go +++ b/internal/ingress/annotations/upstreamvhost/main.go @@ -23,18 +23,48 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + upstreamVhostAnnotation = "upstream-vhost" +) + +var upstreamVhostAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + upstreamVhostAnnotation: { + Validator: parser.ValidateServerName, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows regexes but on a very limited set + Documentation: `This configuration setting allows you to control the value for host in the following statement: proxy_set_header Host $host, which forms part of the location block. + This is useful if you need to call the upstream server by something other than $host`, + }, + }, +} + type upstreamVhost struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new upstream VHost annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return upstreamVhost{r} + return upstreamVhost{ + r: r, + annotationConfig: upstreamVhostAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to indicate if the location/s contains a fragment of // configuration to be included inside the paths of the rules func (a upstreamVhost) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("upstream-vhost", ing) + return parser.GetStringAnnotation(upstreamVhostAnnotation, ing, a.annotationConfig.Annotations) +} + +func (a upstreamVhost) GetDocumentation() parser.AnnotationFields { + return a.annotationConfig.Annotations +} + +func (a upstreamVhost) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, upstreamVhostAnnotations.Annotations) } diff --git a/internal/ingress/annotations/upstreamvhost/main_test.go b/internal/ingress/annotations/upstreamvhost/main_test.go index 130d745ee..87324b181 100644 --- a/internal/ingress/annotations/upstreamvhost/main_test.go +++ b/internal/ingress/annotations/upstreamvhost/main_test.go @@ -36,7 +36,7 @@ func TestParse(t *testing.T) { } data := map[string]string{} - data[parser.GetAnnotationWithPrefix("upstream-vhost")] = "ok.com" + data[parser.GetAnnotationWithPrefix(upstreamVhostAnnotation)] = "ok.com" ing.SetAnnotations(data) diff --git a/internal/ingress/annotations/xforwardedprefix/main.go b/internal/ingress/annotations/xforwardedprefix/main.go index 60eed8773..fc4d5798d 100644 --- a/internal/ingress/annotations/xforwardedprefix/main.go +++ b/internal/ingress/annotations/xforwardedprefix/main.go @@ -23,17 +23,46 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + xForwardedForPrefixAnnotation = "x-forwarded-prefix" +) + +var xForwardedForAnnotations = parser.Annotation{ + Group: "backend", + Annotations: parser.AnnotationFields{ + xForwardedForPrefixAnnotation: { + Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, // Low, as it allows regexes but on a very limited set + Documentation: `This annotation can be used to add the non-standard X-Forwarded-Prefix header to the upstream request with a string value`, + }, + }, +} + type xforwardedprefix struct { - r resolver.Resolver + r resolver.Resolver + annotationConfig parser.Annotation } // NewParser creates a new xforwardedprefix annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return xforwardedprefix{r} + return xforwardedprefix{ + r: r, + annotationConfig: xForwardedForAnnotations, + } } // Parse parses the annotations contained in the ingress rule // used to add an x-forwarded-prefix header to the request func (cbbs xforwardedprefix) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation("x-forwarded-prefix", ing) + return parser.GetStringAnnotation(xForwardedForPrefixAnnotation, ing, cbbs.annotationConfig.Annotations) +} + +func (cbbs xforwardedprefix) GetDocumentation() parser.AnnotationFields { + return cbbs.annotationConfig.Annotations +} + +func (a xforwardedprefix) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) + return parser.CheckAnnotationRisk(anns, maxrisk, xForwardedForAnnotations.Annotations) } diff --git a/internal/ingress/annotations/xforwardedprefix/main_test.go b/internal/ingress/annotations/xforwardedprefix/main_test.go index a78c63d04..d873a4412 100644 --- a/internal/ingress/annotations/xforwardedprefix/main_test.go +++ b/internal/ingress/annotations/xforwardedprefix/main_test.go @@ -27,7 +27,7 @@ import ( ) func TestParse(t *testing.T) { - annotation := parser.GetAnnotationWithPrefix("x-forwarded-prefix") + annotation := parser.GetAnnotationWithPrefix(xForwardedForPrefixAnnotation) ap := NewParser(&resolver.Mock{}) if ap == nil { t.Fatalf("expected a parser.IngressAnnotation but returned nil") diff --git a/internal/ingress/controller/config/config.go b/internal/ingress/controller/config/config.go index 345ce89b4..6e78964ed 100644 --- a/internal/ingress/controller/config/config.go +++ b/internal/ingress/controller/config/config.go @@ -97,6 +97,17 @@ type Configuration struct { // If disabled, only snippets added via ConfigMap are added to ingress. AllowSnippetAnnotations bool `json:"allow-snippet-annotations"` + // AllowCrossNamespaceResources enables users to consume cross namespace resource on annotations + // Case disabled, attempts to use secrets or configmaps from a namespace different from Ingress will + // be denied + // This value will default to `false` on future releases + AllowCrossNamespaceResources bool `json:"allow-cross-namespace-resources"` + + // AnnotationsRiskLevel represents the risk accepted on an annotation. If the risk is, for instance `Medium`, annotations + // with risk High and Critical will not be accepted. + // Default Risk is Critical by default, but this may be changed in future releases + AnnotationsRiskLevel string `json:"annotations-risk-level"` + // AnnotationValueWordBlocklist defines words that should not be part of an user annotation value // (can be used to run arbitrary code or configs, for example) and that should be dropped. // This list should be separated by "," character @@ -708,7 +719,7 @@ type Configuration struct { // DatadogSampleRate specifies sample rate for any traces created. // Default: use a dynamic rate instead - DatadogSampleRate *float32 `json:"datadog-sample-rate",omitempty` + DatadogSampleRate *float32 `json:"datadog-sample-rate,omitempty"` // MainSnippet adds custom configuration to the main section of the nginx configuration MainSnippet string `json:"main-snippet"` @@ -853,8 +864,10 @@ func NewDefault() Configuration { cfg := Configuration{ AllowSnippetAnnotations: true, + AllowCrossNamespaceResources: true, AllowBackendServerHeader: false, AnnotationValueWordBlocklist: "", + AnnotationsRiskLevel: "Critical", AccessLogPath: "/var/log/nginx/access.log", AccessLogParams: "", EnableAccessLogForDefaultBackend: false, diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index 4a4417130..7dc1a5292 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -389,14 +389,19 @@ func (n *NGINXController) CheckIngress(ing *networking.Ingress) error { toCheck.ObjectMeta.Name == ing.ObjectMeta.Name } ings := store.FilterIngresses(allIngresses, filter) + parsed, err := annotations.NewAnnotationExtractor(n.store).Extract(ing) + if err != nil { + n.metricCollector.IncCheckErrorCount(ing.ObjectMeta.Namespace, ing.Name) + return err + } ings = append(ings, &ingress.Ingress{ Ingress: *ing, - ParsedAnnotations: annotations.NewAnnotationExtractor(n.store).Extract(ing), + ParsedAnnotations: parsed, }) startTest := time.Now().UnixNano() / 1000000 _, servers, pcfg := n.getConfiguration(ings) - err := checkOverlap(ing, allIngresses, servers) + err = checkOverlap(ing, allIngresses, servers) if err != nil { n.metricCollector.IncCheckErrorCount(ing.ObjectMeta.Namespace, ing.Name) return err @@ -1509,7 +1514,7 @@ func locationApplyAnnotations(loc *ingress.Location, anns *annotations.Ingress) loc.Rewrite = anns.Rewrite loc.UpstreamVhost = anns.UpstreamVhost loc.Denylist = anns.Denylist - loc.Whitelist = anns.Whitelist + loc.Allowlist = anns.Allowlist loc.Denied = anns.Denied loc.XForwardedPrefix = anns.XForwardedPrefix loc.UsePortInRedirects = anns.UsePortInRedirects @@ -1808,9 +1813,9 @@ func checkOverlap(ing *networking.Ingress, ingresses []*ingress.Ingress, servers } // path overlap. Check if one of the ingresses has a canary annotation - isCanaryEnabled, annotationErr := parser.GetBoolAnnotation("canary", ing) + isCanaryEnabled, annotationErr := parser.GetBoolAnnotation("canary", ing, canary.CanaryAnnotations.Annotations) for _, existing := range existingIngresses { - isExistingCanaryEnabled, existingAnnotationErr := parser.GetBoolAnnotation("canary", existing) + isExistingCanaryEnabled, existingAnnotationErr := parser.GetBoolAnnotation("canary", existing, canary.CanaryAnnotations.Annotations) if isCanaryEnabled && isExistingCanaryEnabled { return fmt.Errorf(`host "%s" and path "%s" is already defined in ingress %s/%s`, rule.Host, path.Path, existing.Namespace, existing.Name) diff --git a/internal/ingress/controller/controller_test.go b/internal/ingress/controller/controller_test.go index 44184f6b9..c353d1b5e 100644 --- a/internal/ingress/controller/controller_test.go +++ b/internal/ingress/controller/controller_test.go @@ -44,7 +44,7 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations" "k8s.io/ingress-nginx/internal/ingress/annotations/canary" - "k8s.io/ingress-nginx/internal/ingress/annotations/ipwhitelist" + "k8s.io/ingress-nginx/internal/ingress/annotations/ipallowlist" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" "k8s.io/ingress-nginx/internal/ingress/annotations/proxyssl" "k8s.io/ingress-nginx/internal/ingress/annotations/sessionaffinity" @@ -73,6 +73,13 @@ func (fis fakeIngressStore) GetBackendConfiguration() ngx_config.Configuration { return fis.configuration } +func (fis fakeIngressStore) GetSecurityConfiguration() defaults.SecurityConfiguration { + return defaults.SecurityConfiguration{ + AnnotationsRiskLevel: fis.configuration.AnnotationsRiskLevel, + AllowCrossNamespaceResources: fis.configuration.AllowCrossNamespaceResources, + } +} + func (fakeIngressStore) GetConfigMap(key string) (*corev1.ConfigMap, error) { return nil, fmt.Errorf("test error") } @@ -2418,7 +2425,7 @@ func TestGetBackendServers(t *testing.T) { }, }, ParsedAnnotations: &annotations.Ingress{ - Whitelist: ipwhitelist.SourceRange{CIDR: []string{"10.0.0.0/24"}}, + Allowlist: ipallowlist.SourceRange{CIDR: []string{"10.0.0.0/24"}}, ServerSnippet: "bla", ConfigurationSnippet: "blo", }, @@ -2439,7 +2446,7 @@ func TestGetBackendServers(t *testing.T) { t.Errorf("config snippet should be empty, got '%s'", s.Locations[0].ConfigurationSnippet) } - if len(s.Locations[0].Whitelist.CIDR) != 1 || s.Locations[0].Whitelist.CIDR[0] != "10.0.0.0/24" { + if len(s.Locations[0].Allowlist.CIDR) != 1 || s.Locations[0].Allowlist.CIDR[0] != "10.0.0.0/24" { t.Errorf("allow list was incorrectly dropped, len should be 1 and contain 10.0.0.0/24") } diff --git a/internal/ingress/controller/store/store.go b/internal/ingress/controller/store/store.go index 9b3700739..c11e35d76 100644 --- a/internal/ingress/controller/store/store.go +++ b/internal/ingress/controller/store/store.go @@ -69,6 +69,9 @@ type Storer interface { // GetBackendConfiguration returns the nginx configuration stored in a configmap GetBackendConfiguration() ngx_config.Configuration + // GetSecurityConfiguration returns the configuration options from Ingress + GetSecurityConfiguration() defaults.SecurityConfiguration + // GetConfigMap returns the ConfigMap matching key. GetConfigMap(key string) (*corev1.ConfigMap, error) @@ -882,9 +885,14 @@ func (s *k8sStore) syncIngress(ing *networkingv1.Ingress) { k8s.SetDefaultNGINXPathType(copyIng) - err := s.listers.IngressWithAnnotation.Update(&ingress.Ingress{ + parsed, err := s.annotations.Extract(ing) + if err != nil { + klog.Error(err) + return + } + err = s.listers.IngressWithAnnotation.Update(&ingress.Ingress{ Ingress: *copyIng, - ParsedAnnotations: s.annotations.Extract(ing), + ParsedAnnotations: parsed, }) if err != nil { klog.Error(err) @@ -920,8 +928,10 @@ func (s *k8sStore) updateSecretIngressMap(ing *networkingv1.Ingress) { "proxy-ssl-secret", "secure-verify-ca-secret", } + + secConfig := s.GetSecurityConfiguration().AllowCrossNamespaceResources for _, ann := range secretAnnotations { - secrKey, err := objectRefAnnotationNsKey(ann, ing) + secrKey, err := objectRefAnnotationNsKey(ann, ing, secConfig) if err != nil && !errors.IsMissingAnnotations(err) { klog.Errorf("error reading secret reference in annotation %q: %s", ann, err) continue @@ -937,8 +947,9 @@ func (s *k8sStore) updateSecretIngressMap(ing *networkingv1.Ingress) { // objectRefAnnotationNsKey returns an object reference formatted as a // 'namespace/name' key from the given annotation name. -func objectRefAnnotationNsKey(ann string, ing *networkingv1.Ingress) (string, error) { - annValue, err := parser.GetStringAnnotation(ann, ing) +func objectRefAnnotationNsKey(ann string, ing *networkingv1.Ingress, allowCrossNamespace bool) (string, error) { + // We pass nil fields, as this is an internal process and we don't need to validate it. + annValue, err := parser.GetStringAnnotation(ann, ing, nil) if err != nil { return "", err } @@ -951,6 +962,9 @@ func objectRefAnnotationNsKey(ann string, ing *networkingv1.Ingress) (string, er if secrNs == "" { return fmt.Sprintf("%v/%v", ing.Namespace, secrName), nil } + if !allowCrossNamespace && secrNs != ing.Namespace { + return "", fmt.Errorf("cross namespace secret is not supported") + } return annValue, nil } @@ -1125,6 +1139,17 @@ func (s *k8sStore) GetBackendConfiguration() ngx_config.Configuration { return s.backendConfig } +func (s *k8sStore) GetSecurityConfiguration() defaults.SecurityConfiguration { + s.backendConfigMu.RLock() + defer s.backendConfigMu.RUnlock() + + secConfig := defaults.SecurityConfiguration{ + AllowCrossNamespaceResources: s.backendConfig.AllowCrossNamespaceResources, + AnnotationsRiskLevel: s.backendConfig.AnnotationsRiskLevel, + } + return secConfig +} + func (s *k8sStore) setConfig(cmap *corev1.ConfigMap) { s.backendConfigMu.Lock() defer s.backendConfigMu.Unlock() diff --git a/internal/ingress/controller/store/store_test.go b/internal/ingress/controller/store/store_test.go index b91cadc6c..774a45676 100644 --- a/internal/ingress/controller/store/store_test.go +++ b/internal/ingress/controller/store/store_test.go @@ -1414,18 +1414,31 @@ func TestUpdateSecretIngressMap(t *testing.T) { t.Run("with annotation in namespace/name format", func(t *testing.T) { ing := ingTpl.DeepCopy() ing.ObjectMeta.SetAnnotations(map[string]string{ - parser.GetAnnotationWithPrefix("auth-secret"): "otherns/auth", + parser.GetAnnotationWithPrefix("auth-secret"): "testns/auth", }) if err := s.listers.Ingress.Update(ing); err != nil { t.Errorf("error updating the Ingress: %v", err) } s.updateSecretIngressMap(ing) - if l := s.secretIngressMap.Len(); !(l == 1 && s.secretIngressMap.Has("otherns/auth")) { + if l := s.secretIngressMap.Len(); !(l == 1 && s.secretIngressMap.Has("testns/auth")) { t.Errorf("Expected \"otherns/auth\" to be the only referenced Secret (got %d)", l) } }) + t.Run("with annotation in namespace/name format should not be supported", func(t *testing.T) { + ing := ingTpl.DeepCopy() + ing.ObjectMeta.SetAnnotations(map[string]string{ + parser.GetAnnotationWithPrefix("auth-secret"): "anotherns/auth", + }) + s.listers.Ingress.Update(ing) + s.updateSecretIngressMap(ing) + + if l := s.secretIngressMap.Len(); l != 0 { + t.Errorf("Expected \"otherns/auth\" to be denied as it contains a different namespace (got %d)", l) + } + }) + t.Run("with annotation in invalid format", func(t *testing.T) { ing := ingTpl.DeepCopy() ing.ObjectMeta.SetAnnotations(map[string]string{ diff --git a/internal/ingress/defaults/main.go b/internal/ingress/defaults/main.go index 0aab2ff47..8cd0e8ba5 100644 --- a/internal/ingress/defaults/main.go +++ b/internal/ingress/defaults/main.go @@ -170,3 +170,15 @@ type Backend struct { // It disables that behavior and instead uses a single upstream in NGINX, the service's Cluster IP and port. ServiceUpstream bool `json:"service-upstream"` } + +type SecurityConfiguration struct { + // AllowCrossNamespaceResources enables users to consume cross namespace resource on annotations + // Case disabled, attempts to use secrets or configmaps from a namespace different from Ingress will + // be denied + // This valid will default to `false` on future releases + AllowCrossNamespaceResources bool `json:"allow-cross-namespace-resources"` + + // AnnotationsRiskLevel represents the risk accepted on an annotation. If the risk is, for instance `Medium`, annotations + // with risk High and Critical will not be accepted + AnnotationsRiskLevel string `json:"annotations-risk-level"` +} diff --git a/internal/ingress/errors/errors.go b/internal/ingress/errors/errors.go index 93c9ee5e0..e6f7fb52c 100644 --- a/internal/ingress/errors/errors.go +++ b/internal/ingress/errors/errors.go @@ -110,3 +110,47 @@ func New(m string) error { func Errorf(format string, args ...interface{}) error { return fmt.Errorf(format, args...) } + +type ValidationError struct { + Reason error +} + +type RiskyAnnotationError struct { + Reason error +} + +func (e ValidationError) Error() string { + return e.Reason.Error() +} + +// NewValidationError returns a new LocationDenied error +func NewValidationError(annotation string) error { + return ValidationError{ + Reason: fmt.Errorf("annotation %s contains invalid value", annotation), + } +} + +// IsValidationError checks if the err is an error which +// indicates that some annotation value is invalid +func IsValidationError(e error) bool { + _, ok := e.(ValidationError) + return ok +} + +// NewValidationError returns a new LocationDenied error +func NewRiskyAnnotations(name string) error { + return RiskyAnnotationError{ + Reason: fmt.Errorf("annotation group %s contains risky annotation based on ingress configuration", name), + } +} + +// IsRiskyAnnotationError checks if the err is an error which +// indicates that some annotation value is invalid +func IsRiskyAnnotationError(e error) bool { + _, ok := e.(ValidationError) + return ok +} + +func (e RiskyAnnotationError) Error() string { + return e.Reason.Error() +} diff --git a/internal/ingress/resolver/main.go b/internal/ingress/resolver/main.go index e05a2aaae..7d17f4e16 100644 --- a/internal/ingress/resolver/main.go +++ b/internal/ingress/resolver/main.go @@ -26,6 +26,9 @@ type Resolver interface { // GetDefaultBackend returns the backend that must be used as default GetDefaultBackend() defaults.Backend + // GetSecurityConfiguration returns the configuration options from Ingress + GetSecurityConfiguration() defaults.SecurityConfiguration + // GetConfigMap searches for configmap containing the namespace and name usting the character / GetConfigMap(string) (*apiv1.ConfigMap, error) diff --git a/internal/ingress/resolver/mock.go b/internal/ingress/resolver/mock.go index 62c5c6db9..679c3b13c 100644 --- a/internal/ingress/resolver/mock.go +++ b/internal/ingress/resolver/mock.go @@ -26,7 +26,9 @@ import ( // Mock implements the Resolver interface type Mock struct { - ConfigMaps map[string]*apiv1.ConfigMap + ConfigMaps map[string]*apiv1.ConfigMap + AnnotationsRiskLevel string + AllowCrossNamespace bool } // GetDefaultBackend returns the backend that must be used as default @@ -34,6 +36,17 @@ func (m Mock) GetDefaultBackend() defaults.Backend { return defaults.Backend{} } +func (m Mock) GetSecurityConfiguration() defaults.SecurityConfiguration { + defRisk := m.AnnotationsRiskLevel + if defRisk == "" { + defRisk = "Critical" + } + return defaults.SecurityConfiguration{ + AnnotationsRiskLevel: defRisk, + AllowCrossNamespaceResources: m.AllowCrossNamespace, + } +} + // GetSecret searches for secrets contenating the namespace and name using a the character / func (m Mock) GetSecret(string) (*apiv1.Secret, error) { return nil, nil diff --git a/pkg/apis/ingress/types.go b/pkg/apis/ingress/types.go index e50666c18..284e9b427 100644 --- a/pkg/apis/ingress/types.go +++ b/pkg/apis/ingress/types.go @@ -29,8 +29,8 @@ import ( "k8s.io/ingress-nginx/internal/ingress/annotations/cors" "k8s.io/ingress-nginx/internal/ingress/annotations/fastcgi" "k8s.io/ingress-nginx/internal/ingress/annotations/globalratelimit" + "k8s.io/ingress-nginx/internal/ingress/annotations/ipallowlist" "k8s.io/ingress-nginx/internal/ingress/annotations/ipdenylist" - "k8s.io/ingress-nginx/internal/ingress/annotations/ipwhitelist" "k8s.io/ingress-nginx/internal/ingress/annotations/log" "k8s.io/ingress-nginx/internal/ingress/annotations/mirror" "k8s.io/ingress-nginx/internal/ingress/annotations/modsecurity" @@ -224,7 +224,7 @@ type Server struct { // is required. // The chain in the execution order of annotations should be: // - Denylist -// - Whitelist +// - Allowlist // - RateLimit // - BasicDigestAuth // - ExternalAuth @@ -298,10 +298,10 @@ type Location struct { // addresses or networks are allowed. // +optional Denylist ipdenylist.SourceRange `json:"denylist,omitempty"` - // Whitelist indicates only connections from certain client + // Allowlist indicates only connections from certain client // addresses or networks are allowed. // +optional - Whitelist ipwhitelist.SourceRange `json:"whitelist,omitempty"` + Allowlist ipallowlist.SourceRange `json:"allowlist,omitempty"` // Proxy contains information about timeouts and buffer sizes // to be used in connections against endpoints // +optional diff --git a/pkg/apis/ingress/types_equals.go b/pkg/apis/ingress/types_equals.go index 84b1a186a..c87f5ba3e 100644 --- a/pkg/apis/ingress/types_equals.go +++ b/pkg/apis/ingress/types_equals.go @@ -400,7 +400,7 @@ func (l1 *Location) Equal(l2 *Location) bool { if !(&l1.Denylist).Equal(&l2.Denylist) { return false } - if !(&l1.Whitelist).Equal(&l2.Whitelist) { + if !(&l1.Allowlist).Equal(&l2.Allowlist) { return false } if !(&l1.Proxy).Equal(&l2.Proxy) { diff --git a/pkg/flags/flags.go b/pkg/flags/flags.go index 489e24886..2c926a35f 100644 --- a/pkg/flags/flags.go +++ b/pkg/flags/flags.go @@ -152,6 +152,9 @@ Requires the update-status parameter.`) annotationsPrefix = flags.String("annotations-prefix", parser.DefaultAnnotationsPrefix, `Prefix of the Ingress annotations specific to the NGINX controller.`) + enableAnnotationValidation = flags.Bool("enable-annotation-validation", false, + `If true, will enable the annotation validation feature. This value will be defaulted to true on a future release`) + enableSSLChainCompletion = flags.Bool("enable-ssl-chain-completion", false, `Autocomplete SSL certificate chains with missing intermediate CA certificates. Certificates uploaded to Kubernetes must have the "Authority Information Access" X.509 v3 @@ -249,6 +252,7 @@ https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-g } parser.AnnotationsPrefix = *annotationsPrefix + parser.EnableAnnotationValidation = *enableAnnotationValidation // check port collisions if !ing_net.IsPortAvailable(*httpPort) { diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 189c13d6c..02b5309cd 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -548,14 +548,14 @@ http { {{ range $rl := (filterRateLimits $servers ) }} # Ratelimit {{ $rl.Name }} - geo $remote_addr $whitelist_{{ $rl.ID }} { + geo $remote_addr $allowlist_{{ $rl.ID }} { default 0; - {{ range $ip := $rl.Whitelist }} + {{ range $ip := $rl.Allowlist }} {{ $ip }} 1;{{ end }} } # Ratelimit {{ $rl.Name }} - map $whitelist_{{ $rl.ID }} $limit_{{ $rl.ID }} { + map $allowlist_{{ $rl.ID }} $limit_{{ $rl.ID }} { 0 {{ $cfg.LimitConnZoneVariable }}; 1 ""; } @@ -1312,8 +1312,8 @@ stream { {{ range $ip := $location.Denylist.CIDR }} deny {{ $ip }};{{ end }} {{ end }} - {{ if gt (len $location.Whitelist.CIDR) 0 }} - {{ range $ip := $location.Whitelist.CIDR }} + {{ if gt (len $location.Allowlist.CIDR) 0 }} + {{ range $ip := $location.Allowlist.CIDR }} allow {{ $ip }};{{ end }} deny all; {{ end }} diff --git a/test/e2e-image/namespace-overlays/validations/values.yaml b/test/e2e-image/namespace-overlays/validations/values.yaml new file mode 100644 index 000000000..d423217db --- /dev/null +++ b/test/e2e-image/namespace-overlays/validations/values.yaml @@ -0,0 +1,38 @@ +# TODO: remove the need to use fullnameOverride +fullnameOverride: nginx-ingress +controller: + image: + repository: ingress-controller/controller + chroot: true + tag: 1.0.0-dev + digest: + digestChroot: + containerPort: + http: "1080" + https: "1443" + + extraArgs: + http-port: "1080" + https-port: "1443" + # e2e tests do not require information about ingress status + update-status: "false" + + scope: + enabled: true + + config: + worker-processes: "1" + service: + type: NodePort + + admissionWebhooks: + enabled: true + certificate: "/usr/local/certificates/cert" + key: "/usr/local/certificates/key" + +defaultBackend: + enabled: false + +rbac: + create: true + scope: true diff --git a/test/e2e/annotations/fastcgi.go b/test/e2e/annotations/fastcgi.go index 572eca548..7ed35cb76 100644 --- a/test/e2e/annotations/fastcgi.go +++ b/test/e2e/annotations/fastcgi.go @@ -75,7 +75,7 @@ var _ = framework.DescribeAnnotation("backend-protocol - FastCGI", func() { Namespace: f.Namespace, }, Data: map[string]string{ - "SCRIPT_FILENAME": "/home/www/scripts/php$fastcgi_script_name", + "SCRIPT_FILENAME": "$fastcgi_script_name", "REDIRECT_STATUS": "200", }, } @@ -94,7 +94,7 @@ var _ = framework.DescribeAnnotation("backend-protocol - FastCGI", func() { f.WaitForNginxServer(host, func(server string) bool { - return strings.Contains(server, "fastcgi_param SCRIPT_FILENAME \"/home/www/scripts/php$fastcgi_script_name\";") && + return strings.Contains(server, "fastcgi_param SCRIPT_FILENAME \"$fastcgi_script_name\";") && strings.Contains(server, "fastcgi_param REDIRECT_STATUS \"200\";") }) }) diff --git a/test/e2e/annotations/ipwhitelist.go b/test/e2e/annotations/ipallowlist.go similarity index 81% rename from test/e2e/annotations/ipwhitelist.go rename to test/e2e/annotations/ipallowlist.go index 71f026c7f..79c77b4d0 100644 --- a/test/e2e/annotations/ipwhitelist.go +++ b/test/e2e/annotations/ipallowlist.go @@ -24,19 +24,19 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) -var _ = framework.DescribeAnnotation("whitelist-source-range", func() { - f := framework.NewDefaultFramework("ipwhitelist") +var _ = framework.DescribeAnnotation("allowlist-source-range", func() { + f := framework.NewDefaultFramework("ipallowlist") ginkgo.BeforeEach(func() { f.NewEchoDeployment() }) - ginkgo.It("should set valid ip whitelist range", func() { - host := "ipwhitelist.foo.com" + ginkgo.It("should set valid ip allowlist range", func() { + host := "ipallowlist.foo.com" nameSpace := f.Namespace annotations := map[string]string{ - "nginx.ingress.kubernetes.io/whitelist-source-range": "18.0.0.0/8, 56.0.0.0/8", + "nginx.ingress.kubernetes.io/allowlist-source-range": "18.0.0.0/8, 56.0.0.0/8", } ing := framework.NewSingleIngress(host, "/", host, nameSpace, framework.EchoService, 80, annotations) diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 614dd166a..28adf297d 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -47,6 +47,8 @@ import ( _ "k8s.io/ingress-nginx/test/e2e/settings" _ "k8s.io/ingress-nginx/test/e2e/settings/modsecurity" _ "k8s.io/ingress-nginx/test/e2e/settings/ocsp" + _ "k8s.io/ingress-nginx/test/e2e/settings/validations" + _ "k8s.io/ingress-nginx/test/e2e/ssl" _ "k8s.io/ingress-nginx/test/e2e/status" _ "k8s.io/ingress-nginx/test/e2e/tcpudp" diff --git a/test/e2e/framework/exec.go b/test/e2e/framework/exec.go index d91d36551..07bf09be8 100644 --- a/test/e2e/framework/exec.go +++ b/test/e2e/framework/exec.go @@ -116,7 +116,12 @@ func (f *Framework) newIngressController(namespace string, namespaceOverlay stri if !ok { isChroot = "false" } - cmd := exec.Command("./wait-for-nginx.sh", namespace, namespaceOverlay, isChroot) + + enableAnnotationValidations, ok := os.LookupEnv("ENABLE_VALIDATIONS") + if !ok { + enableAnnotationValidations = "false" + } + cmd := exec.Command("./wait-for-nginx.sh", namespace, namespaceOverlay, isChroot, enableAnnotationValidations) out, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("unexpected error waiting for ingress controller deployment: %v.\nLogs:\n%v", err, string(out)) diff --git a/test/e2e/run-e2e-suite.sh b/test/e2e/run-e2e-suite.sh index b56312afd..015895e56 100755 --- a/test/e2e/run-e2e-suite.sh +++ b/test/e2e/run-e2e-suite.sh @@ -78,6 +78,7 @@ kubectl run --rm \ --env="E2E_NODES=${E2E_NODES}" \ --env="FOCUS=${FOCUS}" \ --env="IS_CHROOT=${IS_CHROOT:-false}"\ + --env="ENABLE_VALIDATIONS=${ENABLE_VALIDATIONS:-false}"\ --env="E2E_CHECK_LEAKS=${E2E_CHECK_LEAKS}" \ --env="NGINX_BASE_IMAGE=${NGINX_BASE_IMAGE}" \ --env="HTTPBUN_IMAGE=${HTTPBUN_IMAGE}" \ diff --git a/test/e2e/run-kind-e2e.sh b/test/e2e/run-kind-e2e.sh index e6e4e086b..4dc1bddd0 100755 --- a/test/e2e/run-kind-e2e.sh +++ b/test/e2e/run-kind-e2e.sh @@ -39,6 +39,7 @@ fi KIND_LOG_LEVEL="1" IS_CHROOT="${IS_CHROOT:-false}" +ENABLE_VALIDATIONS="${ENABLE_VALIDATIONS:-false}" export KIND_CLUSTER_NAME=${KIND_CLUSTER_NAME:-ingress-nginx-dev} DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Use 1.0.0-dev to make sure we use the latest configuration in the helm template diff --git a/test/e2e/settings/validations/validations.go b/test/e2e/settings/validations/validations.go new file mode 100644 index 000000000..6f1715ada --- /dev/null +++ b/test/e2e/settings/validations/validations.go @@ -0,0 +1,86 @@ +/* +Copyright 2023 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package annotations + +import ( + "context" + + "github.com/onsi/ginkgo/v2" + "github.com/stretchr/testify/assert" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "k8s.io/ingress-nginx/test/e2e/framework" +) + +var _ = framework.IngressNginxDescribeSerial("annotation validations", func() { + f := framework.NewDefaultFramework("validations") + + ginkgo.It("should allow ingress based on their risk on webhooks", func() { + host := "annotation-validations" + + // Low and Medium Risk annotations should be allowed, the rest should be denied + f.UpdateNginxConfigMapData("annotations-risk-level", "Medium") + // Sleep a while just to guarantee that the configmap is applied + framework.Sleep() + + annotations := map[string]string{ + "nginx.ingress.kubernetes.io/default-backend": "default/bla", // low risk + "nginx.ingress.kubernetes.io/denylist-source-range": "1.1.1.1/32", // medium risk + } + + ginkgo.By("allow ingress with low/medium risk annotations") + ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) + _, err := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Create(context.TODO(), ing, metav1.CreateOptions{}) + assert.Nil(ginkgo.GinkgoT(), err, "creating ingress with allowed annotations should not trigger an error") + + ginkgo.By("block ingress with risky annotations") + annotations["nginx.ingress.kubernetes.io/modsecurity-transaction-id"] = "bla123" // High should be blocked + annotations["nginx.ingress.kubernetes.io/modsecurity-snippet"] = "some random stuff;" // High should be blocked + ing = framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) + _, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Update(context.TODO(), ing, metav1.UpdateOptions{}) + assert.NotNil(ginkgo.GinkgoT(), err, "creating ingress with risky annotations should trigger an error") + + }) + + ginkgo.It("should allow ingress based on their risk on webhooks", func() { + host := "annotation-validations" + + // Low and Medium Risk annotations should be allowed, the rest should be denied + f.UpdateNginxConfigMapData("annotations-risk-level", "Medium") + // Sleep a while just to guarantee that the configmap is applied + framework.Sleep() + + annotations := map[string]string{ + "nginx.ingress.kubernetes.io/default-backend": "default/bla", // low risk + "nginx.ingress.kubernetes.io/denylist-source-range": "1.1.1.1/32", // medium risk + } + + ginkgo.By("allow ingress with low/medium risk annotations") + ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) + _, err := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Create(context.TODO(), ing, metav1.CreateOptions{}) + assert.Nil(ginkgo.GinkgoT(), err, "creating ingress with allowed annotations should not trigger an error") + + ginkgo.By("block ingress with risky annotations") + annotations["nginx.ingress.kubernetes.io/modsecurity-transaction-id"] = "bla123" // High should be blocked + annotations["nginx.ingress.kubernetes.io/modsecurity-snippet"] = "some random stuff;" // High should be blocked + ing = framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) + _, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Update(context.TODO(), ing, metav1.UpdateOptions{}) + assert.NotNil(ginkgo.GinkgoT(), err, "creating ingress with risky annotations should trigger an error") + + }) +}) diff --git a/test/e2e/wait-for-nginx.sh b/test/e2e/wait-for-nginx.sh index 153d348c2..0726bde10 100755 --- a/test/e2e/wait-for-nginx.sh +++ b/test/e2e/wait-for-nginx.sh @@ -24,6 +24,7 @@ DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" export NAMESPACE=$1 export NAMESPACE_OVERLAY=$2 export IS_CHROOT=$3 +export ENABLE_VALIDATIONS=$4 echo "deploying NGINX Ingress controller in namespace $NAMESPACE" @@ -68,6 +69,7 @@ else # TODO: remove the need to use fullnameOverride fullnameOverride: nginx-ingress controller: + enableAnnotationValidations: ${ENABLE_VALIDATIONS} image: repository: ingress-controller/controller chroot: ${IS_CHROOT} From ee9c6246f25799677a67a93c4913a70cf756c174 Mon Sep 17 00:00:00 2001 From: Chen Chen Date: Mon, 24 Jul 2023 23:26:13 +0800 Subject: [PATCH 18/47] Add rolling update strategy to each static deployment file (#10129) * Add rollingUpdate strategy to each static deployment file Signed-off-by: z1cheng * Update the templates and regenerate Signed-off-by: z1cheng * Upgrade k8s version and add rolling update for exoscale Signed-off-by: z1cheng * Add rolling update strategy to Oracle template Signed-off-by: z1cheng * Revert the k8s version in generate-deploy-scripts.sh Signed-off-by: z1cheng --------- Signed-off-by: z1cheng --- deploy/static/provider/aws/deploy.yaml | 4 ++++ .../static/provider/aws/nlb-with-tls-termination/deploy.yaml | 4 ++++ deploy/static/provider/baremetal/deploy.yaml | 4 ++++ deploy/static/provider/cloud/deploy.yaml | 4 ++++ deploy/static/provider/do/deploy.yaml | 4 ++++ deploy/static/provider/exoscale/deploy.yaml | 4 ++++ deploy/static/provider/oracle/deploy.yaml | 4 ++++ deploy/static/provider/scw/deploy.yaml | 4 ++++ .../provider/aws/nlb-with-tls-termination/values.yaml | 4 ++++ hack/manifest-templates/provider/aws/values.yaml | 4 ++++ hack/manifest-templates/provider/baremetal/values.yaml | 4 ++++ hack/manifest-templates/provider/cloud/values.yaml | 4 ++++ hack/manifest-templates/provider/do/values.yaml | 4 ++++ hack/manifest-templates/provider/exoscale/values.yaml | 4 ++++ hack/manifest-templates/provider/oracle/values.yaml | 4 ++++ hack/manifest-templates/provider/scw/values.yaml | 4 ++++ 16 files changed, 64 insertions(+) diff --git a/deploy/static/provider/aws/deploy.yaml b/deploy/static/provider/aws/deploy.yaml index f22f3a9c1..2c785fab2 100644 --- a/deploy/static/provider/aws/deploy.yaml +++ b/deploy/static/provider/aws/deploy.yaml @@ -411,6 +411,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/aws/nlb-with-tls-termination/deploy.yaml b/deploy/static/provider/aws/nlb-with-tls-termination/deploy.yaml index e9ae85143..7eb2a4c12 100644 --- a/deploy/static/provider/aws/nlb-with-tls-termination/deploy.yaml +++ b/deploy/static/provider/aws/nlb-with-tls-termination/deploy.yaml @@ -420,6 +420,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/baremetal/deploy.yaml b/deploy/static/provider/baremetal/deploy.yaml index b66da7d45..ba5b71838 100644 --- a/deploy/static/provider/baremetal/deploy.yaml +++ b/deploy/static/provider/baremetal/deploy.yaml @@ -406,6 +406,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/cloud/deploy.yaml b/deploy/static/provider/cloud/deploy.yaml index 659da1d1b..0bb95331f 100644 --- a/deploy/static/provider/cloud/deploy.yaml +++ b/deploy/static/provider/cloud/deploy.yaml @@ -407,6 +407,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/do/deploy.yaml b/deploy/static/provider/do/deploy.yaml index 434f21ead..9ef7f86ee 100644 --- a/deploy/static/provider/do/deploy.yaml +++ b/deploy/static/provider/do/deploy.yaml @@ -410,6 +410,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/exoscale/deploy.yaml b/deploy/static/provider/exoscale/deploy.yaml index c9dff62cb..d09c9bbb4 100644 --- a/deploy/static/provider/exoscale/deploy.yaml +++ b/deploy/static/provider/exoscale/deploy.yaml @@ -510,6 +510,10 @@ spec: - name: webhook-cert secret: secretName: ingress-nginx-admission + updateStrategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate --- apiVersion: batch/v1 kind: Job diff --git a/deploy/static/provider/oracle/deploy.yaml b/deploy/static/provider/oracle/deploy.yaml index 72556bb42..4c93acfb2 100644 --- a/deploy/static/provider/oracle/deploy.yaml +++ b/deploy/static/provider/oracle/deploy.yaml @@ -411,6 +411,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/deploy/static/provider/scw/deploy.yaml b/deploy/static/provider/scw/deploy.yaml index 8b4750992..a57ef5ded 100644 --- a/deploy/static/provider/scw/deploy.yaml +++ b/deploy/static/provider/scw/deploy.yaml @@ -410,6 +410,10 @@ spec: app.kubernetes.io/component: controller app.kubernetes.io/instance: ingress-nginx app.kubernetes.io/name: ingress-nginx + strategy: + rollingUpdate: + maxUnavailable: 1 + type: RollingUpdate template: metadata: labels: diff --git a/hack/manifest-templates/provider/aws/nlb-with-tls-termination/values.yaml b/hack/manifest-templates/provider/aws/nlb-with-tls-termination/values.yaml index 5b36b3dd2..46f8417c7 100644 --- a/hack/manifest-templates/provider/aws/nlb-with-tls-termination/values.yaml +++ b/hack/manifest-templates/provider/aws/nlb-with-tls-termination/values.yaml @@ -1,5 +1,9 @@ # AWS NLB with TLS termination controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/aws/values.yaml b/hack/manifest-templates/provider/aws/values.yaml index 743721fc4..37eac03c2 100644 --- a/hack/manifest-templates/provider/aws/values.yaml +++ b/hack/manifest-templates/provider/aws/values.yaml @@ -1,5 +1,9 @@ # AWS - NLB controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/baremetal/values.yaml b/hack/manifest-templates/provider/baremetal/values.yaml index 3c5a0840b..205a7430c 100644 --- a/hack/manifest-templates/provider/baremetal/values.yaml +++ b/hack/manifest-templates/provider/baremetal/values.yaml @@ -1,5 +1,9 @@ # Baremetal controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: NodePort diff --git a/hack/manifest-templates/provider/cloud/values.yaml b/hack/manifest-templates/provider/cloud/values.yaml index 7d8266c0f..edc5662dd 100644 --- a/hack/manifest-templates/provider/cloud/values.yaml +++ b/hack/manifest-templates/provider/cloud/values.yaml @@ -1,4 +1,8 @@ controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/do/values.yaml b/hack/manifest-templates/provider/do/values.yaml index 2b0578414..aeee47ad6 100644 --- a/hack/manifest-templates/provider/do/values.yaml +++ b/hack/manifest-templates/provider/do/values.yaml @@ -1,5 +1,9 @@ # Digital Ocean controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/exoscale/values.yaml b/hack/manifest-templates/provider/exoscale/values.yaml index 17458cac9..867ecc57e 100644 --- a/hack/manifest-templates/provider/exoscale/values.yaml +++ b/hack/manifest-templates/provider/exoscale/values.yaml @@ -1,6 +1,10 @@ # Exoscale controller: kind: DaemonSet + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/oracle/values.yaml b/hack/manifest-templates/provider/oracle/values.yaml index b4480531f..600dbfe5c 100644 --- a/hack/manifest-templates/provider/oracle/values.yaml +++ b/hack/manifest-templates/provider/oracle/values.yaml @@ -1,4 +1,8 @@ controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local diff --git a/hack/manifest-templates/provider/scw/values.yaml b/hack/manifest-templates/provider/scw/values.yaml index cee5e2b1e..56d351dcd 100644 --- a/hack/manifest-templates/provider/scw/values.yaml +++ b/hack/manifest-templates/provider/scw/values.yaml @@ -1,5 +1,9 @@ # Scaleway controller: + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxUnavailable: 1 service: type: LoadBalancer externalTrafficPolicy: Local From 0ec08bd1d06a2fbb797e6ee9116102599ad9f0e1 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 24 Jul 2023 10:22:13 -0700 Subject: [PATCH 19/47] Bump github.com/opencontainers/runc from 1.1.7 to 1.1.8 (#10244) Bumps [github.com/opencontainers/runc](https://github.com/opencontainers/runc) from 1.1.7 to 1.1.8. - [Release notes](https://github.com/opencontainers/runc/releases) - [Changelog](https://github.com/opencontainers/runc/blob/v1.1.8/CHANGELOG.md) - [Commits](https://github.com/opencontainers/runc/compare/v1.1.7...v1.1.8) --- updated-dependencies: - dependency-name: github.com/opencontainers/runc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 8864e3a83..13d0fcf04 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/moul/pb v0.0.0-20220425114252-bca18df4138c github.com/ncabatoff/process-exporter v0.7.10 github.com/onsi/ginkgo/v2 v2.9.5 - github.com/opencontainers/runc v1.1.7 + github.com/opencontainers/runc v1.1.8 github.com/pmezard/go-difflib v1.0.0 github.com/prometheus/client_golang v1.16.0 github.com/prometheus/client_model v0.4.0 diff --git a/go.sum b/go.sum index acd310e3a..6e1495776 100644 --- a/go.sum +++ b/go.sum @@ -289,8 +289,8 @@ github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3Ro github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= -github.com/opencontainers/runc v1.1.7 h1:y2EZDS8sNng4Ksf0GUYNhKbTShZJPJg1FiXJNH/uoCk= -github.com/opencontainers/runc v1.1.7/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= +github.com/opencontainers/runc v1.1.8 h1:zICRlc+C1XzivLc3nzE+cbJV4LIi8tib6YG0MqC6OqA= +github.com/opencontainers/runc v1.1.8/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 h1:3snG66yBm59tKhhSPQrQ/0bCrv1LQbKt40LnUPiUxdc= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= From afd1311f8529c21fdf6621bf683bec814e698f1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Otto=20Kr=C3=B6pke?= Date: Fri, 28 Jul 2023 13:41:56 +0200 Subject: [PATCH 20/47] [helm] configure allow to configure hostAliases (#10180) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Jan-Otto Kröpke --- charts/ingress-nginx/README.md | 1 + charts/ingress-nginx/templates/controller-deployment.yaml | 3 +++ charts/ingress-nginx/values.yaml | 2 ++ 3 files changed, 6 insertions(+) diff --git a/charts/ingress-nginx/README.md b/charts/ingress-nginx/README.md index 17547912d..6288da3e3 100644 --- a/charts/ingress-nginx/README.md +++ b/charts/ingress-nginx/README.md @@ -307,6 +307,7 @@ As of version `1.26.0` of this chart, by simply not providing any clusterIP valu | controller.extraVolumes | list | `[]` | Additional volumes to the controller pod. | | controller.healthCheckHost | string | `""` | Address to bind the health check endpoint. It is better to set this option to the internal node address if the Ingress-Nginx Controller is running in the `hostNetwork: true` mode. | | controller.healthCheckPath | string | `"/healthz"` | Path of the health check endpoint. All requests received on the port defined by the healthz-port parameter are forwarded internally to this path. | +| controller.hostAliases | object | `{}` | Optionally customize the pod hostAliases. | | controller.hostNetwork | bool | `false` | Required for use with CNI based kubernetes installations (such as ones set up by kubeadm), since CNI and hostport don't mix yet. Can be deprecated once https://github.com/kubernetes/kubernetes/issues/23920 is merged | | controller.hostPort.enabled | bool | `false` | Enable 'hostPort' or not | | controller.hostPort.ports.http | int | `80` | 'hostPort' http port | diff --git a/charts/ingress-nginx/templates/controller-deployment.yaml b/charts/ingress-nginx/templates/controller-deployment.yaml index c4a1a37e1..537c3feef 100644 --- a/charts/ingress-nginx/templates/controller-deployment.yaml +++ b/charts/ingress-nginx/templates/controller-deployment.yaml @@ -49,6 +49,9 @@ spec: {{- if .Values.controller.dnsConfig }} dnsConfig: {{ toYaml .Values.controller.dnsConfig | nindent 8 }} {{- end }} + {{- if .Values.controller.hostAliases }} + hostAliases: {{ tpl (toYaml .Values.controller.hostAliases) $ | nindent 8 }} + {{- end }} {{- if .Values.controller.hostname }} hostname: {{ toYaml .Values.controller.hostname | nindent 8 }} {{- end }} diff --git a/charts/ingress-nginx/values.yaml b/charts/ingress-nginx/values.yaml index 1cd74dad0..8205b3506 100644 --- a/charts/ingress-nginx/values.yaml +++ b/charts/ingress-nginx/values.yaml @@ -49,6 +49,8 @@ controller: addHeaders: {} # -- Optionally customize the pod dnsConfig. dnsConfig: {} + # -- Optionally customize the pod hostAliases. + hostAliases: {} # -- Optionally customize the pod hostname. hostname: {} # -- Optionally change this to ClusterFirstWithHostNet in case you have 'hostNetwork: true'. From 3baa591bb5720c8009b1f575e83b913533d7bc98 Mon Sep 17 00:00:00 2001 From: Ehsan Saei <71217171+esigo@users.noreply.github.com> Date: Wed, 2 Aug 2023 12:34:49 +0200 Subject: [PATCH 21/47] promote distroless otel init image (#10257) --- charts/ingress-nginx/README.md | 2 +- charts/ingress-nginx/templates/controller-deployment.yaml | 2 +- charts/ingress-nginx/values.yaml | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/charts/ingress-nginx/README.md b/charts/ingress-nginx/README.md index 6288da3e3..c9ce4e3bc 100644 --- a/charts/ingress-nginx/README.md +++ b/charts/ingress-nginx/README.md @@ -377,7 +377,7 @@ As of version `1.26.0` of this chart, by simply not providing any clusterIP valu | controller.nodeSelector | object | `{"kubernetes.io/os":"linux"}` | Node labels for controller pod assignment # Ref: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/ # | | controller.opentelemetry.containerSecurityContext.allowPrivilegeEscalation | bool | `false` | | | controller.opentelemetry.enabled | bool | `false` | | -| controller.opentelemetry.image | string | `"registry.k8s.io/ingress-nginx/opentelemetry:v20230527@sha256:fd7ec835f31b7b37187238eb4fdad4438806e69f413a203796263131f4f02ed0"` | | +| controller.opentelemetry.image | string | `"registry.k8s.io/ingress-nginx/opentelemetry:v20230721-3e2062ee5@sha256:13bee3f5223883d3ca62fee7309ad02d22ec00ff0d7033e3e9aca7a9f60fd472"` | | | controller.podAnnotations | object | `{}` | Annotations to be added to controller pods # | | controller.podLabels | object | `{}` | Labels to add to the pod container metadata | | controller.podSecurityContext | object | `{}` | Security Context policies for controller pods | diff --git a/charts/ingress-nginx/templates/controller-deployment.yaml b/charts/ingress-nginx/templates/controller-deployment.yaml index 537c3feef..69cb734a0 100644 --- a/charts/ingress-nginx/templates/controller-deployment.yaml +++ b/charts/ingress-nginx/templates/controller-deployment.yaml @@ -193,7 +193,7 @@ spec: {{- end }} {{- if .Values.controller.opentelemetry.enabled}} {{ $otelContainerSecurityContext := $.Values.controller.opentelemetry.containerSecurityContext | default $.Values.controller.containerSecurityContext }} - {{- include "extraModules" (dict "name" "opentelemetry" "image" .Values.controller.opentelemetry.image "containerSecurityContext" $otelContainerSecurityContext "distroless" false) | nindent 8}} + {{- include "extraModules" (dict "name" "opentelemetry" "image" .Values.controller.opentelemetry.image "containerSecurityContext" $otelContainerSecurityContext "distroless" true) | nindent 8}} {{- end}} {{- end }} {{- if .Values.controller.hostNetwork }} diff --git a/charts/ingress-nginx/values.yaml b/charts/ingress-nginx/values.yaml index 8205b3506..3b156a6bf 100644 --- a/charts/ingress-nginx/values.yaml +++ b/charts/ingress-nginx/values.yaml @@ -556,7 +556,7 @@ controller: opentelemetry: enabled: false - image: registry.k8s.io/ingress-nginx/opentelemetry:v20230527@sha256:fd7ec835f31b7b37187238eb4fdad4438806e69f413a203796263131f4f02ed0 + image: registry.k8s.io/ingress-nginx/opentelemetry:v20230721-3e2062ee5@sha256:13bee3f5223883d3ca62fee7309ad02d22ec00ff0d7033e3e9aca7a9f60fd472 containerSecurityContext: allowPrivilegeEscalation: false admissionWebhooks: From d712dd9d92f1f46eab5f55d4643f3a45a7a97f90 Mon Sep 17 00:00:00 2001 From: James Strong Date: Wed, 2 Aug 2023 10:12:42 -0400 Subject: [PATCH 22/47] test kind updates (#10272) Signed-off-by: James Strong --- .github/workflows/ci.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 453775379..5c08ba0da 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -207,7 +207,7 @@ jobs: strategy: matrix: - k8s: [v1.24.12, v1.25.8, v1.26.3,v1.27.1] + k8s: [v1.24.15, v1.25.11, v1.26.6, v1.27.3] steps: - name: Checkout @@ -282,7 +282,7 @@ jobs: strategy: matrix: - k8s: [v1.24.12, v1.25.8, v1.26.3,v1.27.1] + k8s: [v1.24.15, v1.25.11, v1.26.6, v1.27.3] steps: - name: Checkout @@ -330,7 +330,7 @@ jobs: strategy: matrix: - k8s: [v1.27.1] + k8s: [v1.24.15, v1.25.11, v1.26.6, v1.27.3] steps: - name: Checkout @@ -380,7 +380,7 @@ jobs: strategy: matrix: - k8s: [v1.24.12, v1.25.8, v1.26.3,v1.27.1] + k8s: [v1.24.15, v1.25.11, v1.26.6, v1.27.3] steps: @@ -498,7 +498,7 @@ jobs: strategy: matrix: - k8s: [v1.24.12, v1.25.8, v1.26.3,v1.27.1] + k8s: [v1.24.15, v1.25.11, v1.26.6, v1.27.3] steps: - name: Checkout From e8b8778f74b4b01c56398147844370e78f2047c3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 7 Aug 2023 05:52:31 -0700 Subject: [PATCH 23/47] Bump golang.org/x/crypto from 0.11.0 to 0.12.0 (#10280) Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.11.0 to 0.12.0. - [Commits](https://github.com/golang/crypto/compare/v0.11.0...v0.12.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 8 ++++---- go.sum | 16 ++++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/go.mod b/go.mod index 13d0fcf04..1579513bc 100644 --- a/go.mod +++ b/go.mod @@ -25,7 +25,7 @@ require ( github.com/stretchr/testify v1.8.4 github.com/yudai/gojsondiff v1.0.0 github.com/zakjan/cert-chain-resolver v0.0.0-20211122211144-c6b0b792af9a - golang.org/x/crypto v0.11.0 + golang.org/x/crypto v0.12.0 google.golang.org/grpc v1.56.2 google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 gopkg.in/go-playground/pool.v3 v3.1.1 @@ -103,9 +103,9 @@ require ( golang.org/x/mod v0.10.0 // indirect golang.org/x/net v0.10.0 // indirect golang.org/x/oauth2 v0.8.0 // indirect - golang.org/x/sys v0.10.0 // indirect - golang.org/x/term v0.10.0 // indirect - golang.org/x/text v0.11.0 // indirect + golang.org/x/sys v0.11.0 // indirect + golang.org/x/term v0.11.0 // indirect + golang.org/x/text v0.12.0 // indirect golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.9.1 // indirect google.golang.org/appengine v1.6.7 // indirect diff --git a/go.sum b/go.sum index 6e1495776..a6ae8cdcf 100644 --- a/go.sum +++ b/go.sum @@ -390,8 +390,8 @@ golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.11.0 h1:6Ewdq3tDic1mg5xRO4milcWCfMVQhI4NkqWWvqejpuA= -golang.org/x/crypto v0.11.0/go.mod h1:xgJhtzW8F9jGdVFWZESrid1U1bjeNy4zgy5cRr/CIio= +golang.org/x/crypto v0.12.0 h1:tFM/ta59kqch6LlvYnPa0yx5a83cL2nHflFhYKvv9Yk= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -524,19 +524,19 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.10.0 h1:SqMFp9UcQJZa+pmYuAKjd9xq1f0j5rLcDIk0mj4qAsA= -golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0 h1:eG7RXZHdqOJ1i+0lgLgCpSXAp6M3LYlAo6osgSi0xOM= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.10.0 h1:3R7pNqamzBraeqj/Tj8qt1aQ2HpmlC+Cx/qL/7hn4/c= -golang.org/x/term v0.10.0/go.mod h1:lpqdcUyK/oCiQxvxVrppt5ggO2KCZ5QblwqPnfZ6d5o= +golang.org/x/term v0.11.0 h1:F9tnn/DA/Im8nCwm+fX+1/eBwi4qFjRT++MhtVC4ZX0= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.11.0 h1:LAntKIrcmeSKERyiOh0XMV39LXS8IE9UL2yP7+f5ij4= -golang.org/x/text v0.11.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/text v0.12.0 h1:k+n5B8goJNdU7hSvEtMUz3d1Q6D/XW4COJSJR6fN0mc= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= From 5d8185c9d725359de3fd6f2f77bfdd3e8bc44c8d Mon Sep 17 00:00:00 2001 From: Gabor Lekeny Date: Mon, 7 Aug 2023 15:16:32 +0200 Subject: [PATCH 24/47] Handle request_id variable correctly in auth requests (#9219) * Handle $request_id variable correctly in auth requests * Make share_all_vars configurable * Fix test name --- .../nginx-configuration/annotations.md | 4 ++ internal/ingress/annotations/authreq/main.go | 48 +++++++++++++------ .../ingress/annotations/authreq/main_test.go | 29 ++++++----- rootfs/etc/nginx/template/nginx.tmpl | 2 +- test/e2e/annotations/auth.go | 39 +++++++++++++++ 5 files changed, 96 insertions(+), 26 deletions(-) diff --git a/docs/user-guide/nginx-configuration/annotations.md b/docs/user-guide/nginx-configuration/annotations.md index 0916b4df5..877654d12 100755 --- a/docs/user-guide/nginx-configuration/annotations.md +++ b/docs/user-guide/nginx-configuration/annotations.md @@ -33,6 +33,7 @@ You can add these Kubernetes annotations to specific Ingress objects to customiz |[nginx.ingress.kubernetes.io/auth-cache-key](#external-authentication)|string| |[nginx.ingress.kubernetes.io/auth-cache-duration](#external-authentication)|string| |[nginx.ingress.kubernetes.io/auth-keepalive](#external-authentication)|number| +|[nginx.ingress.kubernetes.io/auth-keepalive-share-vars](#external-authentication)|"true" or "false"| |[nginx.ingress.kubernetes.io/auth-keepalive-requests](#external-authentication)|number| |[nginx.ingress.kubernetes.io/auth-keepalive-timeout](#external-authentication)|number| |[nginx.ingress.kubernetes.io/auth-proxy-set-headers](#external-authentication)|string| @@ -467,6 +468,9 @@ Additionally it is possible to set: > Note: does not work with HTTP/2 listener because of a limitation in Lua [subrequests](https://github.com/openresty/lua-nginx-module#spdy-mode-not-fully-supported). > [UseHTTP2](./configmap.md#use-http2) configuration should be disabled! +* `nginx.ingress.kubernetes.io/auth-keepalive-share-vars`: + Whether to share Nginx variables among the current request and the auth request. Example use case is to track requests: when set to "true" X-Request-ID HTTP header will be the same for the backend and the auth request. + Defaults to "false". * `nginx.ingress.kubernetes.io/auth-keepalive-requests`: `` to specify the maximum number of requests that can be served through one keepalive connection. Defaults to `1000` and only applied if `auth-keepalive` is set to higher than `0`. diff --git a/internal/ingress/annotations/authreq/main.go b/internal/ingress/annotations/authreq/main.go index 2ab98ace0..b8ba4f125 100644 --- a/internal/ingress/annotations/authreq/main.go +++ b/internal/ingress/annotations/authreq/main.go @@ -33,20 +33,21 @@ import ( ) const ( - authReqURLAnnotation = "auth-url" - authReqMethodAnnotation = "auth-method" - authReqSigninAnnotation = "auth-signin" - authReqSigninRedirParamAnnotation = "auth-signin-redirect-param" - authReqSnippetAnnotation = "auth-snippet" - authReqCacheKeyAnnotation = "auth-cache-key" - authReqKeepaliveAnnotation = "auth-keepalive" - authReqKeepaliveRequestsAnnotation = "auth-keepalive-requests" - authReqKeepaliveTimeout = "auth-keepalive-timeout" - authReqCacheDuration = "auth-cache-duration" - authReqResponseHeadersAnnotation = "auth-response-headers" - authReqProxySetHeadersAnnotation = "auth-proxy-set-headers" - authReqRequestRedirectAnnotation = "auth-request-redirect" - authReqAlwaysSetCookieAnnotation = "auth-always-set-cookie" + authReqURLAnnotation = "auth-url" + authReqMethodAnnotation = "auth-method" + authReqSigninAnnotation = "auth-signin" + authReqSigninRedirParamAnnotation = "auth-signin-redirect-param" + authReqSnippetAnnotation = "auth-snippet" + authReqCacheKeyAnnotation = "auth-cache-key" + authReqKeepaliveAnnotation = "auth-keepalive" + authReqKeepaliveShareVarsAnnotation = "auth-keepalive-share-vars" + authReqKeepaliveRequestsAnnotation = "auth-keepalive-requests" + authReqKeepaliveTimeout = "auth-keepalive-timeout" + authReqCacheDuration = "auth-cache-duration" + authReqResponseHeadersAnnotation = "auth-response-headers" + authReqProxySetHeadersAnnotation = "auth-proxy-set-headers" + authReqRequestRedirectAnnotation = "auth-request-redirect" + authReqAlwaysSetCookieAnnotation = "auth-always-set-cookie" // This should be exported as it is imported by other packages AuthSecretAnnotation = "auth-secret" @@ -97,6 +98,12 @@ var authReqAnnotations = parser.Annotation{ Risk: parser.AnnotationRiskLow, Documentation: `This annotation specifies the maximum number of keepalive connections to auth-url. Only takes effect when no variables are used in the host part of the URL`, }, + authReqKeepaliveShareVarsAnnotation: { + Validator: parser.ValidateBool, + Scope: parser.AnnotationScopeLocation, + Risk: parser.AnnotationRiskLow, + Documentation: `This annotation specifies whether to share Nginx variables among the current request and the auth request`, + }, authReqKeepaliveRequestsAnnotation: { Validator: parser.ValidateInt, Scope: parser.AnnotationScopeLocation, @@ -158,6 +165,7 @@ type Config struct { AuthCacheKey string `json:"authCacheKey"` AuthCacheDuration []string `json:"authCacheDuration"` KeepaliveConnections int `json:"keepaliveConnections"` + KeepaliveShareVars bool `json:"keepaliveShareVars"` KeepaliveRequests int `json:"keepaliveRequests"` KeepaliveTimeout int `json:"keepaliveTimeout"` ProxySetHeaders map[string]string `json:"proxySetHeaders,omitempty"` @@ -170,6 +178,7 @@ const DefaultCacheDuration = "200 202 401 5m" // fallback values when no keepalive parameters are set const ( defaultKeepaliveConnections = 0 + defaultKeepaliveShareVars = false defaultKeepaliveRequests = 1000 defaultKeepaliveTimeout = 60 ) @@ -218,6 +227,10 @@ func (e1 *Config) Equal(e2 *Config) bool { return false } + if e1.KeepaliveShareVars != e2.KeepaliveShareVars { + return false + } + if e1.KeepaliveRequests != e2.KeepaliveRequests { return false } @@ -357,6 +370,12 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { } } + keepaliveShareVars, err := parser.GetBoolAnnotation(authReqKeepaliveShareVarsAnnotation, ing, a.annotationConfig.Annotations) + if err != nil { + klog.V(3).InfoS("auth-keepalive-share-vars annotation is undefined and will be set to its default value") + keepaliveShareVars = defaultKeepaliveShareVars + } + keepaliveRequests, err := parser.GetIntAnnotation(authReqKeepaliveRequestsAnnotation, ing, a.annotationConfig.Annotations) if err != nil { klog.V(3).InfoS("auth-keepalive-requests annotation is undefined or invalid and will be set to its default value") @@ -467,6 +486,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { AuthCacheKey: authCacheKey, AuthCacheDuration: authCacheDuration, KeepaliveConnections: keepaliveConnections, + KeepaliveShareVars: keepaliveShareVars, KeepaliveRequests: keepaliveRequests, KeepaliveTimeout: keepaliveTimeout, ProxySetHeaders: proxySetHeaders, diff --git a/internal/ingress/annotations/authreq/main_test.go b/internal/ingress/annotations/authreq/main_test.go index 833bebe78..dc5188c8a 100644 --- a/internal/ingress/annotations/authreq/main_test.go +++ b/internal/ingress/annotations/authreq/main_test.go @@ -268,28 +268,31 @@ func TestKeepaliveAnnotations(t *testing.T) { title string url string keepaliveConnections string + keepaliveShareVars string keepaliveRequests string keepaliveTimeout string expectedConnections int + expectedShareVars bool expectedRequests int expectedTimeout int }{ - {"all set", "http://goog.url", "5", "500", "50", 5, 500, 50}, - {"no annotation", "http://goog.url", "", "", "", defaultKeepaliveConnections, defaultKeepaliveRequests, defaultKeepaliveTimeout}, - {"default for connections", "http://goog.url", "x", "500", "50", defaultKeepaliveConnections, 500, 50}, - {"default for requests", "http://goog.url", "5", "x", "50", 5, defaultKeepaliveRequests, 50}, - {"default for invalid timeout", "http://goog.url", "5", "500", "x", 5, 500, defaultKeepaliveTimeout}, - {"variable in host", "http://$host:5000/a/b", "5", "", "", 0, defaultKeepaliveRequests, defaultKeepaliveTimeout}, - {"variable in path", "http://goog.url:5000/$path", "5", "", "", 5, defaultKeepaliveRequests, defaultKeepaliveTimeout}, - {"negative connections", "http://goog.url", "-2", "", "", 0, defaultKeepaliveRequests, defaultKeepaliveTimeout}, - {"negative requests", "http://goog.url", "5", "-1", "", 0, -1, defaultKeepaliveTimeout}, - {"negative timeout", "http://goog.url", "5", "", "-1", 0, defaultKeepaliveRequests, -1}, - {"negative request and timeout", "http://goog.url", "5", "-2", "-3", 0, -2, -3}, + {"all set", "http://goog.url", "5", "false", "500", "50", 5, false, 500, 50}, + {"no annotation", "http://goog.url", "", "", "", "", defaultKeepaliveConnections, defaultKeepaliveShareVars, defaultKeepaliveRequests, defaultKeepaliveTimeout}, + {"default for connections", "http://goog.url", "x", "true", "500", "50", defaultKeepaliveConnections, true, 500, 50}, + {"default for requests", "http://goog.url", "5", "x", "dummy", "50", 5, defaultKeepaliveShareVars, defaultKeepaliveRequests, 50}, + {"default for invalid timeout", "http://goog.url", "5", "t", "500", "x", 5, true, 500, defaultKeepaliveTimeout}, + {"variable in host", "http://$host:5000/a/b", "5", "1", "", "", 0, true, defaultKeepaliveRequests, defaultKeepaliveTimeout}, + {"variable in path", "http://goog.url:5000/$path", "5", "t", "", "", 5, true, defaultKeepaliveRequests, defaultKeepaliveTimeout}, + {"negative connections", "http://goog.url", "-2", "f", "", "", 0, false, defaultKeepaliveRequests, defaultKeepaliveTimeout}, + {"negative requests", "http://goog.url", "5", "True", "-1", "", 0, true, -1, defaultKeepaliveTimeout}, + {"negative timeout", "http://goog.url", "5", "0", "", "-1", 0, false, defaultKeepaliveRequests, -1}, + {"negative request and timeout", "http://goog.url", "5", "False", "-2", "-3", 0, false, -2, -3}, } for _, test := range tests { data[parser.GetAnnotationWithPrefix("auth-url")] = test.url data[parser.GetAnnotationWithPrefix("auth-keepalive")] = test.keepaliveConnections + data[parser.GetAnnotationWithPrefix("auth-keepalive-share-vars")] = test.keepaliveShareVars data[parser.GetAnnotationWithPrefix("auth-keepalive-timeout")] = test.keepaliveTimeout data[parser.GetAnnotationWithPrefix("auth-keepalive-requests")] = test.keepaliveRequests @@ -313,6 +316,10 @@ func TestKeepaliveAnnotations(t *testing.T) { t.Errorf("%v: expected \"%v\" but \"%v\" was returned", test.title, test.expectedConnections, u.KeepaliveConnections) } + if u.KeepaliveShareVars != test.expectedShareVars { + t.Errorf("%v: expected \"%v\" but \"%v\" was returned", test.title, test.expectedShareVars, u.KeepaliveShareVars) + } + if u.KeepaliveRequests != test.expectedRequests { t.Errorf("%v: expected \"%v\" but \"%v\" was returned", test.title, test.expectedRequests, u.KeepaliveRequests) } diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 02b5309cd..0f44efc3d 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -1334,7 +1334,7 @@ stream { # `auth_request` module does not support HTTP keepalives in upstream block: # https://trac.nginx.org/nginx/ticket/1579 access_by_lua_block { - local res = ngx.location.capture('{{ $authPath }}', { method = ngx.HTTP_GET, body = '' }) + local res = ngx.location.capture('{{ $authPath }}', { method = ngx.HTTP_GET, body = '', share_all_vars = {{ $externalAuth.KeepaliveShareVars }} }) if res.status == ngx.HTTP_OK then ngx.var.auth_cookie = res.header['Set-Cookie'] {{- range $line := buildAuthUpstreamLuaHeaders $externalAuth.ResponseHeaders }} diff --git a/test/e2e/annotations/auth.go b/test/e2e/annotations/auth.go index 8011186a1..56246828a 100644 --- a/test/e2e/annotations/auth.go +++ b/test/e2e/annotations/auth.go @@ -628,6 +628,45 @@ http { strings.Contains(server, `keepalive_timeout 789s;`) }) }) + + ginkgo.It(`should disable set_all_vars when auth-keepalive-share-vars is not set`, func() { + f.UpdateNginxConfigMapData("use-http2", "false") + defer func() { + f.UpdateNginxConfigMapData("use-http2", "true") + }() + // Sleep a while just to guarantee that the configmap is applied + framework.Sleep() + + annotations["nginx.ingress.kubernetes.io/auth-keepalive"] = "10" + f.UpdateIngress(ing) + + f.WaitForNginxServer("", + func(server string) bool { + return strings.Contains(server, `upstream auth-external-auth`) && + strings.Contains(server, `keepalive 10;`) && + strings.Contains(server, `share_all_vars = false`) + }) + }) + + ginkgo.It(`should enable set_all_vars when auth-keepalive-share-vars is true`, func() { + f.UpdateNginxConfigMapData("use-http2", "false") + defer func() { + f.UpdateNginxConfigMapData("use-http2", "true") + }() + // Sleep a while just to guarantee that the configmap is applied + framework.Sleep() + + annotations["nginx.ingress.kubernetes.io/auth-keepalive"] = "10" + annotations["nginx.ingress.kubernetes.io/auth-keepalive-share-vars"] = "true" + f.UpdateIngress(ing) + + f.WaitForNginxServer("", + func(server string) bool { + return strings.Contains(server, `upstream auth-external-auth`) && + strings.Contains(server, `keepalive 10;`) && + strings.Contains(server, `share_all_vars = true`) + }) + }) }) ginkgo.Context("when external authentication is configured with a custom redirect param", func() { From 42610df2a31a3be9bad9c73b76ed76764edc95fd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 11 Aug 2023 07:05:28 -0700 Subject: [PATCH 25/47] Bump google.golang.org/grpc from 1.56.2 to 1.57.0 (#10258) Bumps [google.golang.org/grpc](https://github.com/grpc/grpc-go) from 1.56.2 to 1.57.0. - [Release notes](https://github.com/grpc/grpc-go/releases) - [Commits](https://github.com/grpc/grpc-go/compare/v1.56.2...v1.57.0) --- updated-dependencies: - dependency-name: google.golang.org/grpc dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 1579513bc..0ba9fa71b 100644 --- a/go.mod +++ b/go.mod @@ -26,7 +26,7 @@ require ( github.com/yudai/gojsondiff v1.0.0 github.com/zakjan/cert-chain-resolver v0.0.0-20211122211144-c6b0b792af9a golang.org/x/crypto v0.12.0 - google.golang.org/grpc v1.56.2 + google.golang.org/grpc v1.57.0 google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 gopkg.in/go-playground/pool.v3 v3.1.1 gopkg.in/mcuadros/go-syslog.v2 v2.3.0 @@ -109,7 +109,7 @@ require ( golang.org/x/time v0.3.0 // indirect golang.org/x/tools v0.9.1 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 // indirect google.golang.org/protobuf v1.30.0 // indirect gopkg.in/go-playground/assert.v1 v1.2.1 // indirect gopkg.in/inf.v0 v0.9.1 // indirect diff --git a/go.sum b/go.sum index a6ae8cdcf..5ecec5625 100644 --- a/go.sum +++ b/go.sum @@ -647,8 +647,8 @@ google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6D google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= google.golang.org/genproto v0.0.0-20201019141844-1ed22bb0c154/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1 h1:KpwkzHKEF7B9Zxg18WzOa7djJ+Ha5DzthMyZYQfEn2A= -google.golang.org/genproto v0.0.0-20230410155749-daa745c078e1/go.mod h1:nKE/iIaLqn2bQwXBg8f1g2Ylh6r5MN5CmZvuzZCgsCU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19 h1:0nDDozoAU19Qb2HwhXadU8OcsiO/09cnTqhUtq2MEOM= +google.golang.org/genproto/googleapis/rpc v0.0.0-20230525234030-28d5490b6b19/go.mod h1:66JfowdXAEgad5O9NnYcsNPLCPZJD++2L9X0PCMODrA= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= @@ -661,8 +661,8 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= -google.golang.org/grpc v1.56.2 h1:fVRFRnXvU+x6C4IlHZewvJOVHoOv1TUuQyoRsYnB4bI= -google.golang.org/grpc v1.56.2/go.mod h1:I9bI3vqKfayGqPUAwGdOSu7kt6oIJLixfffKrpXqQ9s= +google.golang.org/grpc v1.57.0 h1:kfzNeI/klCGD2YPMUlaGNT3pxvYfga7smW3Vth8Zsiw= +google.golang.org/grpc v1.57.0/go.mod h1:Sd+9RMTACXwmub0zcNY2c4arhtrbBYD1AUHI/dt16Mo= google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 h1:pPsdyuBif+uoyUoL19yuj/TCfUPsmpJHJZhWQ98JGLU= google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7/go.mod h1:8pQa1yxxkh+EsxUK8/455D5MSbv3vgmEJqKCH3y17mI= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= From 411edd717ba96cfc8f7584596bcb6b2b68e24310 Mon Sep 17 00:00:00 2001 From: Altif Date: Fri, 11 Aug 2023 19:37:27 +0530 Subject: [PATCH 26/47] Updated index.md - Fix typos (#10256) --- docs/examples/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/examples/index.md b/docs/examples/index.md index 3af4266ff..59745e014 100644 --- a/docs/examples/index.md +++ b/docs/examples/index.md @@ -23,7 +23,7 @@ Customization | [External authentication with response header propagation](custo Customization | [Sysctl tuning](customization/sysctl/README.md) | TODO | TODO Features | [Rewrite](rewrite/README.md) | TODO | TODO Features | [Session stickiness](affinity/cookie/README.md) | route requests consistently to the same endpoint | Advanced -Features | [Canary Deployments](canary/README.md) | weigthed canary routing to a seperate deployment | Intermediate +Features | [Canary Deployments](canary/README.md) | weighted canary routing to a seperate deployment | Intermediate Scaling | [Static IP](static-ip/README.md) | a single ingress gets a single static IP | Intermediate TLS | [Multi TLS certificate termination](multi-tls/README.md) | TODO | TODO TLS | [TLS termination](tls-termination/README.md) | TODO | TODO From e17927ba52e852c3a604f257838ad1c00a2a8e86 Mon Sep 17 00:00:00 2001 From: Kazuki Suda <230185+superbrothers@users.noreply.github.com> Date: Fri, 11 Aug 2023 23:09:27 +0900 Subject: [PATCH 27/47] helm: Use .Release.Namespace as default for ServiceMonitor namespace (#10249) Signed-off-by: Kazuki Suda --- charts/ingress-nginx/templates/controller-servicemonitor.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/charts/ingress-nginx/templates/controller-servicemonitor.yaml b/charts/ingress-nginx/templates/controller-servicemonitor.yaml index 8ab16f0b2..482fe7f3c 100644 --- a/charts/ingress-nginx/templates/controller-servicemonitor.yaml +++ b/charts/ingress-nginx/templates/controller-servicemonitor.yaml @@ -5,6 +5,8 @@ metadata: name: {{ include "ingress-nginx.controller.fullname" . }} {{- if .Values.controller.metrics.serviceMonitor.namespace }} namespace: {{ .Values.controller.metrics.serviceMonitor.namespace | quote }} +{{- else }} + namespace: {{ .Release.Namespace }} {{- end }} labels: {{- include "ingress-nginx.labels" . | nindent 4 }} From 868df87bb31478fe239e3cd426eb6c1d4bb3ae04 Mon Sep 17 00:00:00 2001 From: Jintao Zhang Date: Fri, 11 Aug 2023 22:11:27 +0800 Subject: [PATCH 28/47] ci(helm): fix Helm Chart release action 422 error (#10237) Signed-off-by: Jintao Zhang --- .github/workflows/helm.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/helm.yaml b/.github/workflows/helm.yaml index 6303b6a27..e6bd4f101 100644 --- a/.github/workflows/helm.yaml +++ b/.github/workflows/helm.yaml @@ -75,7 +75,7 @@ jobs: - name: Helm Chart Releaser uses: helm/chart-releaser-action@be16258da8010256c6e82849661221415f031968 # v1.5.0 env: - CR_SKIP_EXISTING: "false" + CR_SKIP_EXISTING: true CR_TOKEN: "${{ secrets.GITHUB_TOKEN }}" CR_RELEASE_NAME_TEMPLATE: "helm-chart-{{ .Version }}" with: From d9baff90d7d9fa451331882acb6af3a6c0cde14a Mon Sep 17 00:00:00 2001 From: Jack <56563911+jdockerty@users.noreply.github.com> Date: Fri, 11 Aug 2023 15:13:27 +0100 Subject: [PATCH 29/47] docs: swap explanation to match example (#10220) --- docs/user-guide/exposing-tcp-udp-services.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/exposing-tcp-udp-services.md b/docs/user-guide/exposing-tcp-udp-services.md index 089511ff9..dbc143ff1 100644 --- a/docs/user-guide/exposing-tcp-udp-services.md +++ b/docs/user-guide/exposing-tcp-udp-services.md @@ -3,7 +3,7 @@ While the Kubernetes Ingress resource only officially supports routing external HTTP(s) traffic to services, ingress-nginx can be configured to receive external TCP/UDP traffic from non-HTTP protocols and route them to internal services using TCP/UDP port mappings that are specified within a ConfigMap. To support this, the `--tcp-services-configmap` and `--udp-services-configmap` flags can be used to point to an existing config map where the key is the external port to use and the value indicates the service to expose using the format: -`::[PROXY]:[PROXY]` +`::[PROXY]:[PROXY]` It is also possible to use a number or the name of the port. The two last fields are optional. Adding `PROXY` in either or both of the two last fields we can use [Proxy Protocol](https://www.nginx.com/resources/admin-guide/proxy-protocol) decoding (listen) and/or encoding (proxy_pass) in a TCP service. From dd6145b2d38491be60b2fadad69524163429cdf0 Mon Sep 17 00:00:00 2001 From: logica <84759675+logica0419@users.noreply.github.com> Date: Fri, 11 Aug 2023 23:17:27 +0900 Subject: [PATCH 30/47] Bump k8s.io/component-base from 0.26.4 to 0.27.4 (Replace Topology Aware Hints with Topology Aware Routing) (#10282) * Bump k8s.io/component-base from 0.26.4 to 0.27.4 Bumps [k8s.io/component-base](https://github.com/kubernetes/component-base) from 0.26.4 to 0.27.4. - [Commits](https://github.com/kubernetes/component-base/compare/v0.26.4...v0.27.4) --- updated-dependencies: - dependency-name: k8s.io/component-base dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] * changed annotation to TopologyMode * fixed documents * fixed test * using api constraint for test deployment options --------- Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- charts/ingress-nginx/README.md | 2 +- charts/ingress-nginx/values.yaml | 2 +- docs/user-guide/cli-arguments.md | 2 +- go.mod | 24 ++++----- go.sum | 61 +++++++++++------------ internal/ingress/controller/controller.go | 2 +- pkg/flags/flags.go | 2 +- test/e2e/framework/deployment.go | 6 +-- 8 files changed, 50 insertions(+), 51 deletions(-) diff --git a/charts/ingress-nginx/README.md b/charts/ingress-nginx/README.md index c9ce4e3bc..4deed599b 100644 --- a/charts/ingress-nginx/README.md +++ b/charts/ingress-nginx/README.md @@ -296,7 +296,7 @@ As of version `1.26.0` of this chart, by simply not providing any clusterIP valu | controller.electionID | string | `""` | Election ID to use for status update, by default it uses the controller name combined with a suffix of 'leader' | | controller.enableAnnotationValidations | bool | `false` | | | controller.enableMimalloc | bool | `true` | Enable mimalloc as a drop-in replacement for malloc. # ref: https://github.com/microsoft/mimalloc # | -| controller.enableTopologyAwareRouting | bool | `false` | This configuration enables Topology Aware Routing feature, used together with service annotation service.kubernetes.io/topology-aware-hints="auto" Defaults to false | +| controller.enableTopologyAwareRouting | bool | `false` | This configuration enables Topology Aware Routing feature, used together with service annotation service.kubernetes.io/topology-mode="auto" Defaults to false | | controller.existingPsp | string | `""` | Use an existing PSP instead of creating one | | controller.extraArgs | object | `{}` | Additional command line arguments to pass to Ingress-Nginx Controller E.g. to specify the default SSL certificate you can use | | controller.extraContainers | list | `[]` | Additional containers to be added to the controller pod. See https://github.com/lemonldap-ng-controller/lemonldap-ng-controller as example. | diff --git a/charts/ingress-nginx/values.yaml b/charts/ingress-nginx/values.yaml index 3b156a6bf..4e8ddb4fc 100644 --- a/charts/ingress-nginx/values.yaml +++ b/charts/ingress-nginx/values.yaml @@ -66,7 +66,7 @@ controller: watchIngressWithoutClass: false # -- Process IngressClass per name (additionally as per spec.controller). ingressClassByName: false - # -- This configuration enables Topology Aware Routing feature, used together with service annotation service.kubernetes.io/topology-aware-hints="auto" + # -- This configuration enables Topology Aware Routing feature, used together with service annotation service.kubernetes.io/topology-mode="auto" # Defaults to false enableTopologyAwareRouting: false # -- This configuration defines if Ingress Controller should allow users to set diff --git a/docs/user-guide/cli-arguments.md b/docs/user-guide/cli-arguments.md index be6e1dd50..07a17a271 100644 --- a/docs/user-guide/cli-arguments.md +++ b/docs/user-guide/cli-arguments.md @@ -25,7 +25,7 @@ They are set in the container spec of the `ingress-nginx-controller` Deployment | `--enable-metrics` | Enables the collection of NGINX metrics. (default true) | | `--enable-ssl-chain-completion` | Autocomplete SSL certificate chains with missing intermediate CA certificates. Certificates uploaded to Kubernetes must have the "Authority Information Access" X.509 v3 extension for this to succeed. (default false)| | `--enable-ssl-passthrough` | Enable SSL Passthrough. (default false) | -| `--enable-topology-aware-routing` | Enable topology aware hints feature, needs service object annotation service.kubernetes.io/topology-aware-hints sets to auto. (default false) | +| `--enable-topology-aware-routing` | Enable topology aware routing feature, needs service object annotation service.kubernetes.io/topology-mode sets to auto. (default false) | | `--exclude-socket-metrics` | Set of socket request metrics to exclude which won't be exported nor being calculated. The possible socket request metrics to exclude are documented in the monitoring guide e.g. 'nginx_ingress_controller_request_duration_seconds,nginx_ingress_controller_response_size'| | `--health-check-path` | URL path of the health check endpoint. Configured inside the NGINX status server. All requests received on the port defined by the healthz-port parameter are forwarded internally to this path. (default "/healthz") | | `--health-check-timeout` | Time limit, in seconds, for a probe to health-check-path to succeed. (default 10) | diff --git a/go.mod b/go.mod index 0ba9fa71b..3ed0e77e0 100644 --- a/go.mod +++ b/go.mod @@ -30,14 +30,14 @@ require ( google.golang.org/grpc/examples v0.0.0-20221220003428-4f16fbe410f7 gopkg.in/go-playground/pool.v3 v3.1.1 gopkg.in/mcuadros/go-syslog.v2 v2.3.0 - k8s.io/api v0.26.4 + k8s.io/api v0.27.4 k8s.io/apiextensions-apiserver v0.26.4 - k8s.io/apimachinery v0.26.4 + k8s.io/apimachinery v0.27.4 k8s.io/apiserver v0.26.4 k8s.io/cli-runtime v0.26.4 - k8s.io/client-go v0.26.4 + k8s.io/client-go v0.27.4 k8s.io/code-generator v0.26.4 - k8s.io/component-base v0.26.4 + k8s.io/component-base v0.27.4 k8s.io/klog/v2 v2.100.1 pault.ag/go/sniff v0.0.0-20200207005214-cf7e4d167732 sigs.k8s.io/controller-runtime v0.14.6 @@ -59,9 +59,9 @@ require ( github.com/fullsailor/pkcs7 v0.0.0-20160414161337-2585af45975b // indirect github.com/go-errors/errors v1.0.1 // indirect github.com/go-logr/logr v1.2.4 // indirect - github.com/go-openapi/jsonpointer v0.19.5 // indirect - github.com/go-openapi/jsonreference v0.20.0 // indirect - github.com/go-openapi/swag v0.19.14 // indirect + github.com/go-openapi/jsonpointer v0.19.6 // indirect + github.com/go-openapi/jsonreference v0.20.1 // indirect + github.com/go-openapi/swag v0.22.3 // indirect github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 // indirect github.com/godbus/dbus/v5 v5.0.6 // indirect github.com/gogo/protobuf v1.3.2 // indirect @@ -72,14 +72,14 @@ require ( github.com/google/gnostic v0.5.7-v3refs // indirect github.com/google/go-cmp v0.5.9 // indirect github.com/google/gofuzz v1.1.0 // indirect - github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 // indirect + github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/google/uuid v1.3.0 // indirect github.com/gregjones/httpcache v0.0.0-20180305231024-9cad4c3443a7 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de // indirect - github.com/mailru/easyjson v0.7.6 // indirect + github.com/mailru/easyjson v0.7.7 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect github.com/mmarkdown/mmark v2.0.40+incompatible // indirect @@ -116,9 +116,9 @@ require ( gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/gengo v0.0.0-20220902162205-c0856e24416d // indirect - k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect - k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 // indirect - sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect + k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect + k8s.io/utils v0.0.0-20230209194617-a36077c30491 // indirect + sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect sigs.k8s.io/kustomize/api v0.12.1 // indirect sigs.k8s.io/kustomize/kyaml v0.13.9 // indirect sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect diff --git a/go.sum b/go.sum index 5ecec5625..eb703a707 100644 --- a/go.sum +++ b/go.sum @@ -103,14 +103,12 @@ github.com/go-logr/logr v1.2.0/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbV github.com/go-logr/logr v1.2.4 h1:g01GSCwiDw2xSZfjJ2/T9M+S6pFdcNtFYsp+Y43HYDQ= github.com/go-logr/logr v1.2.4/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= github.com/go-logr/zapr v1.2.3 h1:a9vnzlIBPQBBkeaR9IuMUfmVOrQlkoC4YfPoFkX3T7A= -github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY= -github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg= -github.com/go-openapi/jsonreference v0.20.0 h1:MYlu0sBgChmCfJxxUKZ8g1cPWFOB37YSZqewK7OKeyA= -github.com/go-openapi/jsonreference v0.20.0/go.mod h1:Ag74Ico3lPc+zR+qjn4XBUmXymS4zJbYVCZmcgkasdo= -github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= -github.com/go-openapi/swag v0.19.14 h1:gm3vOOXfiuw5i9p5N9xJvfjvuofpyvLA9Wr6QfK5Fng= -github.com/go-openapi/swag v0.19.14/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ= +github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE= +github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs= +github.com/go-openapi/jsonreference v0.20.1 h1:FBLnyygC4/IZZr893oiomc9XaghoveYTrLC1F86HID8= +github.com/go-openapi/jsonreference v0.20.1/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k= +github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g= +github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= @@ -184,8 +182,8 @@ github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hf github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= -github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38 h1:yAJXTCF9TqKcTiHJAE8dj7HMvPfh66eeA2JYW7eFpSE= -github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= @@ -235,10 +233,8 @@ github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0 github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de h1:9TO3cAIGXtEhnIaL+V+BEER86oLrvS+kWobKpbJuye0= github.com/liggitt/tabwriter v0.0.0-20181228230101-89fcab3d43de/go.mod h1:zAbeS9B/r2mtpb6U+EI2rYA5OAXxsYw6wTamcNW+zcE= -github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= -github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA= -github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= +github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0= +github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= @@ -276,7 +272,6 @@ github.com/ncabatoff/go-seq v0.0.0-20180805175032-b08ef85ed833 h1:t4WWQ9I797y7QU github.com/ncabatoff/go-seq v0.0.0-20180805175032-b08ef85ed833/go.mod h1:0CznHmXSjMEqs5Tezj/w2emQoM41wzYM9KpDKUHPYag= github.com/ncabatoff/process-exporter v0.7.10 h1:+Ere7+3se6QqP54gg7aBRagWcL8bq3u5zNi/GRSWeKQ= github.com/ncabatoff/process-exporter v0.7.10/go.mod h1:DHZRZjqxw9LCOpLlX0DjBuyn6d5plh41Jv6Tmttj7Ek= -github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE= github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU= @@ -331,7 +326,7 @@ github.com/prometheus/procfs v0.10.1/go.mod h1:nwNm2aOCAYw8uTR/9bWRREkZFxAUcWzPH github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= -github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= @@ -347,7 +342,9 @@ github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0 h1:1zr/of2m5FGMsad5YfcqgdqdWrIhu+EBEJRhR1U7z/c= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.1.3/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= @@ -355,6 +352,9 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/urfave/cli v1.17.1-0.20160602030128-01a33823596e/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= @@ -683,7 +683,6 @@ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLks gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= @@ -717,31 +716,31 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/api v0.26.4 h1:qSG2PmtcD23BkYiWfoYAcak870eF/hE7NNYBYavTT94= -k8s.io/api v0.26.4/go.mod h1:WwKEXU3R1rgCZ77AYa7DFksd9/BAIKyOmRlbVxgvjCk= +k8s.io/api v0.27.4 h1:0pCo/AN9hONazBKlNUdhQymmnfLRbSZjd5H5H3f0bSs= +k8s.io/api v0.27.4/go.mod h1:O3smaaX15NfxjzILfiln1D8Z3+gEYpjEpiNA/1EVK1Y= k8s.io/apiextensions-apiserver v0.26.4 h1:9D2RTxYGxrG5uYg6D7QZRcykXvavBvcA59j5kTaedQI= k8s.io/apiextensions-apiserver v0.26.4/go.mod h1:cd4uGFGIgzEqUghWpRsr9KE8j2KNTjY8Ji8pnMMazyw= -k8s.io/apimachinery v0.26.4 h1:rZccKdBLg9vP6J09JD+z8Yr99Ce8gk3Lbi9TCx05Jzs= -k8s.io/apimachinery v0.26.4/go.mod h1:ats7nN1LExKHvJ9TmwootT00Yz05MuYqPXEXaVeOy5I= +k8s.io/apimachinery v0.27.4 h1:CdxflD4AF61yewuid0fLl6bM4a3q04jWel0IlP+aYjs= +k8s.io/apimachinery v0.27.4/go.mod h1:XNfZ6xklnMCOGGFNqXG7bUrQCoR04dh/E7FprV6pb+E= k8s.io/apiserver v0.26.4 h1:3Oq4mnJv0mzVX7BR/Nod+8KjlELf/3Ljvu9ZWDyLUoA= k8s.io/apiserver v0.26.4/go.mod h1:yAY3O1vBM4/0OIGAGeWcdfzQvgdwJ188VirLcuSAVnw= k8s.io/cli-runtime v0.26.4 h1:MgSU871KDzBDX7V9GtuqS6Ai9lhQCHgRzkurnXOWtZ0= k8s.io/cli-runtime v0.26.4/go.mod h1:MjJ2DXMChw2zcG0/agzm17xwKpfVxOfuoCdfY9iOCOE= -k8s.io/client-go v0.26.4 h1:/7P/IbGBuT73A+G97trf44NTPSNqvuBREpOfdLbHvD4= -k8s.io/client-go v0.26.4/go.mod h1:6qOItWm3EwxJdl/8p5t7FWtWUOwyMdA8N9ekbW4idpI= +k8s.io/client-go v0.27.4 h1:vj2YTtSJ6J4KxaC88P4pMPEQECWMY8gqPqsTgUKzvjk= +k8s.io/client-go v0.27.4/go.mod h1:ragcly7lUlN0SRPk5/ZkGnDjPknzb37TICq07WhI6Xc= k8s.io/code-generator v0.26.4 h1:zgDD0qX13p/jtrAoYRRiYeQ5ibnriwmo2cMkMZAtJxc= k8s.io/code-generator v0.26.4/go.mod h1:ryaiIKwfxEJEaywEzx3dhWOydpVctKYbqLajJf0O8dI= -k8s.io/component-base v0.26.4 h1:Bg2xzyXNKL3eAuiTEu3XE198d6z22ENgFgGQv2GGOUk= -k8s.io/component-base v0.26.4/go.mod h1:lTuWL1Xz/a4e80gmIC3YZG2JCO4xNwtKWHJWeJmsq20= +k8s.io/component-base v0.27.4 h1:Wqc0jMKEDGjKXdae8hBXeskRP//vu1m6ypC+gwErj4c= +k8s.io/component-base v0.27.4/go.mod h1:hoiEETnLc0ioLv6WPeDt8vD34DDeB35MfQnxCARq3kY= k8s.io/gengo v0.0.0-20220902162205-c0856e24416d h1:U9tB195lKdzwqicbJvyJeOXV7Klv+wNAWENRnXEGi08= k8s.io/gengo v0.0.0-20220902162205-c0856e24416d/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.100.1 h1:7WCHKK6K8fNhTqfBhISHQ97KrnJNFZMcQvKp7gP/tmg= k8s.io/klog/v2 v2.100.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 h1:+70TFaan3hfJzs+7VK2o+OGxg8HsuBr/5f6tVAjDu6E= -k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280/go.mod h1:+Axhij7bCpeqhklhUTe3xmOn6bWxolyZEeyaFpjGtl4= -k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 h1:KTgPnR10d5zhztWptI952TNtt/4u5h3IzDXkdIMuo2Y= -k8s.io/utils v0.0.0-20221128185143-99ec85e7a448/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= +k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f h1:2kWPakN3i/k81b0gvD5C5FJ2kxm1WrQFanWchyKuqGg= +k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f/go.mod h1:byini6yhqGC14c3ebc/QwanvYwhuMWF6yz2F8uwW8eg= +k8s.io/utils v0.0.0-20230209194617-a36077c30491 h1:r0BAOLElQnnFhE/ApUsg3iHdVYYPBjNSSOMowRZxxsY= +k8s.io/utils v0.0.0-20230209194617-a36077c30491/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0= pault.ag/go/sniff v0.0.0-20200207005214-cf7e4d167732 h1:SAElp8THCfmBdM+4lmWX5gebiSSkEr7PAYDVF91qpfg= pault.ag/go/sniff v0.0.0-20200207005214-cf7e4d167732/go.mod h1:lpvCfhqEHNJSSpG5R5A2EgsVzG8RTt4RfPoQuRAcDmg= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= @@ -749,8 +748,8 @@ rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= sigs.k8s.io/controller-runtime v0.14.6 h1:oxstGVvXGNnMvY7TAESYk+lzr6S3V5VFxQ6d92KcwQA= sigs.k8s.io/controller-runtime v0.14.6/go.mod h1:WqIdsAY6JBsjfc/CqO0CORmNtoCtE4S6qbPc9s68h+0= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 h1:iXTIw73aPyC+oRdyqqvVJuloN1p0AC/kzH07hu3NE+k= -sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo= +sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0= sigs.k8s.io/kustomize/api v0.12.1 h1:7YM7gW3kYBwtKvoY216ZzY+8hM+lV53LUayghNRJ0vM= sigs.k8s.io/kustomize/api v0.12.1/go.mod h1:y3JUhimkZkR6sbLNwfJHxvo1TCLwuwm14sCYnkH6S1s= sigs.k8s.io/kustomize/kyaml v0.13.9 h1:Qz53EAaFFANyNgyOEJbT/yoIHygK40/ZcvU3rgry2Tk= diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index 7dc1a5292..f405bdcbb 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -142,7 +142,7 @@ type Configuration struct { func getIngressPodZone(svc *apiv1.Service) string { svcKey := k8s.MetaNamespaceKey(svc) - if svcZoneAnnotation, ok := svc.ObjectMeta.GetAnnotations()[apiv1.AnnotationTopologyAwareHints]; ok { + if svcZoneAnnotation, ok := svc.ObjectMeta.GetAnnotations()[apiv1.AnnotationTopologyMode]; ok { if strings.ToLower(svcZoneAnnotation) == "auto" { if foundZone, ok := k8s.IngressNodeDetails.GetLabels()[apiv1.LabelTopologyZone]; ok { klog.V(3).Infof("Svc has topology aware annotation enabled, try to use zone %q where controller pod is running for Service %q ", foundZone, svcKey) diff --git a/pkg/flags/flags.go b/pkg/flags/flags.go index 2c926a35f..55d24f690 100644 --- a/pkg/flags/flags.go +++ b/pkg/flags/flags.go @@ -221,7 +221,7 @@ Takes the form ":port". If not provided, no admission controller is starte disableSyncEvents = flags.Bool("disable-sync-events", false, "Disables the creation of 'Sync' event resources") - enableTopologyAwareRouting = flags.Bool("enable-topology-aware-routing", false, "Enable topology aware hints feature, needs service object annotation service.kubernetes.io/topology-aware-hints sets to auto.") + enableTopologyAwareRouting = flags.Bool("enable-topology-aware-routing", false, "Enable topology aware routing feature, needs service object annotation service.kubernetes.io/topology-mode sets to auto.") ) flags.StringVar(&nginx.MaxmindMirror, "maxmind-mirror", "", `Maxmind mirror url (example: http://geoip.local/databases.`) diff --git a/test/e2e/framework/deployment.go b/test/e2e/framework/deployment.go index bcb1d3960..93e1811ec 100644 --- a/test/e2e/framework/deployment.go +++ b/test/e2e/framework/deployment.go @@ -67,11 +67,11 @@ func WithDeploymentNamespace(n string) func(*deploymentOptions) { } } -// WithSvcTopologyAnnotations create svc with topology aware hints sets to auto +// WithSvcTopologyAnnotations create svc with topology mode sets to auto func WithSvcTopologyAnnotations() func(*deploymentOptions) { return func(o *deploymentOptions) { o.svcAnnotations = map[string]string{ - "service.kubernetes.io/topology-aware-hints": "auto", + corev1.AnnotationTopologyMode: "auto", } } } @@ -213,7 +213,7 @@ func (f *Framework) NewHttpbunDeployment(opts ...func(*deploymentOptions)) strin 80, int32(options.replicas), nil, nil, - //Required to get hostname information + // Required to get hostname information []corev1.EnvVar{ { Name: "HTTPBUN_INFO_ENABLED", From 53c2f2742fa49648ade7ed3d150e01d19be91fa5 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 11 Aug 2023 13:11:22 -0700 Subject: [PATCH 31/47] Bump github.com/opencontainers/runc from 1.1.8 to 1.1.9 (#10298) Bumps [github.com/opencontainers/runc](https://github.com/opencontainers/runc) from 1.1.8 to 1.1.9. - [Release notes](https://github.com/opencontainers/runc/releases) - [Changelog](https://github.com/opencontainers/runc/blob/v1.1.9/CHANGELOG.md) - [Commits](https://github.com/opencontainers/runc/compare/v1.1.8...v1.1.9) --- updated-dependencies: - dependency-name: github.com/opencontainers/runc dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 3ed0e77e0..e78ca245e 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/moul/pb v0.0.0-20220425114252-bca18df4138c github.com/ncabatoff/process-exporter v0.7.10 github.com/onsi/ginkgo/v2 v2.9.5 - github.com/opencontainers/runc v1.1.8 + github.com/opencontainers/runc v1.1.9 github.com/pmezard/go-difflib v1.0.0 github.com/prometheus/client_golang v1.16.0 github.com/prometheus/client_model v0.4.0 diff --git a/go.sum b/go.sum index eb703a707..bbfacc71e 100644 --- a/go.sum +++ b/go.sum @@ -284,8 +284,8 @@ github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3Ro github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= -github.com/opencontainers/runc v1.1.8 h1:zICRlc+C1XzivLc3nzE+cbJV4LIi8tib6YG0MqC6OqA= -github.com/opencontainers/runc v1.1.8/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= +github.com/opencontainers/runc v1.1.9 h1:XR0VIHTGce5eWPkaPesqTBrhW2yAcaraWfsEalNwQLM= +github.com/opencontainers/runc v1.1.9/go.mod h1:CbUumNnWCuTGFukNXahoo/RFBZvDAgRh/smNYNOhA50= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417 h1:3snG66yBm59tKhhSPQrQ/0bCrv1LQbKt40LnUPiUxdc= github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= From a92e7b4857b3cd7fb152f1ade5f6c3db462311b2 Mon Sep 17 00:00:00 2001 From: Son Bui Date: Sat, 12 Aug 2023 11:21:19 +0800 Subject: [PATCH 32/47] Remove curl dependencies in e2e tests #9716 (#10296) * fix: Replace curl list backend with dbg command #9716 Signed-off-by: Son Bui * fix: Remove curl dependencies in e2e tests #9716 Signed-off-by: Son Bui --------- Signed-off-by: Son Bui --- test/e2e/annotations/serviceupstream.go | 20 +++++++++---------- test/e2e/endpointslices/topology.go | 5 ++--- .../servicebackend/service_externalname.go | 11 +++------- test/e2e/settings/tls.go | 20 ++++++++++--------- 4 files changed, 25 insertions(+), 31 deletions(-) diff --git a/test/e2e/annotations/serviceupstream.go b/test/e2e/annotations/serviceupstream.go index 94ad6d346..0606a2d61 100644 --- a/test/e2e/annotations/serviceupstream.go +++ b/test/e2e/annotations/serviceupstream.go @@ -25,8 +25,6 @@ import ( "github.com/stretchr/testify/assert" "k8s.io/ingress-nginx/test/e2e/framework" - - "k8s.io/ingress-nginx/internal/nginx" ) var _ = framework.DescribeAnnotation("service-upstream", func() { @@ -59,10 +57,10 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are used") s := f.GetService(f.Namespace, framework.EchoService) - curlCmd := fmt.Sprintf("curl --fail --silent http://localhost:%v/configuration/backends", nginx.StatusPort) - output, err := f.ExecIngressPod(curlCmd) + dbgCmd := "/dbg backends all" + output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`{"address":"%s"`, s.Spec.ClusterIP)) + assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) }) }) @@ -88,10 +86,10 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are used") s := f.GetService(f.Namespace, framework.EchoService) - curlCmd := fmt.Sprintf("curl --fail --silent http://localhost:%v/configuration/backends", nginx.StatusPort) - output, err := f.ExecIngressPod(curlCmd) + dbgCmd := "/dbg backends all" + output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`{"address":"%s"`, s.Spec.ClusterIP)) + assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) }) }) @@ -119,10 +117,10 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are not used") s := f.GetService(f.Namespace, framework.EchoService) - curlCmd := fmt.Sprintf("curl --fail --silent http://localhost:%v/configuration/backends", nginx.StatusPort) - output, err := f.ExecIngressPod(curlCmd) + dbgCmd := "/dbg backends all" + output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.NotContains(ginkgo.GinkgoT(), output, fmt.Sprintf(`{"address":"%s"`, s.Spec.ClusterIP)) + assert.NotContains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) }) }) }) diff --git a/test/e2e/endpointslices/topology.go b/test/e2e/endpointslices/topology.go index ff66f2ad1..2197bcb53 100644 --- a/test/e2e/endpointslices/topology.go +++ b/test/e2e/endpointslices/topology.go @@ -28,7 +28,6 @@ import ( "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/assert" - "k8s.io/ingress-nginx/internal/nginx" "k8s.io/ingress-nginx/test/e2e/framework" ) @@ -72,8 +71,8 @@ var _ = framework.IngressNginxDescribeSerial("[TopologyHints] topology aware rou } } - curlCmd := fmt.Sprintf("curl --fail --silent http://localhost:%v/configuration/backends", nginx.StatusPort) - status, err := f.ExecIngressPod(curlCmd) + dbgCmd := "/dbg backends all" + status, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) var backends []map[string]interface{} err = json.Unmarshal([]byte(status), &backends) diff --git a/test/e2e/servicebackend/service_externalname.go b/test/e2e/servicebackend/service_externalname.go index 89ae77b10..429690ff1 100644 --- a/test/e2e/servicebackend/service_externalname.go +++ b/test/e2e/servicebackend/service_externalname.go @@ -30,7 +30,6 @@ import ( networking "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/ingress-nginx/internal/nginx" "k8s.io/ingress-nginx/test/e2e/framework" ) @@ -330,17 +329,13 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { assert.Contains(ginkgo.GinkgoT(), body, `"X-Forwarded-Host": "echo"`) ginkgo.By("checking the service is updated to use new host") - curlCmd := fmt.Sprintf( - "curl --fail --silent http://localhost:%v/configuration/backends", - nginx.StatusPort, - ) - - output, err := f.ExecIngressPod(curlCmd) + dbgCmd := "/dbg backends all" + output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) assert.Contains( ginkgo.GinkgoT(), output, - fmt.Sprintf("{\"address\":\"%s\"", framework.BuildNIPHost(ip)), + fmt.Sprintf(`"address": "%s"`, framework.BuildNIPHost(ip)), ) }) diff --git a/test/e2e/settings/tls.go b/test/e2e/settings/tls.go index a820e41dd..2cead4a94 100644 --- a/test/e2e/settings/tls.go +++ b/test/e2e/settings/tls.go @@ -170,15 +170,17 @@ var _ = framework.DescribeSetting("[SSL] TLS protocols, ciphers and headers)", f hstsIncludeSubdomains: "false", }) - // we can not use gorequest here because it flattens the duplicate headers - // and specifically in case of Strict-Transport-Security it ignore extra headers - // intead of concatenating, rightfully. And I don't know of any API it provides for getting raw headers. - curlCmd := fmt.Sprintf("curl -I -k --fail --silent --resolve settings-tls:443:127.0.0.1 https://settings-tls%v", "?hsts=true") - output, err := f.ExecIngressPod(curlCmd) - assert.Nil(ginkgo.GinkgoT(), err) - assert.Contains(ginkgo.GinkgoT(), output, "strict-transport-security: max-age=86400; preload") - // this is what the upstream sets - assert.NotContains(ginkgo.GinkgoT(), output, "strict-transport-security: max-age=3600; preload") + expectResponse := f.HTTPTestClientWithTLSConfig(tlsConfig). + GET("/"). + WithURL(f.GetURL(framework.HTTPS)). + WithHeader("Host", host). + WithQuery("hsts", "true"). + Expect() + + expectResponse.Header("Strict-Transport-Security").Equal("max-age=86400; preload") + header := expectResponse.Raw().Header + got := header["Strict-Transport-Security"] + assert.Equal(ginkgo.GinkgoT(), 1, len(got)) }) }) From 6b05e9b06e3a61062a33c6c8338f2e253c881aec Mon Sep 17 00:00:00 2001 From: Lucas Fernando Cardoso Nunes Date: Sun, 13 Aug 2023 12:27:20 -0300 Subject: [PATCH 33/47] fix: add /etc/mime.types #10309 (#10310) Signed-off-by: Lucas Fernando Cardoso Nunes --- images/custom-error-pages/rootfs/Dockerfile | 1 + 1 file changed, 1 insertion(+) diff --git a/images/custom-error-pages/rootfs/Dockerfile b/images/custom-error-pages/rootfs/Dockerfile index 04bcb8e08..4560e9ed5 100755 --- a/images/custom-error-pages/rootfs/Dockerfile +++ b/images/custom-error-pages/rootfs/Dockerfile @@ -32,6 +32,7 @@ FROM gcr.io/distroless/static:nonroot COPY --from=builder /go/src/k8s.io/ingress-nginx/images/custom-error-pages/nginx-errors / COPY --from=builder /go/src/k8s.io/ingress-nginx/images/custom-error-pages/www /www +COPY --from=builder /go/src/k8s.io/ingress-nginx/images/custom-error-pages/etc /etc USER nonroot:nonroot CMD ["/nginx-errors"] From 8a578c9f4a268cba2d75fc40d4e5f4bb3e17a714 Mon Sep 17 00:00:00 2001 From: Mark Ley Date: Mon, 14 Aug 2023 10:35:21 -0700 Subject: [PATCH 34/47] Disable Modsecurity from internal processing which affects large ingresses (#10316) * Disable Modsecurity from interanl processing * Fix modsecurity check logic --- rootfs/etc/nginx/template/nginx.tmpl | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 0f44efc3d..0a031442c 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -709,6 +709,11 @@ http { # default server, used for NGINX healthcheck and access to nginx stats server { + # Ensure that modsecurity will not run on an internal location as this is not accessible from outside + {{ if $all.Cfg.EnableModsecurity }} + modsecurity off; + {{ end }} + listen 127.0.0.1:{{ .StatusPort }}; set $proxy_upstream_name "internal"; From 1a8ba5e2f26c16064888be869ce978bbaaffda32 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 16 Aug 2023 02:44:27 -0700 Subject: [PATCH 35/47] Bump goreleaser/goreleaser-action from 4.3.0 to 4.4.0 (#10314) Bumps [goreleaser/goreleaser-action](https://github.com/goreleaser/goreleaser-action) from 4.3.0 to 4.4.0. - [Release notes](https://github.com/goreleaser/goreleaser-action/releases) - [Commits](https://github.com/goreleaser/goreleaser-action/compare/336e29918d653399e599bfca99fadc1d7ffbc9f7...3fa32b8bb5620a2c1afe798654bbad59f9da4906) --- updated-dependencies: - dependency-name: goreleaser/goreleaser-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/plugin.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/plugin.yaml b/.github/workflows/plugin.yaml index d8769f439..a7ce737ac 100644 --- a/.github/workflows/plugin.yaml +++ b/.github/workflows/plugin.yaml @@ -28,7 +28,7 @@ jobs: check-latest: true - name: Run GoReleaser - uses: goreleaser/goreleaser-action@336e29918d653399e599bfca99fadc1d7ffbc9f7 # v4.3.0 + uses: goreleaser/goreleaser-action@3fa32b8bb5620a2c1afe798654bbad59f9da4906 # v4.4.0 with: version: latest args: release --rm-dist From cee39f68ef1053057f14c88443605a80a180c769 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 21 Aug 2023 06:21:23 -0700 Subject: [PATCH 36/47] Bump securego/gosec from 2.16.0 to 2.17.0 (#10332) Bumps [securego/gosec](https://github.com/securego/gosec) from 2.16.0 to 2.17.0. - [Release notes](https://github.com/securego/gosec/releases) - [Changelog](https://github.com/securego/gosec/blob/master/.goreleaser.yml) - [Commits](https://github.com/securego/gosec/compare/c5ea1b7bdd9efc3792e513258853552b0ae31e06...a89e9d5a7acb4457f3891ac18532b142b1bf9221) --- updated-dependencies: - dependency-name: securego/gosec dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 5c08ba0da..54ad661cc 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -71,7 +71,7 @@ jobs: uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 - name: Run Gosec Security Scanner - uses: securego/gosec@c5ea1b7bdd9efc3792e513258853552b0ae31e06 # v2.16.0 + uses: securego/gosec@a89e9d5a7acb4457f3891ac18532b142b1bf9221 # v2.17.0 with: # G601 for zz_generated.deepcopy.go # G306 TODO: Expect WriteFile permissions to be 0600 or less From ac3ff59ea42a8c7defd84f5b5bf0e2c6e71ac133 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 23 Aug 2023 15:26:00 -0700 Subject: [PATCH 37/47] Bump actions/setup-go from 4.0.1 to 4.1.0 (#10313) Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4.0.1 to 4.1.0. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/fac708d6674e30b6ba41289acaab6d4b75aa0753...93397bea11091df50f3d7e59dc26a7711a8bcfbe) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 12 ++++++------ .github/workflows/plugin.yaml | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 54ad661cc..09de92680 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -89,7 +89,7 @@ jobs: - name: Set up Go id: go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true @@ -108,7 +108,7 @@ jobs: - name: Set up Go id: go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true @@ -127,7 +127,7 @@ jobs: - name: Set up Go id: go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true @@ -148,7 +148,7 @@ jobs: - name: Set up Go id: go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true @@ -214,7 +214,7 @@ jobs: uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 - name: Setup Go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true @@ -521,7 +521,7 @@ jobs: - name: Set up Go id: go if: ${{ steps.filter-images.outputs.kube-webhook-certgen == 'true' }} - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: '1.20' check-latest: true diff --git a/.github/workflows/plugin.yaml b/.github/workflows/plugin.yaml index a7ce737ac..40fed1d9b 100644 --- a/.github/workflows/plugin.yaml +++ b/.github/workflows/plugin.yaml @@ -22,7 +22,7 @@ jobs: fetch-depth: 0 - name: Set up Go - uses: actions/setup-go@fac708d6674e30b6ba41289acaab6d4b75aa0753 # v4.0.1 + uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: go-version: 1.20 check-latest: true From 40e0849b16f1e9c07d8f5a1554ef2a7f79c9224a Mon Sep 17 00:00:00 2001 From: Ciprian Hacman Date: Fri, 25 Aug 2023 07:33:19 +0300 Subject: [PATCH 38/47] Use gzip instead of pigz in CI (#10348) Signed-off-by: Ciprian Hacman --- .github/workflows/ci.yaml | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 09de92680..796e81844 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -167,8 +167,6 @@ jobs: - name: Prepare Host run: | - sudo apt-get -qq update || true - sudo apt-get install -y pigz curl -LO https://dl.k8s.io/release/v1.25.5/bin/linux/amd64/kubectl chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin/kubectl @@ -188,7 +186,7 @@ jobs: nginx-ingress-controller:e2e \ ingress-controller/controller:1.0.0-dev \ ingress-controller/controller-chroot:1.0.0-dev \ - | pigz > docker.tar.gz + | gzip > docker.tar.gz - name: cache uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2 @@ -260,7 +258,7 @@ jobs: - name: Load images from cache run: | echo "loading docker images..." - pigz -dc docker.tar.gz | docker load + gzip -dc docker.tar.gz | docker load - name: Test env: @@ -301,7 +299,7 @@ jobs: - name: Load images from cache run: | echo "loading docker images..." - pigz -dc docker.tar.gz | docker load + gzip -dc docker.tar.gz | docker load - name: Run e2e tests env: @@ -349,7 +347,7 @@ jobs: - name: Load images from cache run: | echo "loading docker images..." - pigz -dc docker.tar.gz | docker load + gzip -dc docker.tar.gz | docker load - name: Run e2e tests env: @@ -400,7 +398,7 @@ jobs: - name: Load images from cache run: | echo "loading docker images..." - pigz -dc docker.tar.gz | docker load + gzip -dc docker.tar.gz | docker load - name: Run e2e tests env: From 8d0b00dd263b32f179460ab881095c3e95efbcbc Mon Sep 17 00:00:00 2001 From: Son Bui Date: Fri, 25 Aug 2023 21:00:53 +0800 Subject: [PATCH 39/47] fix: update action file to auto release plugin #10197 (#10321) Signed-off-by: Son Bui --- .github/workflows/plugin.yaml | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/.github/workflows/plugin.yaml b/.github/workflows/plugin.yaml index 40fed1d9b..1eeb1d102 100644 --- a/.github/workflows/plugin.yaml +++ b/.github/workflows/plugin.yaml @@ -4,10 +4,8 @@ on: push: branches: - "main" - paths: - - "cmd/plugin/**" tags: - - "v*" + - 'v*.*.*\+plugin' permissions: contents: write # for goreleaser/goreleaser-action @@ -24,14 +22,14 @@ jobs: - name: Set up Go uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 with: - go-version: 1.20 + go-version: '1.20' check-latest: true - name: Run GoReleaser uses: goreleaser/goreleaser-action@3fa32b8bb5620a2c1afe798654bbad59f9da4906 # v4.4.0 with: version: latest - args: release --rm-dist + args: release --clean env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 9487907fa1ba3451d2f4440b550f9cfffe11fd65 Mon Sep 17 00:00:00 2001 From: Marcelo Cyreno <812725+marcelocyreno@users.noreply.github.com> Date: Sat, 26 Aug 2023 00:25:21 -0300 Subject: [PATCH 40/47] =?UTF-8?q?Fix=20=E2=80=9Cdev-env=E2=80=9D=20Makefil?= =?UTF-8?q?e=20target=20to=20work=20with=20kubectl=201.28+=20(#10350)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- build/dev-env.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/dev-env.sh b/build/dev-env.sh index 3d21b7e15..d79238b7d 100755 --- a/build/dev-env.sh +++ b/build/dev-env.sh @@ -52,7 +52,7 @@ if [[ ${HELM_VERSION} -lt 3.10.0 ]]; then exit 1 fi -KUBE_CLIENT_VERSION=$(kubectl version --client --short 2>/dev/null | grep Client | awk '{print $3}' | cut -d. -f2) || true +KUBE_CLIENT_VERSION=$(kubectl version --client -oyaml 2>/dev/null | grep "minor:" | awk '{print $2}' | tr -d '"') || true if [[ ${KUBE_CLIENT_VERSION} -lt 24 ]]; then echo "Please update kubectl to 1.24.2 or higher" exit 1 From 300a60f7244cb056701177989a1a09135626f930 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 26 Aug 2023 16:59:22 -0700 Subject: [PATCH 41/47] Bump actions/dependency-review-action from 3.0.6 to 3.0.8 (#10333) Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 3.0.6 to 3.0.8. - [Release notes](https://github.com/actions/dependency-review-action/releases) - [Commits](https://github.com/actions/dependency-review-action/compare/1360a344ccb0ab6e9475edef90ad2f46bf8003b1...f6fff72a3217f580d5afd49a46826795305b63c7) --- updated-dependencies: - dependency-name: actions/dependency-review-action dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/depreview.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/depreview.yaml b/.github/workflows/depreview.yaml index 625c2f461..45d796088 100644 --- a/.github/workflows/depreview.yaml +++ b/.github/workflows/depreview.yaml @@ -11,4 +11,4 @@ jobs: - name: 'Checkout Repository' uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 - name: 'Dependency Review' - uses: actions/dependency-review-action@1360a344ccb0ab6e9475edef90ad2f46bf8003b1 # v3.0.6 + uses: actions/dependency-review-action@f6fff72a3217f580d5afd49a46826795305b63c7 # v3.0.8 From 1ce25127bd39179bfaba6f0b7ef5b40ec2dc4bbb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 28 Aug 2023 04:55:43 -0700 Subject: [PATCH 42/47] Bump actions/checkout from 3.5.3 to 3.6.0 (#10354) Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.3 to 3.6.0. - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/c85c95e3d7251135ab7dc9ce3241c5835cc595a9...f43a0e5ff2bd294095638e18286ca9a3d1956744) --- updated-dependencies: - dependency-name: actions/checkout dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 24 +++++++++++----------- .github/workflows/depreview.yaml | 2 +- .github/workflows/docs.yaml | 4 ++-- .github/workflows/helm.yaml | 4 ++-- .github/workflows/perftest.yaml | 2 +- .github/workflows/plugin.yaml | 2 +- .github/workflows/scorecards.yml | 2 +- .github/workflows/vulnerability-scans.yaml | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 796e81844..596ef0427 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -42,7 +42,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - uses: dorny/paths-filter@4512585405083f25c027a35db413c2b3b9006d50 # v2.11.1 id: filter @@ -68,7 +68,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Run Gosec Security Scanner uses: securego/gosec@a89e9d5a7acb4457f3891ac18532b142b1bf9221 # v2.17.0 @@ -85,7 +85,7 @@ jobs: (needs.changes.outputs.go == 'true') steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Set up Go id: go @@ -104,7 +104,7 @@ jobs: (needs.changes.outputs.go == 'true') steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Set up Go id: go @@ -123,7 +123,7 @@ jobs: (needs.changes.outputs.go == 'true') steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Set up Go id: go @@ -144,7 +144,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Set up Go id: go @@ -209,7 +209,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Setup Go uses: actions/setup-go@93397bea11091df50f3d7e59dc26a7711a8bcfbe # v4.1.0 @@ -284,7 +284,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: cache uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 @@ -332,7 +332,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: cache uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 @@ -383,7 +383,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: cache uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 @@ -427,7 +427,7 @@ jobs: PLATFORMS: linux/amd64,linux/arm64 steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - uses: dorny/paths-filter@4512585405083f25c027a35db413c2b3b9006d50 # v2.11.1 id: filter-images @@ -500,7 +500,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - uses: dorny/paths-filter@4512585405083f25c027a35db413c2b3b9006d50 # v2.11.1 id: filter-images diff --git a/.github/workflows/depreview.yaml b/.github/workflows/depreview.yaml index 45d796088..f93869c79 100644 --- a/.github/workflows/depreview.yaml +++ b/.github/workflows/depreview.yaml @@ -9,6 +9,6 @@ jobs: runs-on: ubuntu-latest steps: - name: 'Checkout Repository' - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: 'Dependency Review' uses: actions/dependency-review-action@f6fff72a3217f580d5afd49a46826795305b63c7 # v3.0.8 diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index f7aee6610..d4b81e62a 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -23,7 +23,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - uses: dorny/paths-filter@4512585405083f25c027a35db413c2b3b9006d50 # v2.11.1 id: filter @@ -47,7 +47,7 @@ jobs: steps: - name: Checkout master - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Deploy uses: ./.github/actions/mkdocs diff --git a/.github/workflows/helm.yaml b/.github/workflows/helm.yaml index e6bd4f101..5b0f98f1b 100644 --- a/.github/workflows/helm.yaml +++ b/.github/workflows/helm.yaml @@ -23,7 +23,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Run Artifact Hub lint run: | @@ -61,7 +61,7 @@ jobs: steps: - name: Checkout master - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 with: # Fetch entire history. Required for chart-releaser; see https://github.com/helm/chart-releaser-action/issues/13#issuecomment-602063896 fetch-depth: 0 diff --git a/.github/workflows/perftest.yaml b/.github/workflows/perftest.yaml index 36f1f1ede..154ab6e47 100644 --- a/.github/workflows/perftest.yaml +++ b/.github/workflows/perftest.yaml @@ -19,7 +19,7 @@ jobs: steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - name: Install K6 run: | diff --git a/.github/workflows/plugin.yaml b/.github/workflows/plugin.yaml index 1eeb1d102..16974e906 100644 --- a/.github/workflows/plugin.yaml +++ b/.github/workflows/plugin.yaml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 with: fetch-depth: 0 diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml index 2e276a3f6..d06fa1528 100644 --- a/.github/workflows/scorecards.yml +++ b/.github/workflows/scorecards.yml @@ -27,7 +27,7 @@ jobs: steps: - name: "Checkout code" - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 with: persist-credentials: false diff --git a/.github/workflows/vulnerability-scans.yaml b/.github/workflows/vulnerability-scans.yaml index af7d8bda1..1acc6c163 100644 --- a/.github/workflows/vulnerability-scans.yaml +++ b/.github/workflows/vulnerability-scans.yaml @@ -22,7 +22,7 @@ jobs: versions: ${{ steps.version.outputs.TAGS }} steps: - name: Checkout code - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 with: fetch-depth: 0 @@ -52,7 +52,7 @@ jobs: versions: ${{ fromJSON(needs.version.outputs.versions) }} steps: - name: Checkout code - uses: actions/checkout@c85c95e3d7251135ab7dc9ce3241c5835cc595a9 # v3.5.3 + uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d1956744 # v3.6.0 - shell: bash id: test From 93f9ac2521519404a442fa2660b79c1ba672adea Mon Sep 17 00:00:00 2001 From: Marcelo Cyreno <812725+marcelocyreno@users.noreply.github.com> Date: Mon, 28 Aug 2023 11:37:44 -0300 Subject: [PATCH 43/47] Making auth access logs optional (#10335) --- internal/ingress/controller/config/config.go | 5 +++++ rootfs/etc/nginx/template/nginx.tmpl | 2 ++ 2 files changed, 7 insertions(+) diff --git a/internal/ingress/controller/config/config.go b/internal/ingress/controller/config/config.go index 6e78964ed..60cef489a 100644 --- a/internal/ingress/controller/config/config.go +++ b/internal/ingress/controller/config/config.go @@ -131,6 +131,10 @@ type Configuration struct { // By default this is disabled EnableAccessLogForDefaultBackend bool `json:"enable-access-log-for-default-backend"` + // EnableAuthAccessLog enable auth access log + // By default this is disabled + EnableAuthAccessLog bool `json:"enable-auth-access-log"` + // AccessLogPath sets the path of the access logs for both http and stream contexts if enabled // http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log // http://nginx.org/en/docs/stream/ngx_stream_log_module.html#access_log @@ -871,6 +875,7 @@ func NewDefault() Configuration { AccessLogPath: "/var/log/nginx/access.log", AccessLogParams: "", EnableAccessLogForDefaultBackend: false, + EnableAuthAccessLog: false, WorkerCPUAffinity: "", ErrorLogPath: "/var/log/nginx/error.log", BlockCIDRs: defBlockEntity, diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 0a031442c..3d7235bcc 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -1102,7 +1102,9 @@ stream { opentelemetry_propagate; {{ end }} + {{ if not $all.Cfg.EnableAuthAccessLog }} access_log off; + {{ end }} # Ensure that modsecurity will not run on an internal location as this is not accessible from outside {{ if $all.Cfg.EnableModsecurity }} From 616d7e97d006cb0d054706dd0db5639497abee54 Mon Sep 17 00:00:00 2001 From: Rudolf Byker Date: Tue, 29 Aug 2023 09:17:22 +0200 Subject: [PATCH 44/47] Add firewall configuration to quick start documentation (#10357) --- docs/deploy/index.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/deploy/index.md b/docs/deploy/index.md index d719d4a57..df11d710c 100644 --- a/docs/deploy/index.md +++ b/docs/deploy/index.md @@ -80,6 +80,12 @@ kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/cont Because of api deprecations, the default manifest may not work on your cluster. Specific manifests for supported Kubernetes versions are available within a sub-folder of each provider. +### Firewall configuration + +To check which ports are used by your installation of ingress-nginx, look at the output of `kubectl -n ingress-nginx get pod -o yaml`. In general, you need: +- Port 8443 open between all hosts on which the kubernetes nodes are running. This is used for the ingress-nginx [admission controller](https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/). +- Port 80 (for HTTP) and/or 443 (for HTTPS) open to the public on the kubernetes nodes to which the DNS of your apps are pointing. + ### Pre-flight check A few pods should start in the `ingress-nginx` namespace: From 46d87d3462014d7e188bff0082f0c4de044d9bc0 Mon Sep 17 00:00:00 2001 From: Son Bui Date: Thu, 31 Aug 2023 10:06:47 +0800 Subject: [PATCH 45/47] chore(build): Fix Run make dev-env syntax error (#10294) * fix: Run make dev-env syntax error #10293 Signed-off-by: Son Bui * fix: Run make dev-env value too great for base #10294 --------- Signed-off-by: Son Bui --- build/dev-env.sh | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/build/dev-env.sh b/build/dev-env.sh index d79238b7d..93ed3de40 100755 --- a/build/dev-env.sh +++ b/build/dev-env.sh @@ -45,9 +45,11 @@ if ! command -v helm &> /dev/null; then exit 1 fi +function ver { printf "%d%03d%03d" $(echo "$1" | tr '.' ' '); } + HELM_VERSION=$(helm version 2>&1 | cut -f1 -d"," | grep -oE '[0-9]+\.[0-9]+\.[0-9]+') || true echo $HELM_VERSION -if [[ ${HELM_VERSION} -lt 3.10.0 ]]; then +if [[ $(ver $HELM_VERSION) -lt $(ver "3.10.0") ]]; then echo "Please upgrade helm to v3.10.0 or higher" exit 1 fi From b3060bfbd09825993081f60b56df8201f1246702 Mon Sep 17 00:00:00 2001 From: Chen Chen Date: Thu, 31 Aug 2023 15:36:48 +0800 Subject: [PATCH 46/47] Fix golangci-lint errors (#10196) * Fix golangci-lint errors Signed-off-by: z1cheng * Fix dupl errors Signed-off-by: z1cheng * Fix comments Signed-off-by: z1cheng * Fix errcheck lint errors Signed-off-by: z1cheng * Fix assert in e2e test Signed-off-by: z1cheng * Not interrupt the waitForPodsReady Signed-off-by: z1cheng * Replace string with constant Signed-off-by: z1cheng * Fix comments Signed-off-by: z1cheng * Revert write file permision Signed-off-by: z1cheng --------- Signed-off-by: z1cheng --- cmd/dataplane/main.go | 5 +- cmd/dbg/main.go | 40 ++- cmd/nginx/logger.go | 1 - cmd/nginx/main.go | 5 +- cmd/nginx/main_test.go | 10 +- cmd/plugin/commands/backends/backends.go | 9 +- cmd/plugin/commands/certs/certs.go | 2 +- cmd/plugin/commands/conf/conf.go | 2 +- cmd/plugin/commands/exec/exec.go | 2 +- cmd/plugin/commands/general/general.go | 2 +- cmd/plugin/commands/ingresses/ingresses.go | 15 +- .../commands/ingresses/ingresses_test.go | 1 - cmd/plugin/commands/lint/main.go | 10 +- cmd/plugin/commands/logs/logs.go | 2 +- cmd/plugin/commands/ssh/ssh.go | 2 +- cmd/plugin/kubectl/kubectl.go | 18 +- cmd/plugin/lints/deployment.go | 20 +- cmd/plugin/lints/ingress.go | 21 +- cmd/plugin/main.go | 2 +- cmd/plugin/request/request.go | 49 ++- cmd/plugin/util/util.go | 22 +- docs/e2e-tests.md | 2 +- images/fastcgi-helloserver/rootfs/main.go | 4 +- images/go-grpc-greeter-server/rootfs/main.go | 4 +- internal/admission/controller/main.go | 13 +- internal/admission/controller/main_test.go | 4 +- internal/admission/controller/server.go | 4 +- internal/ingress/annotations/alias/main.go | 2 +- .../ingress/annotations/alias/main_test.go | 4 +- internal/ingress/annotations/annotations.go | 61 ++-- .../ingress/annotations/annotations_test.go | 8 +- internal/ingress/annotations/auth/main.go | 24 +- .../ingress/annotations/auth/main_test.go | 62 ++-- internal/ingress/annotations/authreq/main.go | 36 +- .../ingress/annotations/authreq/main_test.go | 5 +- .../ingress/annotations/authreqglobal/main.go | 1 - .../annotations/authreqglobal/main_test.go | 5 +- internal/ingress/annotations/authtls/main.go | 19 +- .../ingress/annotations/authtls/main_test.go | 33 +- .../annotations/backendprotocol/main.go | 4 +- .../annotations/backendprotocol/main_test.go | 7 +- internal/ingress/annotations/canary/main.go | 12 +- .../ingress/annotations/canary/main_test.go | 11 +- .../annotations/clientbodybuffersize/main.go | 6 +- .../clientbodybuffersize/main_test.go | 1 + .../ingress/annotations/connection/main.go | 6 +- .../annotations/connection/main_test.go | 1 - internal/ingress/annotations/cors/main.go | 16 +- .../annotations/customhttperrors/main.go | 14 +- .../annotations/defaultbackend/main.go | 14 +- internal/ingress/annotations/fastcgi/main.go | 15 +- .../ingress/annotations/fastcgi/main_test.go | 5 - .../annotations/globalratelimit/main.go | 19 +- .../annotations/globalratelimit/main_test.go | 21 +- .../annotations/http2pushpreload/main.go | 4 +- .../ingress/annotations/ipallowlist/main.go | 5 +- .../ingress/annotations/ipdenylist/main.go | 5 +- .../annotations/loadbalancing/main_test.go | 1 + internal/ingress/annotations/log/main.go | 4 +- internal/ingress/annotations/log/main_test.go | 15 +- internal/ingress/annotations/mirror/main.go | 6 +- .../ingress/annotations/modsecurity/main.go | 14 +- .../annotations/modsecurity/main_test.go | 10 +- .../ingress/annotations/opentelemetry/main.go | 7 +- .../annotations/opentelemetry/main_test.go | 25 +- .../ingress/annotations/opentracing/main.go | 14 +- .../annotations/opentracing/main_test.go | 29 +- internal/ingress/annotations/parser/main.go | 13 +- .../ingress/annotations/parser/main_test.go | 12 +- .../ingress/annotations/parser/validators.go | 8 +- .../annotations/parser/validators_test.go | 1 - internal/ingress/annotations/proxy/main.go | 23 +- .../ingress/annotations/proxy/main_test.go | 32 +- internal/ingress/annotations/proxyssl/main.go | 32 +- .../ingress/annotations/proxyssl/main_test.go | 62 ++-- .../ingress/annotations/ratelimit/main.go | 2 +- .../ingress/annotations/redirect/redirect.go | 12 +- .../annotations/redirect/redirect_test.go | 1 - internal/ingress/annotations/rewrite/main.go | 4 +- .../ingress/annotations/rewrite/main_test.go | 36 +- internal/ingress/annotations/satisfy/main.go | 4 +- .../annotations/serversnippet/main_test.go | 1 + .../annotations/serviceupstream/main.go | 4 +- .../annotations/serviceupstream/main_test.go | 25 +- .../annotations/sessionaffinity/main.go | 31 +- .../annotations/sessionaffinity/main_test.go | 6 +- .../ingress/annotations/snippet/main_test.go | 1 + .../ingress/annotations/sslcipher/main.go | 12 +- .../annotations/sslcipher/main_test.go | 7 +- .../annotations/sslpassthrough/main.go | 3 +- .../annotations/streamsnippet/main_test.go | 4 +- .../annotations/upstreamhashby/main.go | 2 +- .../annotations/xforwardedprefix/main.go | 14 +- .../annotations/xforwardedprefix/main_test.go | 1 + internal/ingress/controller/certificate.go | 2 +- internal/ingress/controller/checker.go | 2 +- internal/ingress/controller/checker_test.go | 13 +- internal/ingress/controller/config/config.go | 84 +++-- internal/ingress/controller/controller.go | 76 ++--- .../ingress/controller/controller_test.go | 69 ++-- internal/ingress/controller/endpointslices.go | 6 +- .../ingress/controller/endpointslices_test.go | 1 + .../controller/ingressclass/ingressclass.go | 6 +- internal/ingress/controller/nginx.go | 65 ++-- internal/ingress/controller/nginx_test.go | 23 +- internal/ingress/controller/process/nginx.go | 5 +- internal/ingress/controller/status.go | 10 +- .../ingress/controller/store/backend_ssl.go | 9 +- .../ingress/controller/store/endpointslice.go | 2 +- .../controller/store/endpointslice_test.go | 1 - internal/ingress/controller/store/store.go | 113 +++++-- .../ingress/controller/store/store_test.go | 178 ++++++---- .../ingress/controller/template/configmap.go | 38 ++- .../ingress/controller/template/template.go | 309 +++++++++--------- .../controller/template/template_test.go | 94 +++--- internal/ingress/controller/util.go | 2 + internal/ingress/defaults/main.go | 2 +- internal/ingress/errors/errors.go | 32 +- internal/ingress/inspector/ingress_test.go | 1 - internal/ingress/inspector/inspector.go | 4 +- internal/ingress/inspector/rules.go | 6 +- internal/ingress/inspector/rules_test.go | 1 - internal/ingress/inspector/service.go | 2 +- .../ingress/metric/collectors/admission.go | 6 +- .../ingress/metric/collectors/controller.go | 66 ++-- .../metric/collectors/controller_test.go | 20 +- .../ingress/metric/collectors/nginx_status.go | 1 - .../metric/collectors/nginx_status_test.go | 2 +- internal/ingress/metric/collectors/process.go | 23 +- .../ingress/metric/collectors/process_test.go | 9 +- internal/ingress/metric/collectors/socket.go | 73 ++--- .../ingress/metric/collectors/socket_test.go | 7 +- .../ingress/metric/collectors/testutils.go | 6 +- internal/ingress/metric/dummy.go | 40 +-- internal/ingress/metric/main.go | 14 +- internal/ingress/status/status.go | 34 +- internal/ingress/status/status_test.go | 287 ++++++++-------- internal/k8s/main.go | 7 +- internal/k8s/main_test.go | 20 +- internal/net/dns/dns.go | 2 +- internal/net/ipnet_test.go | 8 +- internal/net/net.go | 16 +- internal/net/net_test.go | 2 +- internal/net/ssl/ssl.go | 53 +-- internal/net/ssl/ssl_test.go | 37 +-- internal/nginx/main.go | 17 +- internal/nginx/maxmind.go | 10 +- internal/task/queue.go | 11 +- pkg/apis/ingress/sslcert.go | 6 +- pkg/apis/ingress/types.go | 7 +- pkg/apis/ingress/types_equals.go | 62 ++-- pkg/apis/ingress/types_equals_test.go | 25 +- pkg/flags/flags.go | 10 +- pkg/flags/flags_test.go | 7 +- pkg/metrics/handler.go | 3 +- pkg/tcpproxy/tcp.go | 12 +- pkg/util/file/file_watcher.go | 6 +- pkg/util/file/filesystem.go | 2 +- pkg/util/file/structure.go | 10 +- pkg/util/ingress/ingress.go | 28 +- pkg/util/process/controller.go | 4 +- pkg/util/process/sigterm.go | 2 +- pkg/util/process/sigterm_test.go | 4 +- pkg/util/runtime/cpu_notlinux.go | 2 +- pkg/util/sets/match_test.go | 27 +- rootfs/etc/nginx/template/nginx.tmpl | 6 +- test/e2e/admission/admission.go | 17 +- test/e2e/annotations/affinity.go | 86 ++--- test/e2e/annotations/affinitymode.go | 8 +- test/e2e/annotations/alias.go | 12 +- test/e2e/annotations/auth.go | 84 ++--- test/e2e/annotations/authtls.go | 22 +- test/e2e/annotations/backendprotocol.go | 12 +- test/e2e/annotations/canary.go | 53 ++- test/e2e/annotations/clientbodybuffersize.go | 14 +- test/e2e/annotations/cors.go | 57 ++-- test/e2e/annotations/customhttperrors.go | 2 +- test/e2e/annotations/default_backend.go | 6 +- test/e2e/annotations/fromtowwwredirect.go | 4 +- test/e2e/annotations/globalratelimit.go | 2 +- test/e2e/annotations/grpc.go | 34 +- .../annotations/modsecurity/modsecurity.go | 65 ++-- test/e2e/annotations/proxy.go | 9 +- test/e2e/annotations/proxyssl.go | 15 +- test/e2e/annotations/rewrite.go | 16 +- test/e2e/annotations/serversnippet.go | 1 - test/e2e/annotations/serviceupstream.go | 11 +- test/e2e/annotations/upstreamhashby.go | 7 +- test/e2e/dbg/main.go | 4 +- test/e2e/e2e.go | 1 - test/e2e/e2e_test.go | 1 + test/e2e/endpointslices/longname.go | 1 - test/e2e/endpointslices/topology.go | 3 +- test/e2e/framework/deployment.go | 15 +- test/e2e/framework/exec.go | 12 +- test/e2e/framework/fastcgi_helloserver.go | 3 +- test/e2e/framework/framework.go | 41 +-- test/e2e/framework/grpc_fortune_teller.go | 3 +- test/e2e/framework/healthz.go | 2 +- test/e2e/framework/httpexpect/match.go | 2 +- test/e2e/framework/httpexpect/object.go | 17 +- test/e2e/framework/httpexpect/request.go | 3 +- test/e2e/framework/k8s.go | 55 ++-- test/e2e/framework/metrics.go | 3 +- test/e2e/framework/ssl.go | 10 +- test/e2e/framework/test_context.go | 3 +- test/e2e/framework/util.go | 40 ++- test/e2e/gracefulshutdown/grace_period.go | 2 - test/e2e/ingress/pathtype_exact.go | 3 +- test/e2e/ingress/pathtype_mixed.go | 3 +- test/e2e/leaks/lua_ssl.go | 4 +- test/e2e/loadbalance/configmap.go | 4 +- test/e2e/loadbalance/ewma.go | 9 +- test/e2e/loadbalance/round_robin.go | 6 +- test/e2e/lua/dynamic_certificates.go | 2 - test/e2e/lua/dynamic_configuration.go | 19 +- test/e2e/nginx/nginx.go | 5 - test/e2e/security/request_smuggling.go | 8 +- test/e2e/servicebackend/service_backend.go | 91 +++--- .../servicebackend/service_externalname.go | 22 +- .../e2e/servicebackend/service_nil_backend.go | 1 - test/e2e/settings/access_log.go | 4 - test/e2e/settings/badannotationvalues.go | 2 - test/e2e/settings/default_ssl_certificate.go | 6 +- test/e2e/settings/disable_catch_all.go | 8 +- .../settings/disable_service_external_name.go | 1 - test/e2e/settings/disable_sync_events.go | 3 +- test/e2e/settings/forwarded_headers.go | 6 +- test/e2e/settings/geoip2.go | 9 +- test/e2e/settings/global_external_auth.go | 22 +- test/e2e/settings/global_options.go | 1 - test/e2e/settings/hash-size.go | 9 - test/e2e/settings/ingress_class.go | 24 +- test/e2e/settings/keep-alive.go | 14 +- test/e2e/settings/listen_nondefault_ports.go | 5 - test/e2e/settings/log-format.go | 2 - test/e2e/settings/namespace_selector.go | 16 +- test/e2e/settings/no_auth_locations.go | 8 +- .../e2e/settings/no_tls_redirect_locations.go | 1 - test/e2e/settings/ocsp/ocsp.go | 5 +- test/e2e/settings/opentelemetry.go | 15 +- test/e2e/settings/opentracing.go | 60 ++-- .../settings/pod_security_policy_volumes.go | 1 - test/e2e/settings/proxy_connect_timeout.go | 2 +- test/e2e/settings/proxy_protocol.go | 19 +- test/e2e/settings/proxy_read_timeout.go | 2 +- test/e2e/settings/proxy_send_timeout.go | 2 +- test/e2e/settings/ssl_passthrough.go | 11 +- test/e2e/settings/tls.go | 5 +- test/e2e/settings/validations/validations.go | 6 +- test/e2e/ssl/secret_update.go | 2 +- test/e2e/status/update.go | 4 +- test/e2e/tcpudp/tcp.go | 12 +- 253 files changed, 2434 insertions(+), 2113 deletions(-) diff --git a/cmd/dataplane/main.go b/cmd/dataplane/main.go index a1c4cbcc6..65f898df6 100644 --- a/cmd/dataplane/main.go +++ b/cmd/dataplane/main.go @@ -18,11 +18,12 @@ package main import ( "fmt" - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/client_golang/prometheus/collectors" "net/http" "os" + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/collectors" + "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/controller" diff --git a/cmd/dbg/main.go b/cmd/dbg/main.go index 41a3c2772..b63bcf5fe 100644 --- a/cmd/dbg/main.go +++ b/cmd/dbg/main.go @@ -114,7 +114,6 @@ func main() { fmt.Println(err) os.Exit(1) } - } func backendsAll() { @@ -155,10 +154,16 @@ func backendsList() { fmt.Println(unmarshalErr) return } - backends := f.([]interface{}) + backends, ok := f.([]interface{}) + if !ok { + fmt.Printf("unexpected type: %T", f) + } for _, backendi := range backends { - backend := backendi.(map[string]interface{}) + backend, ok := backendi.(map[string]interface{}) + if !ok { + fmt.Printf("unexpected type: %T", backendi) + } fmt.Println(backend["name"].(string)) } } @@ -180,12 +185,22 @@ func backendsGet(name string) { fmt.Println(unmarshalErr) return } - backends := f.([]interface{}) + backends, ok := f.([]interface{}) + if !ok { + fmt.Printf("unexpected type: %T", f) + } for _, backendi := range backends { - backend := backendi.(map[string]interface{}) + backend, ok := backendi.(map[string]interface{}) + if !ok { + fmt.Printf("unexpected type: %T", backendi) + } if backend["name"].(string) == name { - printed, _ := json.MarshalIndent(backend, "", " ") + printed, err := json.MarshalIndent(backend, "", " ") + if err != nil { + fmt.Println(err) + return + } fmt.Println(string(printed)) return } @@ -213,18 +228,7 @@ func certGet(host string) { } func general() { - //TODO: refactor to obtain ingress-nginx pod count from the api server - /* - statusCode, body, requestErr := nginx.NewGetStatusRequest(generalPath) - if requestErr != nil { - fmt.Println(requestErr) - return - } - if statusCode != 200 { - fmt.Printf("Nginx returned code %v\n", statusCode) - return - } - */ + // TODO: refactor to obtain ingress-nginx pod count from the api server var prettyBuffer bytes.Buffer indentErr := json.Indent(&prettyBuffer, []byte("{}"), "", " ") diff --git a/cmd/nginx/logger.go b/cmd/nginx/logger.go index 13ec095fa..323085c83 100644 --- a/cmd/nginx/logger.go +++ b/cmd/nginx/logger.go @@ -47,5 +47,4 @@ func logger(address string) { server.Wait() klog.Infof("Stopping logger") - } diff --git a/cmd/nginx/main.go b/cmd/nginx/main.go index 508e940e1..1d30091ef 100644 --- a/cmd/nginx/main.go +++ b/cmd/nginx/main.go @@ -153,7 +153,6 @@ func main() { if errExists == nil { conf.IsChroot = true go logger(conf.InternalLoggerAddress) - } go metrics.StartHTTPServer(conf.HealthCheckHost, conf.ListenPorts.Health, mux) @@ -282,10 +281,10 @@ func checkService(key string, kubeClient *kubernetes.Clientset) error { } if errors.IsNotFound(err) { - return fmt.Errorf("No service with name %v found in namespace %v: %v", name, ns, err) + return fmt.Errorf("no service with name %v found in namespace %v: %v", name, ns, err) } - return fmt.Errorf("Unexpected error searching service with name %v in namespace %v: %v", name, ns, err) + return fmt.Errorf("unexpected error searching service with name %v in namespace %v: %v", name, ns, err) } return nil diff --git a/cmd/nginx/main_test.go b/cmd/nginx/main_test.go index f57c02c5e..13f1e9eec 100644 --- a/cmd/nginx/main_test.go +++ b/cmd/nginx/main_test.go @@ -47,7 +47,7 @@ func TestCreateApiserverClient(t *testing.T) { func init() { // the default value of nginx.TemplatePath assumes the template exists in // the root filesystem and not in the rootfs directory - path, err := filepath.Abs(filepath.Join("../../rootfs/", nginx.TemplatePath)) + path, err := filepath.Abs(filepath.Join("..", "..", "rootfs", nginx.TemplatePath)) if err == nil { nginx.TemplatePath = path } @@ -87,14 +87,14 @@ func TestHandleSigterm(t *testing.T) { ingressflags.ResetForTesting(func() { t.Fatal("bad parse") }) - os.Setenv("POD_NAME", podName) - os.Setenv("POD_NAMESPACE", namespace) + t.Setenv("POD_NAME", podName) + t.Setenv("POD_NAMESPACE", namespace) oldArgs := os.Args defer func() { - os.Setenv("POD_NAME", "") - os.Setenv("POD_NAMESPACE", "") + t.Setenv("POD_NAME", "") + t.Setenv("POD_NAMESPACE", "") os.Args = oldArgs }() diff --git a/cmd/plugin/commands/backends/backends.go b/cmd/plugin/commands/backends/backends.go index afc98e4d6..ff44fd9c2 100644 --- a/cmd/plugin/commands/backends/backends.go +++ b/cmd/plugin/commands/backends/backends.go @@ -63,13 +63,14 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command { return cmd } -func backends(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, backend string, onlyList bool) error { +func backends(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container, backend string, onlyList bool) error { var command []string - if onlyList { + switch { + case onlyList: command = []string{"/dbg", "backends", "list"} - } else if backend != "" { + case backend != "": command = []string{"/dbg", "backends", "get", backend} - } else { + default: command = []string{"/dbg", "backends", "all"} } diff --git a/cmd/plugin/commands/certs/certs.go b/cmd/plugin/commands/certs/certs.go index 1f08b5216..ee27cf1b1 100644 --- a/cmd/plugin/commands/certs/certs.go +++ b/cmd/plugin/commands/certs/certs.go @@ -59,7 +59,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command { return cmd } -func certs(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, host string) error { +func certs(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container, host string) error { command := []string{"/dbg", "certs", "get", host} pod, err := request.ChoosePod(flags, podName, deployment, selector) diff --git a/cmd/plugin/commands/conf/conf.go b/cmd/plugin/commands/conf/conf.go index a7f03a062..090fb40bb 100644 --- a/cmd/plugin/commands/conf/conf.go +++ b/cmd/plugin/commands/conf/conf.go @@ -55,7 +55,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command { return cmd } -func conf(flags *genericclioptions.ConfigFlags, host string, podName string, deployment string, selector string, container string) error { +func conf(flags *genericclioptions.ConfigFlags, host, podName, deployment, selector, container string) error { pod, err := request.ChoosePod(flags, podName, deployment, selector) if err != nil { return err diff --git a/cmd/plugin/commands/exec/exec.go b/cmd/plugin/commands/exec/exec.go index f06aaeb23..8e853c534 100644 --- a/cmd/plugin/commands/exec/exec.go +++ b/cmd/plugin/commands/exec/exec.go @@ -55,7 +55,7 @@ type execFlags struct { Stdin bool } -func exec(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, cmd []string, opts execFlags) error { +func exec(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string, cmd []string, opts execFlags) error { pod, err := request.ChoosePod(flags, podName, deployment, selector) if err != nil { return err diff --git a/cmd/plugin/commands/general/general.go b/cmd/plugin/commands/general/general.go index fa6c1301f..cea403562 100644 --- a/cmd/plugin/commands/general/general.go +++ b/cmd/plugin/commands/general/general.go @@ -47,7 +47,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command { return cmd } -func general(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string) error { +func general(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string) error { pod, err := request.ChoosePod(flags, podName, deployment, selector) if err != nil { return err diff --git a/cmd/plugin/commands/ingresses/ingresses.go b/cmd/plugin/commands/ingresses/ingresses.go index dff967103..8a25418db 100644 --- a/cmd/plugin/commands/ingresses/ingresses.go +++ b/cmd/plugin/commands/ingresses/ingresses.go @@ -74,9 +74,9 @@ func ingresses(flags *genericclioptions.ConfigFlags, host string, allNamespaces if host != "" { rowsWithHost := make([]ingressRow, 0) - for _, row := range rows { - if row.Host == host { - rowsWithHost = append(rowsWithHost, row) + for i := range rows { + if rows[i].Host == host { + rowsWithHost = append(rowsWithHost, rows[i]) } } rows = rowsWithHost @@ -91,7 +91,8 @@ func ingresses(flags *genericclioptions.ConfigFlags, host string, allNamespaces fmt.Fprintln(printer, "INGRESS NAME\tHOST+PATH\tADDRESSES\tTLS\tSERVICE\tSERVICE PORT\tENDPOINTS") } - for _, row := range rows { + for i := range rows { + row := &rows[i] var tlsMsg string if row.TLS { tlsMsg = "YES" @@ -134,8 +135,8 @@ type ingressRow struct { func getIngressRows(ingresses *[]networking.Ingress) []ingressRow { rows := make([]ingressRow, 0) - for _, ing := range *ingresses { - + for i := range *ingresses { + ing := &(*ingresses)[i] address := "" for _, lbIng := range ing.Status.LoadBalancer.Ingress { if len(lbIng.IP) > 0 { @@ -182,7 +183,7 @@ func getIngressRows(ingresses *[]networking.Ingress) []ingressRow { for _, rule := range ing.Spec.Rules { _, hasTLS := tlsHosts[rule.Host] - //Handle ingress with no paths + // Handle ingress with no paths if rule.HTTP == nil { row := ingressRow{ Namespace: ing.Namespace, diff --git a/cmd/plugin/commands/ingresses/ingresses_test.go b/cmd/plugin/commands/ingresses/ingresses_test.go index 6a8d8837f..7a90efe46 100644 --- a/cmd/plugin/commands/ingresses/ingresses_test.go +++ b/cmd/plugin/commands/ingresses/ingresses_test.go @@ -24,7 +24,6 @@ import ( ) func TestGetIngressInformation(t *testing.T) { - testcases := map[string]struct { ServiceBackend *networking.IngressServiceBackend wantName string diff --git a/cmd/plugin/commands/lint/main.go b/cmd/plugin/commands/lint/main.go index 2daf8eb87..847fe86c9 100644 --- a/cmd/plugin/commands/lint/main.go +++ b/cmd/plugin/commands/lint/main.go @@ -111,11 +111,13 @@ type lintOptions struct { } func (opts *lintOptions) Validate() error { + //nolint:dogsled // Ignore 3 blank identifiers _, _, _, err := util.ParseVersionString(opts.versionFrom) if err != nil { return err } + //nolint:dogsled // Ignore 3 blank identifiers _, _, _, err = util.ParseVersionString(opts.versionTo) if err != nil { return err @@ -131,9 +133,9 @@ type lint interface { Version() string } -func checkObjectArray(lints []lint, objects []kmeta.Object, opts lintOptions) { +func checkObjectArray(allLints []lint, objects []kmeta.Object, opts lintOptions) { usedLints := make([]lint, 0) - for _, lint := range lints { + for _, lint := range allLints { lintVersion := lint.Version() if lint.Version() == "" { lintVersion = "0.0.0" @@ -189,7 +191,7 @@ func ingresses(opts lintOptions) error { return err } - var iLints []lints.IngressLint = lints.GetIngressLints() + iLints := lints.GetIngressLints() genericLints := make([]lint, len(iLints)) for i := range iLints { genericLints[i] = iLints[i] @@ -216,7 +218,7 @@ func deployments(opts lintOptions) error { return err } - var iLints []lints.DeploymentLint = lints.GetDeploymentLints() + iLints := lints.GetDeploymentLints() genericLints := make([]lint, len(iLints)) for i := range iLints { genericLints[i] = iLints[i] diff --git a/cmd/plugin/commands/logs/logs.go b/cmd/plugin/commands/logs/logs.go index 56f4fc640..22068d469 100644 --- a/cmd/plugin/commands/logs/logs.go +++ b/cmd/plugin/commands/logs/logs.go @@ -95,7 +95,7 @@ func (o *logsFlags) toStrings() []string { return r } -func logs(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, opts logsFlags) error { +func logs(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string, opts logsFlags) error { pod, err := request.ChoosePod(flags, podName, deployment, selector) if err != nil { return err diff --git a/cmd/plugin/commands/ssh/ssh.go b/cmd/plugin/commands/ssh/ssh.go index fe1b3e9fe..a4762d781 100644 --- a/cmd/plugin/commands/ssh/ssh.go +++ b/cmd/plugin/commands/ssh/ssh.go @@ -45,7 +45,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command { return cmd } -func ssh(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string) error { +func ssh(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string) error { pod, err := request.ChoosePod(flags, podName, deployment, selector) if err != nil { return err diff --git a/cmd/plugin/kubectl/kubectl.go b/cmd/plugin/kubectl/kubectl.go index 1171e9218..cb33243fc 100644 --- a/cmd/plugin/kubectl/kubectl.go +++ b/cmd/plugin/kubectl/kubectl.go @@ -38,11 +38,11 @@ func PodExecString(flags *genericclioptions.ConfigFlags, pod *apiv1.Pod, contain // ExecToString runs a kubectl subcommand and returns stdout as a string func ExecToString(flags *genericclioptions.ConfigFlags, args []string) (string, error) { - kArgs := getKubectlConfigFlags(flags) - kArgs = append(kArgs, args...) + kubectlArgs := getKubectlConfigFlags(flags) + kubectlArgs = append(kubectlArgs, args...) buf := bytes.NewBuffer(make([]byte, 0)) - err := execToWriter(append([]string{"kubectl"}, kArgs...), buf) + err := execToWriter(append([]string{"kubectl"}, kubectlArgs...), buf) if err != nil { return "", err } @@ -51,9 +51,9 @@ func ExecToString(flags *genericclioptions.ConfigFlags, args []string) (string, // Exec replaces the current process with a kubectl invocation func Exec(flags *genericclioptions.ConfigFlags, args []string) error { - kArgs := getKubectlConfigFlags(flags) - kArgs = append(kArgs, args...) - return execCommand(append([]string{"kubectl"}, kArgs...)) + kubectlArgs := getKubectlConfigFlags(flags) + kubectlArgs = append(kubectlArgs, args...) + return execCommand(append([]string{"kubectl"}, kubectlArgs...)) } // Replaces the currently running process with the given command @@ -70,6 +70,7 @@ func execCommand(args []string) error { // Runs a command and returns stdout func execToWriter(args []string, writer io.Writer) error { + //nolint:gosec // Ignore G204 error cmd := exec.Command(args[0], args[1:]...) op, err := cmd.StdoutPipe() @@ -78,7 +79,7 @@ func execToWriter(args []string, writer io.Writer) error { } go func() { - io.Copy(writer, op) //nolint:errcheck + io.Copy(writer, op) //nolint:errcheck // Ignore the error }() err = cmd.Run() if err != nil { @@ -106,7 +107,6 @@ func getKubectlConfigFlags(flags *genericclioptions.ConfigFlags) []string { appendStringFlag(o, flags.Password, "password") appendStringFlag(o, flags.ClusterName, "cluster") appendStringFlag(o, flags.AuthInfoName, "user") - //appendStringFlag(o, flags.Namespace, "namespace") appendStringFlag(o, flags.Context, "context") appendStringFlag(o, flags.APIServer, "server") appendBoolFlag(o, flags.Insecure, "insecure-skip-tls-verify") @@ -128,7 +128,7 @@ func appendBoolFlag(out *[]string, in *bool, flag string) { } } -func appendStringArrayFlag(out *[]string, in *[]string, flag string) { +func appendStringArrayFlag(out, in *[]string, flag string) { if in != nil && len(*in) > 0 { *out = append(*out, fmt.Sprintf("--%v=%v'", flag, strings.Join(*in, ","))) } diff --git a/cmd/plugin/lints/deployment.go b/cmd/plugin/lints/deployment.go index a1c473f1e..ce1712284 100644 --- a/cmd/plugin/lints/deployment.go +++ b/cmd/plugin/lints/deployment.go @@ -35,7 +35,10 @@ type DeploymentLint struct { // Check returns true if the lint detects an issue func (lint DeploymentLint) Check(obj kmeta.Object) bool { - cmp := obj.(*v1.Deployment) + cmp, ok := obj.(*v1.Deployment) + if !ok { + util.PrintError(fmt.Errorf("unexpected type: %T", obj)) + } return lint.f(*cmp) } @@ -72,11 +75,11 @@ func removedFlag(flag string, issueNumber int, version string) DeploymentLint { issue: issueNumber, version: version, f: func(dep v1.Deployment) bool { - if !isIngressNginxDeployment(dep) { + if !isIngressNginxDeployment(&dep) { return false } - args := getNginxArgs(dep) + args := getNginxArgs(&dep) for _, arg := range args { if strings.HasPrefix(arg, fmt.Sprintf("--%v", flag)) { return true @@ -88,8 +91,9 @@ func removedFlag(flag string, issueNumber int, version string) DeploymentLint { } } -func getNginxArgs(dep v1.Deployment) []string { - for _, container := range dep.Spec.Template.Spec.Containers { +func getNginxArgs(dep *v1.Deployment) []string { + for i := range dep.Spec.Template.Spec.Containers { + container := &dep.Spec.Template.Spec.Containers[i] if len(container.Args) > 0 && container.Args[0] == "/nginx-ingress-controller" { return container.Args } @@ -97,10 +101,10 @@ func getNginxArgs(dep v1.Deployment) []string { return make([]string, 0) } -func isIngressNginxDeployment(dep v1.Deployment) bool { +func isIngressNginxDeployment(dep *v1.Deployment) bool { containers := dep.Spec.Template.Spec.Containers - for _, container := range containers { - if len(container.Args) > 0 && container.Args[0] == "/nginx-ingress-controller" { + for i := range containers { + if len(containers[i].Args) > 0 && containers[i].Args[0] == "/nginx-ingress-controller" { return true } } diff --git a/cmd/plugin/lints/ingress.go b/cmd/plugin/lints/ingress.go index ea08bfd8b..d5ad42e2c 100644 --- a/cmd/plugin/lints/ingress.go +++ b/cmd/plugin/lints/ingress.go @@ -30,13 +30,16 @@ type IngressLint struct { message string issue int version string - f func(ing networking.Ingress) bool + f func(ing *networking.Ingress) bool } // Check returns true if the lint detects an issue func (lint IngressLint) Check(obj kmeta.Object) bool { - ing := obj.(*networking.Ingress) - return lint.f(*ing) + ing, ok := obj.(*networking.Ingress) + if !ok { + util.PrintError(fmt.Errorf("unexpected type: %T", obj)) + } + return lint.f(ing) } // Message is a description of the lint @@ -94,7 +97,7 @@ func GetIngressLints() []IngressLint { } } -func xForwardedPrefixIsBool(ing networking.Ingress) bool { +func xForwardedPrefixIsBool(ing *networking.Ingress) bool { for name, val := range ing.Annotations { if strings.HasSuffix(name, "/x-forwarded-prefix") && (val == "true" || val == "false") { return true @@ -103,7 +106,7 @@ func xForwardedPrefixIsBool(ing networking.Ingress) bool { return false } -func annotationPrefixIsNginxCom(ing networking.Ingress) bool { +func annotationPrefixIsNginxCom(ing *networking.Ingress) bool { for name := range ing.Annotations { if strings.HasPrefix(name, "nginx.com/") { return true @@ -112,7 +115,7 @@ func annotationPrefixIsNginxCom(ing networking.Ingress) bool { return false } -func annotationPrefixIsNginxOrg(ing networking.Ingress) bool { +func annotationPrefixIsNginxOrg(ing *networking.Ingress) bool { for name := range ing.Annotations { if strings.HasPrefix(name, "nginx.org/") { return true @@ -121,7 +124,7 @@ func annotationPrefixIsNginxOrg(ing networking.Ingress) bool { return false } -func rewriteTargetWithoutCaptureGroup(ing networking.Ingress) bool { +func rewriteTargetWithoutCaptureGroup(ing *networking.Ingress) bool { for name, val := range ing.Annotations { if strings.HasSuffix(name, "/rewrite-target") && !strings.Contains(val, "$1") { return true @@ -135,7 +138,7 @@ func removedAnnotation(annotationName string, issueNumber int, version string) I message: fmt.Sprintf("Contains the removed %v annotation.", annotationName), issue: issueNumber, version: version, - f: func(ing networking.Ingress) bool { + f: func(ing *networking.Ingress) bool { for annotation := range ing.Annotations { if strings.HasSuffix(annotation, "/"+annotationName) { return true @@ -146,7 +149,7 @@ func removedAnnotation(annotationName string, issueNumber int, version string) I } } -func satisfyDirective(ing networking.Ingress) bool { +func satisfyDirective(ing *networking.Ingress) bool { for name, val := range ing.Annotations { if strings.HasSuffix(name, "/configuration-snippet") { return strings.Contains(val, "satisfy") diff --git a/cmd/plugin/main.go b/cmd/plugin/main.go index f3a809715..e9a8ea59a 100644 --- a/cmd/plugin/main.go +++ b/cmd/plugin/main.go @@ -24,7 +24,7 @@ import ( "k8s.io/cli-runtime/pkg/genericclioptions" - //Just importing this is supposed to allow cloud authentication + // Just importing this is supposed to allow cloud authentication // eg GCP, AWS, Azure ... _ "k8s.io/client-go/plugin/pkg/client/auth" diff --git a/cmd/plugin/request/request.go b/cmd/plugin/request/request.go index fd47564a9..55df85d5e 100644 --- a/cmd/plugin/request/request.go +++ b/cmd/plugin/request/request.go @@ -35,7 +35,7 @@ import ( ) // ChoosePod finds a pod either by deployment or by name -func ChoosePod(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string) (apiv1.Pod, error) { +func ChoosePod(flags *genericclioptions.ConfigFlags, podName, deployment, selector string) (apiv1.Pod, error) { if podName != "" { return GetNamedPod(flags, podName) } @@ -54,9 +54,9 @@ func GetNamedPod(flags *genericclioptions.ConfigFlags, name string) (apiv1.Pod, return apiv1.Pod{}, err } - for _, pod := range allPods { - if pod.Name == name { - return pod, nil + for i := range allPods { + if allPods[i].Name == name { + return allPods[i], nil } } @@ -132,7 +132,7 @@ func GetIngressDefinitions(flags *genericclioptions.ConfigFlags, namespace strin } // GetNumEndpoints counts the number of endpointslices adresses for the service with the given name -func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace string, serviceName string) (*int, error) { +func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace, serviceName string) (*int, error) { epss, err := GetEndpointSlicesByName(flags, namespace, serviceName) if err != nil { return nil, err @@ -143,25 +143,26 @@ func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace string, ser } ret := 0 - for _, eps := range epss { - for _, ep := range eps.Endpoints { - ret += len(ep.Addresses) + for i := range epss { + eps := &epss[i] + for j := range eps.Endpoints { + ret += len(eps.Endpoints[j].Addresses) } } return &ret, nil } // GetEndpointSlicesByName returns the endpointSlices for the service with the given name -func GetEndpointSlicesByName(flags *genericclioptions.ConfigFlags, namespace string, name string) ([]discoveryv1.EndpointSlice, error) { +func GetEndpointSlicesByName(flags *genericclioptions.ConfigFlags, namespace, name string) ([]discoveryv1.EndpointSlice, error) { allEndpointsSlices, err := getEndpointSlices(flags, namespace) if err != nil { return nil, err } var eps []discoveryv1.EndpointSlice - for _, slice := range allEndpointsSlices { - if svcName, ok := slice.ObjectMeta.GetLabels()[discoveryv1.LabelServiceName]; ok { + for i := range allEndpointsSlices { + if svcName, ok := allEndpointsSlices[i].ObjectMeta.GetLabels()[discoveryv1.LabelServiceName]; ok { if svcName == name { - eps = append(eps, slice) + eps = append(eps, allEndpointsSlices[i]) } } } @@ -182,7 +183,7 @@ func getEndpointSlices(flags *genericclioptions.ConfigFlags, namespace string) ( tryAllNamespacesEndpointSlicesCache(flags) } - cachedEndpointSlices = tryFilteringEndpointSlicesFromAllNamespacesCache(flags, namespace) + cachedEndpointSlices = tryFilteringEndpointSlicesFromAllNamespacesCache(namespace) if cachedEndpointSlices != nil { return *cachedEndpointSlices, nil @@ -217,13 +218,13 @@ func tryAllNamespacesEndpointSlicesCache(flags *genericclioptions.ConfigFlags) { } } -func tryFilteringEndpointSlicesFromAllNamespacesCache(flags *genericclioptions.ConfigFlags, namespace string) *[]discoveryv1.EndpointSlice { +func tryFilteringEndpointSlicesFromAllNamespacesCache(namespace string) *[]discoveryv1.EndpointSlice { allEndpointSlices := endpointSlicesCache[""] if allEndpointSlices != nil { endpointSlices := make([]discoveryv1.EndpointSlice, 0) - for _, slice := range *allEndpointSlices { - if slice.Namespace == namespace { - endpointSlices = append(endpointSlices, slice) + for i := range *allEndpointSlices { + if (*allEndpointSlices)[i].Namespace == namespace { + endpointSlices = append(endpointSlices, (*allEndpointSlices)[i]) } } endpointSlicesCache[namespace] = &endpointSlices @@ -242,9 +243,9 @@ func GetServiceByName(flags *genericclioptions.ConfigFlags, name string, service services = &servicesArray } - for _, svc := range *services { - if svc.Name == name { - return svc, nil + for i := range *services { + if (*services)[i].Name == name { + return (*services)[i], nil } } @@ -288,7 +289,6 @@ func getLabeledPods(flags *genericclioptions.ConfigFlags, label string) ([]apiv1 pods, err := api.Pods(namespace).List(context.TODO(), metav1.ListOptions{ LabelSelector: label, }) - if err != nil { return make([]apiv1.Pod, 0), err } @@ -303,9 +303,9 @@ func getDeploymentPods(flags *genericclioptions.ConfigFlags, deployment string) } ingressPods := make([]apiv1.Pod, 0) - for _, pod := range pods { - if util.PodInDeployment(pod, deployment) { - ingressPods = append(ingressPods, pod) + for i := range pods { + if util.PodInDeployment(&pods[i], deployment) { + ingressPods = append(ingressPods, pods[i]) } } @@ -331,5 +331,4 @@ func getServices(flags *genericclioptions.ConfigFlags) ([]apiv1.Service, error) } return services.Items, nil - } diff --git a/cmd/plugin/util/util.go b/cmd/plugin/util/util.go index e1910140d..aa753689a 100644 --- a/cmd/plugin/util/util.go +++ b/cmd/plugin/util/util.go @@ -47,17 +47,25 @@ func PrintError(e error) { } // ParseVersionString returns the major, minor, and patch numbers of a version string -func ParseVersionString(v string) (int, int, int, error) { +func ParseVersionString(v string) (major, minor, patch int, err error) { parts := versionRegex.FindStringSubmatch(v) if len(parts) != 4 { return 0, 0, 0, fmt.Errorf("could not parse %v as a version string (like 0.20.3)", v) } - major, _ := strconv.Atoi(parts[1]) - minor, _ := strconv.Atoi(parts[2]) - patch, _ := strconv.Atoi(parts[3]) - + major, err = strconv.Atoi(parts[1]) + if err != nil { + return 0, 0, 0, err + } + minor, err = strconv.Atoi(parts[2]) + if err != nil { + return 0, 0, 0, err + } + patch, err = strconv.Atoi(parts[3]) + if err != nil { + return 0, 0, 0, err + } return major, minor, patch, nil } @@ -90,7 +98,7 @@ func isVersionLessThan(a, b string) bool { // PodInDeployment returns whether a pod is part of a deployment with the given name // a pod is considered to be in {deployment} if it is owned by a replicaset with a name of format {deployment}-otherchars -func PodInDeployment(pod apiv1.Pod, deployment string) bool { +func PodInDeployment(pod *apiv1.Pod, deployment string) bool { for _, owner := range pod.OwnerReferences { if owner.Controller == nil || !*owner.Controller || owner.Kind != "ReplicaSet" { continue @@ -138,7 +146,7 @@ func AddContainerFlag(cmd *cobra.Command) *string { // GetNamespace takes a set of kubectl flag values and returns the namespace we should be operating in func GetNamespace(flags *genericclioptions.ConfigFlags) string { namespace, _, err := flags.ToRawKubeConfigLoader().Namespace() - if err != nil || len(namespace) == 0 { + if err != nil || namespace == "" { namespace = apiv1.NamespaceDefault } return namespace diff --git a/docs/e2e-tests.md b/docs/e2e-tests.md index c45b1e72c..398304c57 100644 --- a/docs/e2e-tests.md +++ b/docs/e2e-tests.md @@ -716,7 +716,7 @@ Do not try to edit it manually. ### [[Flag] watch namespace selector](https://github.com/kubernetes/ingress-nginx/tree/main/test/e2e/settings/namespace_selector.go#L30) -- [should ingore Ingress of namespace without label foo=bar and accept those of namespace with label foo=bar](https://github.com/kubernetes/ingress-nginx/tree/main/test/e2e/settings/namespace_selector.go#L63) +- [should ignore Ingress of namespace without label foo=bar and accept those of namespace with label foo=bar](https://github.com/kubernetes/ingress-nginx/tree/main/test/e2e/settings/namespace_selector.go#L63) ### [[Security] no-auth-locations](https://github.com/kubernetes/ingress-nginx/tree/main/test/e2e/settings/no_auth_locations.go#L33) diff --git a/images/fastcgi-helloserver/rootfs/main.go b/images/fastcgi-helloserver/rootfs/main.go index a42c9a487..710f90f2c 100644 --- a/images/fastcgi-helloserver/rootfs/main.go +++ b/images/fastcgi-helloserver/rootfs/main.go @@ -16,13 +16,13 @@ func hello(w http.ResponseWriter, r *http.Request) { } key := keys[0] - fmt.Fprintf(w, "Hello "+string(key)+"!") + fmt.Fprintf(w, "Hello "+key+"!") } func main() { http.HandleFunc("/hello", hello) - l, err := net.Listen("tcp", "0.0.0.0:9000") + l, err := net.Listen("tcp", "0.0.0.0:9000") //nolint:gosec // Ignore the gosec error since it's a hello server if err != nil { panic(err) } diff --git a/images/go-grpc-greeter-server/rootfs/main.go b/images/go-grpc-greeter-server/rootfs/main.go index 569273dfd..d7fc36208 100644 --- a/images/go-grpc-greeter-server/rootfs/main.go +++ b/images/go-grpc-greeter-server/rootfs/main.go @@ -41,7 +41,7 @@ type hwServer struct { } // SayHello implements helloworld.GreeterServer -func (s *hwServer) SayHello(ctx context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { +func (s *hwServer) SayHello(_ context.Context, in *hwpb.HelloRequest) (*hwpb.HelloReply, error) { return &hwpb.HelloReply{Message: "Hello " + in.Name}, nil } @@ -49,7 +49,7 @@ type ecServer struct { ecpb.UnimplementedEchoServer } -func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { +func (s *ecServer) UnaryEcho(_ context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { return &ecpb.EchoResponse{Message: req.Message}, nil } diff --git a/internal/admission/controller/main.go b/internal/admission/controller/main.go index f59bf2091..888818c89 100644 --- a/internal/admission/controller/main.go +++ b/internal/admission/controller/main.go @@ -42,19 +42,16 @@ type IngressAdmission struct { Checker Checker } -var ( - ingressResource = metav1.GroupVersionKind{ - Group: networking.GroupName, - Version: "v1", - Kind: "Ingress", - } -) +var ingressResource = metav1.GroupVersionKind{ + Group: networking.GroupName, + Version: "v1", + Kind: "Ingress", +} // HandleAdmission populates the admission Response // with Allowed=false if the Object is an ingress that would prevent nginx to reload the configuration // with Allowed=true otherwise func (ia *IngressAdmission) HandleAdmission(obj runtime.Object) (runtime.Object, error) { - review, isV1 := obj.(*admissionv1.AdmissionReview) if !isV1 { return nil, fmt.Errorf("request is not of type AdmissionReview v1 or v1beta1") diff --git a/internal/admission/controller/main_test.go b/internal/admission/controller/main_test.go index 8c42f87ef..1d223cc9e 100644 --- a/internal/admission/controller/main_test.go +++ b/internal/admission/controller/main_test.go @@ -33,12 +33,12 @@ type failTestChecker struct { t *testing.T } -func (ftc failTestChecker) CheckIngress(ing *networking.Ingress) error { +func (ftc failTestChecker) CheckIngress(_ *networking.Ingress) error { ftc.t.Error("checker should not be called") return nil } -func (ftc failTestChecker) CheckWarning(ing *networking.Ingress) ([]string, error) { +func (ftc failTestChecker) CheckWarning(_ *networking.Ingress) ([]string, error) { ftc.t.Error("checker should not be called") return nil, nil } diff --git a/internal/admission/controller/server.go b/internal/admission/controller/server.go index 3fa70971f..7fc61bcbb 100644 --- a/internal/admission/controller/server.go +++ b/internal/admission/controller/server.go @@ -26,9 +26,7 @@ import ( "k8s.io/klog/v2" ) -var ( - scheme = runtime.NewScheme() -) +var scheme = runtime.NewScheme() func init() { if err := admissionv1.AddToScheme(scheme); err != nil { diff --git a/internal/ingress/annotations/alias/main.go b/internal/ingress/annotations/alias/main.go index 4a5e6f188..7a33e648e 100644 --- a/internal/ingress/annotations/alias/main.go +++ b/internal/ingress/annotations/alias/main.go @@ -72,7 +72,7 @@ func (a alias) Parse(ing *networking.Ingress) (interface{}, error) { aliases := sets.NewString() for _, alias := range strings.Split(val, ",") { alias = strings.TrimSpace(alias) - if len(alias) == 0 { + if alias == "" { continue } diff --git a/internal/ingress/annotations/alias/main_test.go b/internal/ingress/annotations/alias/main_test.go index 1965f2630..f1d68c1f7 100644 --- a/internal/ingress/annotations/alias/main_test.go +++ b/internal/ingress/annotations/alias/main_test.go @@ -65,9 +65,9 @@ func TestParse(t *testing.T) { if testCase.skipValidation { parser.EnableAnnotationValidation = false } - defer func() { + t.Cleanup(func() { parser.EnableAnnotationValidation = true - }() + }) result, err := ap.Parse(ing) if (err != nil) != testCase.wantErr { t.Errorf("ParseAliasAnnotation() annotation: %s, error = %v, wantErr %v", testCase.annotations, err, testCase.wantErr) diff --git a/internal/ingress/annotations/annotations.go b/internal/ingress/annotations/annotations.go index 5371e6eb7..38843c2db 100644 --- a/internal/ingress/annotations/annotations.go +++ b/internal/ingress/annotations/annotations.go @@ -86,37 +86,36 @@ type Ingress struct { CorsConfig cors.Config CustomHTTPErrors []int DefaultBackend *apiv1.Service - //TODO: Change this back into an error when https://github.com/imdario/mergo/issues/100 is resolved - FastCGI fastcgi.Config - Denied *string - ExternalAuth authreq.Config - EnableGlobalAuth bool - HTTP2PushPreload bool - Opentracing opentracing.Config - Opentelemetry opentelemetry.Config - Proxy proxy.Config - ProxySSL proxyssl.Config - RateLimit ratelimit.Config - GlobalRateLimit globalratelimit.Config - Redirect redirect.Config - Rewrite rewrite.Config - Satisfy string - ServerSnippet string - ServiceUpstream bool - SessionAffinity sessionaffinity.Config - SSLPassthrough bool - UsePortInRedirects bool - UpstreamHashBy upstreamhashby.Config - LoadBalancing string - UpstreamVhost string - Denylist ipdenylist.SourceRange - XForwardedPrefix string - SSLCipher sslcipher.Config - Logs log.Config - ModSecurity modsecurity.Config - Mirror mirror.Config - StreamSnippet string - Allowlist ipallowlist.SourceRange + FastCGI fastcgi.Config + Denied *string + ExternalAuth authreq.Config + EnableGlobalAuth bool + HTTP2PushPreload bool + Opentracing opentracing.Config + Opentelemetry opentelemetry.Config + Proxy proxy.Config + ProxySSL proxyssl.Config + RateLimit ratelimit.Config + GlobalRateLimit globalratelimit.Config + Redirect redirect.Config + Rewrite rewrite.Config + Satisfy string + ServerSnippet string + ServiceUpstream bool + SessionAffinity sessionaffinity.Config + SSLPassthrough bool + UsePortInRedirects bool + UpstreamHashBy upstreamhashby.Config + LoadBalancing string + UpstreamVhost string + Denylist ipdenylist.SourceRange + XForwardedPrefix string + SSLCipher sslcipher.Config + Logs log.Config + ModSecurity modsecurity.Config + Mirror mirror.Config + StreamSnippet string + Allowlist ipallowlist.SourceRange } // Extractor defines the annotation parsers to be used in the extraction of annotations diff --git a/internal/ingress/annotations/annotations_test.go b/internal/ingress/annotations/annotations_test.go index 2b2a64268..5f8128e0d 100644 --- a/internal/ingress/annotations/annotations_test.go +++ b/internal/ingress/annotations/annotations_test.go @@ -64,7 +64,11 @@ func (m mockCfg) GetService(name string) (*apiv1.Service, error) { } func (m mockCfg) GetAuthCertificate(name string) (*resolver.AuthSSLCert, error) { - if secret, _ := m.GetSecret(name); secret != nil { + secret, err := m.GetSecret(name) + if err != nil { + return nil, err + } + if secret != nil { return &resolver.AuthSSLCert{ Secret: name, CAFileName: "/opt/ca.pem", @@ -270,9 +274,9 @@ func TestCors(t *testing.T) { if r.CorsAllowCredentials != foo.credentials { t.Errorf("Returned %v but expected %v for Cors Credentials", r.CorsAllowCredentials, foo.credentials) } - } } + func TestCustomHTTPErrors(t *testing.T) { ec := NewAnnotationExtractor(mockCfg{}) ing := buildIngress() diff --git a/internal/ingress/annotations/auth/main.go b/internal/ingress/annotations/auth/main.go index beecebdb1..7c7fde7b8 100644 --- a/internal/ingress/annotations/auth/main.go +++ b/internal/ingress/annotations/auth/main.go @@ -50,7 +50,7 @@ var ( ) var AuthSecretConfig = parser.AnnotationConfig{ - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars Documentation: `This annotation defines the name of the Secret that contains the usernames and passwords which are granted access to the paths defined in the Ingress rules. `, @@ -61,20 +61,20 @@ var authSecretAnnotations = parser.Annotation{ Annotations: parser.AnnotationFields{ AuthSecretAnnotation: AuthSecretConfig, authSecretTypeAnnotation: { - Validator: parser.ValidateRegex(*authSecretTypeRegex, true), + Validator: parser.ValidateRegex(authSecretTypeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation what is the format of auth-secret value. Can be "auth-file" that defines the content of an htpasswd file, or "auth-map" where each key is a user and each value is the password.`, }, authRealmAnnotation: { - Validator: parser.ValidateRegex(*parser.CharsWithSpace, false), + Validator: parser.ValidateRegex(parser.CharsWithSpace, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars Documentation: `This annotation defines the realm (message) that should be shown to user when authentication is requested.`, }, authTypeAnnotation: { - Validator: parser.ValidateRegex(*authTypeRegex, true), + Validator: parser.ValidateRegex(authTypeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation defines the basic authentication type. Should be "basic" or "digest"`, @@ -167,14 +167,14 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { s, err := parser.GetStringAnnotation(AuthSecretAnnotation, ing, a.annotationConfig.Annotations) if err != nil { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("error reading secret name from annotation: %w", err), } } sns, sname, err := cache.SplitMetaNamespaceKey(s) if err != nil { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("error reading secret name from annotation: %w", err), } } @@ -185,7 +185,7 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { secCfg := a.r.GetSecurityConfiguration() // We don't accept different namespaces for secrets. if !secCfg.AllowCrossNamespaceResources && sns != ing.Namespace { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("cross namespace usage of secrets is not allowed"), } } @@ -193,7 +193,7 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { name := fmt.Sprintf("%v/%v", sns, sname) secret, err := a.r.GetSecret(name) if err != nil { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("unexpected error reading secret %s: %w", name, err), } } @@ -217,7 +217,7 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { return nil, err } default: - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("invalid auth-secret-type in annotation, must be 'auth-file' or 'auth-map': %w", err), } } @@ -238,14 +238,14 @@ func (a auth) Parse(ing *networking.Ingress) (interface{}, error) { func dumpSecretAuthFile(filename string, secret *api.Secret) error { val, ok := secret.Data["auth"] if !ok { - return ing_errors.LocationDenied{ + return ing_errors.LocationDeniedError{ Reason: fmt.Errorf("the secret %s does not contain a key with value auth", secret.Name), } } err := os.WriteFile(filename, val, file.ReadWriteByUser) if err != nil { - return ing_errors.LocationDenied{ + return ing_errors.LocationDeniedError{ Reason: fmt.Errorf("unexpected error creating password file: %w", err), } } @@ -264,7 +264,7 @@ func dumpSecretAuthMap(filename string, secret *api.Secret) error { err := os.WriteFile(filename, []byte(builder.String()), file.ReadWriteByUser) if err != nil { - return ing_errors.LocationDenied{ + return ing_errors.LocationDeniedError{ Reason: fmt.Errorf("unexpected error creating password file: %w", err), } } diff --git a/internal/ingress/annotations/auth/main_test.go b/internal/ingress/annotations/auth/main_test.go index 2a9dc7c72..868f31a05 100644 --- a/internal/ingress/annotations/auth/main_test.go +++ b/internal/ingress/annotations/auth/main_test.go @@ -32,6 +32,15 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +//nolint:gosec // Ignore hardcoded credentials error in testing +const ( + authType = "basic" + authRealm = "-realm-" + defaultDemoSecret = "default/demo-secret" + othernsDemoSecret = "otherns/demo-secret" + demoSecret = "demo-secret" +) + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -80,7 +89,7 @@ type mockSecret struct { } func (m mockSecret) GetSecret(name string) (*api.Secret, error) { - if name != "default/demo-secret" && name != "otherns/demo-secret" { + if name != defaultDemoSecret && name != othernsDemoSecret { return nil, fmt.Errorf("there is no secret with name %v", name) } @@ -92,7 +101,7 @@ func (m mockSecret) GetSecret(name string) (*api.Secret, error) { return &api.Secret{ ObjectMeta: meta_v1.ObjectMeta{ Namespace: ns, - Name: "demo-secret", + Name: demoSecret, }, Data: map[string][]byte{"auth": []byte("foo:$apr1$OFG3Xybp$ckL0FHDAkoXYIlH9.cysT0")}, }, nil @@ -129,9 +138,9 @@ func TestIngressInvalidRealm(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "something weird ; location trying to { break }" - data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = demoSecret ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -148,14 +157,14 @@ func TestIngressInvalidDifferentNamespace(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" - data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "otherns/demo-secret" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = othernsDemoSecret ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - expected := ing_errors.LocationDenied{ + expected := ing_errors.LocationDeniedError{ Reason: errors.New("cross namespace usage of secrets is not allowed"), } _, err := NewParser(dir, &mockSecret{}).Parse(ing) @@ -168,8 +177,8 @@ func TestIngressInvalidDifferentNamespaceAllowed(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" - data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "otherns/demo-secret" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = othernsDemoSecret ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -187,14 +196,14 @@ func TestIngressInvalidSecretName(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret;xpto" ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - expected := ing_errors.LocationDenied{ + expected := ing_errors.LocationDeniedError{ Reason: errors.New("error reading secret name from annotation: annotation nginx.ingress.kubernetes.io/auth-secret contains invalid value"), } _, err := NewParser(dir, &mockSecret{}).Parse(ing) @@ -207,13 +216,13 @@ func TestInvalidIngressAuthNoSecret(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) defer os.RemoveAll(dir) - expected := ing_errors.LocationDenied{ + expected := ing_errors.LocationDeniedError{ Reason: errors.New("error reading secret name from annotation: ingress rule without annotations"), } _, err := NewParser(dir, &mockSecret{}).Parse(ing) @@ -226,9 +235,9 @@ func TestIngressAuth(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" - data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" - data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = demoSecret + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = authRealm ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -242,10 +251,10 @@ func TestIngressAuth(t *testing.T) { if !ok { t.Errorf("expected a BasicDigest type") } - if auth.Type != "basic" { + if auth.Type != authType { t.Errorf("Expected basic as auth type but returned %s", auth.Type) } - if auth.Realm != "-realm-" { + if auth.Realm != authRealm { t.Errorf("Expected -realm- as realm but returned %s", auth.Realm) } if !auth.Secured { @@ -257,9 +266,9 @@ func TestIngressAuthWithoutSecret(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "invalid-secret" - data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = authRealm ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -275,10 +284,10 @@ func TestIngressAuthInvalidSecretKey(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = "basic" - data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = "demo-secret" + data[parser.GetAnnotationWithPrefix(authTypeAnnotation)] = authType + data[parser.GetAnnotationWithPrefix(AuthSecretAnnotation)] = demoSecret data[parser.GetAnnotationWithPrefix(authSecretTypeAnnotation)] = "invalid-type" - data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = "-realm-" + data[parser.GetAnnotationWithPrefix(authRealmAnnotation)] = authRealm ing.SetAnnotations(data) _, dir, _ := dummySecretContent(t) @@ -290,7 +299,7 @@ func TestIngressAuthInvalidSecretKey(t *testing.T) { } } -func dummySecretContent(t *testing.T) (string, string, *api.Secret) { +func dummySecretContent(t *testing.T) (fileName, dir string, s *api.Secret) { dir, err := os.MkdirTemp("", fmt.Sprintf("%v", time.Now().Unix())) if err != nil { t.Error(err) @@ -301,7 +310,10 @@ func dummySecretContent(t *testing.T) (string, string, *api.Secret) { t.Error(err) } defer tmpfile.Close() - s, _ := mockSecret{}.GetSecret("default/demo-secret") + s, err = mockSecret{}.GetSecret(defaultDemoSecret) + if err != nil { + t.Errorf("unexpected error: %v", err) + } return tmpfile.Name(), dir, s } diff --git a/internal/ingress/annotations/authreq/main.go b/internal/ingress/annotations/authreq/main.go index b8ba4f125..c66b0ed47 100644 --- a/internal/ingress/annotations/authreq/main.go +++ b/internal/ingress/annotations/authreq/main.go @@ -57,25 +57,25 @@ var authReqAnnotations = parser.Annotation{ Group: "authentication", Annotations: parser.AnnotationFields{ authReqURLAnnotation: { - Validator: parser.ValidateRegex(*parser.URLWithNginxVariableRegex, true), + Validator: parser.ValidateRegex(parser.URLWithNginxVariableRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation allows to indicate the URL where the HTTP request should be sent`, }, authReqMethodAnnotation: { - Validator: parser.ValidateRegex(*methodsRegex, true), + Validator: parser.ValidateRegex(methodsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation allows to specify the HTTP method to use`, }, authReqSigninAnnotation: { - Validator: parser.ValidateRegex(*parser.URLWithNginxVariableRegex, true), + Validator: parser.ValidateRegex(parser.URLWithNginxVariableRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation allows to specify the location of the error page`, }, authReqSigninRedirParamAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows to specify the URL parameter in the error page which should contain the original URL for a failed signin request`, @@ -87,7 +87,7 @@ var authReqAnnotations = parser.Annotation{ Documentation: `This annotation allows to specify a custom snippet to use with external authentication`, }, authReqCacheKeyAnnotation: { - Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + Validator: parser.ValidateRegex(parser.NGINXVariable, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation enables caching for auth requests.`, @@ -117,26 +117,26 @@ var authReqAnnotations = parser.Annotation{ Documentation: `This annotation specifies a duration in seconds which an idle keepalive connection to an upstream server will stay open`, }, authReqCacheDuration: { - Validator: parser.ValidateRegex(*parser.ExtendedCharsRegex, false), + Validator: parser.ValidateRegex(parser.ExtendedCharsRegex, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows to specify a caching time for auth responses based on their response codes, e.g. 200 202 30m`, }, authReqResponseHeadersAnnotation: { - Validator: parser.ValidateRegex(*parser.HeadersVariable, true), + Validator: parser.ValidateRegex(parser.HeadersVariable, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation sets the headers to pass to backend once authentication request completes. They should be separated by comma.`, }, authReqProxySetHeadersAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation sets the name of a ConfigMap that specifies headers to pass to the authentication service. Only ConfigMaps on the same namespace are allowed`, }, authReqRequestRedirectAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows to specify the X-Auth-Request-Redirect header value`, @@ -249,8 +249,8 @@ func (e1 *Config) Equal(e2 *Config) bool { var ( methodsRegex = regexp.MustCompile("(GET|HEAD|POST|PUT|PATCH|DELETE|CONNECT|OPTIONS|TRACE)") headerRegexp = regexp.MustCompile(`^[a-zA-Z\d\-_]+$`) - statusCodeRegex = regexp.MustCompile(`^[\d]{3}$`) - durationRegex = regexp.MustCompile(`^[\d]+(ms|s|m|h|d|w|M|y)$`) // see http://nginx.org/en/docs/syntax.html + statusCodeRegex = regexp.MustCompile(`^\d{3}$`) + durationRegex = regexp.MustCompile(`^\d+(ms|s|m|h|d|w|M|y)$`) // see http://nginx.org/en/docs/syntax.html ) // ValidMethod checks is the provided string a valid HTTP method @@ -273,7 +273,7 @@ func ValidCacheDuration(duration string) bool { seenDuration := false for _, element := range elements { - if len(element) == 0 { + if element == "" { continue } if statusCodeRegex.MatchString(element) { @@ -304,6 +304,8 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // ParseAnnotations parses the annotations contained in the ingress // rule used to use an Config URL as source for authentication +// +//nolint:gocyclo // Ignore function complexity error func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { // Required Parameters urlString, err := parser.GetStringAnnotation(authReqURLAnnotation, ing, a.annotationConfig.Annotations) @@ -313,7 +315,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { authURL, err := parser.StringToURL(urlString) if err != nil { - return nil, ing_errors.LocationDenied{Reason: fmt.Errorf("could not parse auth-url annotation: %v", err)} + return nil, ing_errors.LocationDeniedError{Reason: fmt.Errorf("could not parse auth-url annotation: %v", err)} } authMethod, err := parser.GetStringAnnotation(authReqMethodAnnotation, ing, a.annotationConfig.Annotations) @@ -410,7 +412,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { if err != nil && ing_errors.IsValidationError(err) { return nil, ing_errors.NewLocationDenied("validation error") } - if len(hstr) != 0 { + if hstr != "" { harr := strings.Split(hstr, ",") for _, header := range harr { header = strings.TrimSpace(header) @@ -430,7 +432,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { cns, _, err := cache.SplitMetaNamespaceKey(proxySetHeaderMap) if err != nil { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("error reading configmap name %s from annotation: %w", proxySetHeaderMap, err), } } @@ -442,7 +444,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { secCfg := a.r.GetSecurityConfiguration() // We don't accept different namespaces for secrets. if !secCfg.AllowCrossNamespaceResources && cns != ing.Namespace { - return nil, ing_errors.LocationDenied{ + return nil, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("cross namespace usage of secrets is not allowed"), } } @@ -499,7 +501,7 @@ func (a authReq) Parse(ing *networking.Ingress) (interface{}, error) { // It will always return at least one duration (the default duration) func ParseStringToCacheDurations(input string) ([]string, error) { authCacheDuration := []string{} - if len(input) != 0 { + if input != "" { arr := strings.Split(input, ",") for _, duration := range arr { duration = strings.TrimSpace(duration) diff --git a/internal/ingress/annotations/authreq/main_test.go b/internal/ingress/annotations/authreq/main_test.go index dc5188c8a..3e6df3d3b 100644 --- a/internal/ingress/annotations/authreq/main_test.go +++ b/internal/ingress/annotations/authreq/main_test.go @@ -17,7 +17,6 @@ limitations under the License. package authreq import ( - "fmt" "reflect" "testing" @@ -113,7 +112,7 @@ func TestAnnotations(t *testing.T) { data[parser.GetAnnotationWithPrefix("auth-url")] = test.url data[parser.GetAnnotationWithPrefix("auth-signin")] = test.signinURL data[parser.GetAnnotationWithPrefix("auth-signin-redirect-param")] = test.signinURLRedirectParam - data[parser.GetAnnotationWithPrefix("auth-method")] = fmt.Sprintf("%v", test.method) + data[parser.GetAnnotationWithPrefix("auth-method")] = test.method data[parser.GetAnnotationWithPrefix("auth-request-redirect")] = test.requestRedirect data[parser.GetAnnotationWithPrefix("auth-snippet")] = test.authSnippet data[parser.GetAnnotationWithPrefix("auth-cache-key")] = test.authCacheKey @@ -331,7 +330,6 @@ func TestKeepaliveAnnotations(t *testing.T) { } func TestParseStringToCacheDurations(t *testing.T) { - tests := []struct { title string duration string @@ -346,7 +344,6 @@ func TestParseStringToCacheDurations(t *testing.T) { } for _, test := range tests { - dur, err := ParseStringToCacheDurations(test.duration) if test.expErr { if err == nil { diff --git a/internal/ingress/annotations/authreqglobal/main.go b/internal/ingress/annotations/authreqglobal/main.go index a1641e085..e8a259047 100644 --- a/internal/ingress/annotations/authreqglobal/main.go +++ b/internal/ingress/annotations/authreqglobal/main.go @@ -55,7 +55,6 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // ParseAnnotations parses the annotations contained in the ingress // rule used to enable or disable global external authentication func (a authReqGlobal) Parse(ing *networking.Ingress) (interface{}, error) { - enableGlobalAuth, err := parser.GetBoolAnnotation(enableGlobalAuthAnnotation, ing, a.annotationConfig.Annotations) if err != nil { enableGlobalAuth = true diff --git a/internal/ingress/annotations/authreqglobal/main_test.go b/internal/ingress/annotations/authreqglobal/main_test.go index 0313edcf5..734f97c0f 100644 --- a/internal/ingress/annotations/authreqglobal/main_test.go +++ b/internal/ingress/annotations/authreqglobal/main_test.go @@ -77,7 +77,10 @@ func TestAnnotation(t *testing.T) { data[parser.GetAnnotationWithPrefix("enable-global-auth")] = "false" ing.SetAnnotations(data) - i, _ := NewParser(&resolver.Mock{}).Parse(ing) + i, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } u, ok := i.(bool) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/authtls/main.go b/internal/ingress/annotations/authtls/main.go index 5d6763e8b..adedb084a 100644 --- a/internal/ingress/annotations/authtls/main.go +++ b/internal/ingress/annotations/authtls/main.go @@ -18,11 +18,10 @@ package authtls import ( "fmt" + "regexp" networking "k8s.io/api/networking/v1" - "regexp" - "k8s.io/ingress-nginx/internal/ingress/annotations/parser" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" @@ -45,20 +44,20 @@ var ( regexChars = regexp.QuoteMeta(`()|=`) authVerifyClientRegex = regexp.MustCompile(`on|off|optional|optional_no_ca`) commonNameRegex = regexp.MustCompile(`^CN=[/\-.\_\~a-zA-Z0-9` + regexChars + `]*$`) - redirectRegex = regexp.MustCompile(`^((https?://)?[A-Za-z0-9\-\.]*(:[0-9]+)?/[A-Za-z0-9\-\.]*)?$`) + redirectRegex = regexp.MustCompile(`^((https?://)?[A-Za-z0-9\-.]*(:\d+)?/[A-Za-z0-9\-.]*)?$`) ) var authTLSAnnotations = parser.Annotation{ Group: "authentication", Annotations: parser.AnnotationFields{ annotationAuthTLSSecret: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars Documentation: `This annotation defines the secret that contains the certificate chain of allowed certs`, }, annotationAuthTLSVerifyClient: { - Validator: parser.ValidateRegex(*authVerifyClientRegex, true), + Validator: parser.ValidateRegex(authVerifyClientRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium as it allows a subset of chars Documentation: `This annotation enables verification of client certificates. Can be "on", "off", "optional" or "optional_no_ca"`, @@ -70,7 +69,7 @@ var authTLSAnnotations = parser.Annotation{ Documentation: `This annotation defines validation depth between the provided client certificate and the Certification Authority chain.`, }, annotationAuthTLSErrorPage: { - Validator: parser.ValidateRegex(*redirectRegex, true), + Validator: parser.ValidateRegex(redirectRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation defines the URL/Page that user should be redirected in case of a Certificate Authentication Error`, @@ -82,7 +81,7 @@ var authTLSAnnotations = parser.Annotation{ Documentation: `This annotation defines if the received certificates should be passed or not to the upstream server in the header "ssl-client-cert"`, }, annotationAuthTLSMatchCN: { - Validator: parser.ValidateRegex(*commonNameRegex, true), + Validator: parser.ValidateRegex(commonNameRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation adds a sanity check for the CN of the client certificate that is sent over using a string / regex starting with "CN="`, @@ -130,9 +129,9 @@ func (assl1 *Config) Equal(assl2 *Config) bool { } // NewParser creates a new TLS authentication annotation parser -func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { +func NewParser(r resolver.Resolver) parser.IngressAnnotation { return authTLS{ - r: resolver, + r: r, annotationConfig: authTLSAnnotations, } } @@ -169,7 +168,7 @@ func (a authTLS) Parse(ing *networking.Ingress) (interface{}, error) { authCert, err := a.r.GetAuthCertificate(tlsauthsecret) if err != nil { e := fmt.Errorf("error obtaining certificate: %w", err) - return &Config{}, ing_errors.LocationDenied{Reason: e} + return &Config{}, ing_errors.LocationDeniedError{Reason: e} } config.AuthSSLCert = *authCert diff --git a/internal/ingress/annotations/authtls/main_test.go b/internal/ingress/annotations/authtls/main_test.go index a1f3f0f92..0dd442e4f 100644 --- a/internal/ingress/annotations/authtls/main_test.go +++ b/internal/ingress/annotations/authtls/main_test.go @@ -27,6 +27,11 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + defaultDemoSecret = "default/demo-secret" + off = "off" +) + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -77,23 +82,22 @@ type mockSecret struct { // GetAuthCertificate from mockSecret mocks the GetAuthCertificate for authTLS func (m mockSecret) GetAuthCertificate(name string) (*resolver.AuthSSLCert, error) { - if name != "default/demo-secret" { + if name != defaultDemoSecret { return nil, errors.Errorf("there is no secret with name %v", name) } return &resolver.AuthSSLCert{ - Secret: "default/demo-secret", + Secret: defaultDemoSecret, CAFileName: "/ssl/ca.crt", CASHA: "abc", }, nil - } func TestAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = "default/demo-secret" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSSecret)] = defaultDemoSecret ing.SetAnnotations(data) @@ -108,7 +112,7 @@ func TestAnnotations(t *testing.T) { t.Errorf("expected *Config but got %v", u) } - secret, err := fakeSecret.GetAuthCertificate("default/demo-secret") + secret, err := fakeSecret.GetAuthCertificate(defaultDemoSecret) if err != nil { t.Errorf("unexpected error getting secret %v", err) } @@ -132,7 +136,7 @@ func TestAnnotations(t *testing.T) { t.Errorf("expected empty string, but got %v", u.MatchCN) } - data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyClient)] = "off" + data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyClient)] = off data[parser.GetAnnotationWithPrefix(annotationAuthTLSVerifyDepth)] = "2" data[parser.GetAnnotationWithPrefix(annotationAuthTLSErrorPage)] = "ok.com/error" data[parser.GetAnnotationWithPrefix(annotationAuthTLSPassCertToUpstream)] = "true" @@ -153,8 +157,8 @@ func TestAnnotations(t *testing.T) { if u.AuthSSLCert.Secret != secret.Secret { t.Errorf("expected %v but got %v", secret.Secret, u.AuthSSLCert.Secret) } - if u.VerifyClient != "off" { - t.Errorf("expected %v but got %v", "off", u.VerifyClient) + if u.VerifyClient != off { + t.Errorf("expected %v but got %v", off, u.VerifyClient) } if u.ValidationDepth != 2 { t.Errorf("expected %v but got %v", 2, u.ValidationDepth) @@ -262,28 +266,21 @@ func TestInvalidAnnotations(t *testing.T) { if u.MatchCN != "" { t.Errorf("expected empty string but got %v", u.MatchCN) } - } func TestEquals(t *testing.T) { cfg1 := &Config{} cfg2 := &Config{} - // Same config - result := cfg1.Equal(cfg1) - if result != true { - t.Errorf("Expected true") - } - // compare nil - result = cfg1.Equal(nil) + result := cfg1.Equal(nil) if result != false { t.Errorf("Expected false") } // Different Certs sslCert1 := resolver.AuthSSLCert{ - Secret: "default/demo-secret", + Secret: defaultDemoSecret, CAFileName: "/ssl/ca.crt", CASHA: "abc", } @@ -302,7 +299,7 @@ func TestEquals(t *testing.T) { // Different Verify Client cfg1.VerifyClient = "on" - cfg2.VerifyClient = "off" + cfg2.VerifyClient = off result = cfg1.Equal(cfg2) if result != false { t.Errorf("Expected false") diff --git a/internal/ingress/annotations/backendprotocol/main.go b/internal/ingress/annotations/backendprotocol/main.go index 2704ce9f6..62674c4e5 100644 --- a/internal/ingress/annotations/backendprotocol/main.go +++ b/internal/ingress/annotations/backendprotocol/main.go @@ -25,9 +25,7 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -var ( - validProtocols = []string{"auto_http", "http", "https", "grpc", "grpcs", "fcgi"} -) +var validProtocols = []string{"auto_http", "http", "https", "grpc", "grpcs", "fcgi"} const ( http = "HTTP" diff --git a/internal/ingress/annotations/backendprotocol/main_test.go b/internal/ingress/annotations/backendprotocol/main_test.go index 490be447b..cb1ec779f 100644 --- a/internal/ingress/annotations/backendprotocol/main_test.go +++ b/internal/ingress/annotations/backendprotocol/main_test.go @@ -44,6 +44,7 @@ func buildIngress() *networking.Ingress { }, } } + func TestParseInvalidAnnotations(t *testing.T) { ing := buildIngress() @@ -56,7 +57,7 @@ func TestParseInvalidAnnotations(t *testing.T) { if !ok { t.Errorf("expected a string type") } - if val != "HTTP" { + if val != http { t.Errorf("expected HTTPS but %v returned", val) } @@ -72,7 +73,7 @@ func TestParseInvalidAnnotations(t *testing.T) { if !ok { t.Errorf("expected a string type") } - if val != "HTTP" { + if val != http { t.Errorf("expected HTTPS but %v returned", val) } @@ -88,7 +89,7 @@ func TestParseInvalidAnnotations(t *testing.T) { if !ok { t.Errorf("expected a string type") } - if val != "HTTP" { + if val != http { t.Errorf("expected HTTPS but %v returned", val) } } diff --git a/internal/ingress/annotations/canary/main.go b/internal/ingress/annotations/canary/main.go index 119f09181..be5761675 100644 --- a/internal/ingress/annotations/canary/main.go +++ b/internal/ingress/annotations/canary/main.go @@ -57,7 +57,7 @@ var CanaryAnnotations = parser.Annotation{ Documentation: `This annotation The total weight of traffic. If unspecified, it defaults to 100`, }, canaryByHeaderAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the header that should be used for notifying the Ingress to route the request to the service specified in the Canary Ingress. @@ -65,7 +65,7 @@ var CanaryAnnotations = parser.Annotation{ For any other value, the header will be ignored and the request compared against the other canary rules by precedence`, }, canaryByHeaderValueAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the header value to match for notifying the Ingress to route the request to the service specified in the Canary Ingress. @@ -74,7 +74,7 @@ var CanaryAnnotations = parser.Annotation{ It doesn't have any effect if the 'canary-by-header' annotation is not defined`, }, canaryByHeaderPatternAnnotation: { - Validator: parser.ValidateRegex(*parser.IsValidRegex, false), + Validator: parser.ValidateRegex(parser.IsValidRegex, false), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation works the same way as canary-by-header-value except it does PCRE Regex matching. @@ -82,7 +82,7 @@ var CanaryAnnotations = parser.Annotation{ When the given Regex causes error during request processing, the request will be considered as not matching.`, }, canaryByCookieAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the cookie that should be used for notifying the Ingress to route the request to the service specified in the Canary Ingress. @@ -189,7 +189,7 @@ func (c canary) GetDocumentation() parser.AnnotationFields { return c.annotationConfig.Annotations } -func (a canary) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (c canary) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(c.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, CanaryAnnotations.Annotations) } diff --git a/internal/ingress/annotations/canary/main_test.go b/internal/ingress/annotations/canary/main_test.go index ddfc0a9c4..1787ddb85 100644 --- a/internal/ingress/annotations/canary/main_test.go +++ b/internal/ingress/annotations/canary/main_test.go @@ -17,6 +17,7 @@ limitations under the License. package canary import ( + "strconv" "testing" api "k8s.io/api/core/v1" @@ -24,8 +25,6 @@ import ( metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" - "strconv" - "k8s.io/ingress-nginx/internal/ingress/resolver" ) @@ -93,7 +92,6 @@ func TestCanaryInvalid(t *testing.T) { if val.Weight != 0 { t.Errorf("Expected %v but got %v", 0, val.Weight) } - } func TestAnnotations(t *testing.T) { @@ -133,10 +131,9 @@ func TestAnnotations(t *testing.T) { } continue - } else { - if err != nil { - t.Errorf("%v: expected nil but returned error %v", test.title, err) - } + } + if err != nil { + t.Errorf("%v: expected nil but returned error %v", test.title, err) } canaryConfig, ok := i.(*Config) diff --git a/internal/ingress/annotations/clientbodybuffersize/main.go b/internal/ingress/annotations/clientbodybuffersize/main.go index aa1485df2..c0fa79713 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main.go +++ b/internal/ingress/annotations/clientbodybuffersize/main.go @@ -31,7 +31,7 @@ var clientBodyBufferSizeConfig = parser.Annotation{ Group: "backend", Annotations: parser.AnnotationFields{ clientBodyBufferSizeAnnotation: { - Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Validator: parser.ValidateRegex(parser.SizeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, // Low, as it allows just a set of options Documentation: `Sets buffer size for reading client request body per location. @@ -65,7 +65,7 @@ func (cbbs clientBodyBufferSize) Parse(ing *networking.Ingress) (interface{}, er return parser.GetStringAnnotation(clientBodyBufferSizeAnnotation, ing, cbbs.annotationConfig.Annotations) } -func (a clientBodyBufferSize) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (cbbs clientBodyBufferSize) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(cbbs.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, clientBodyBufferSizeConfig.Annotations) } diff --git a/internal/ingress/annotations/clientbodybuffersize/main_test.go b/internal/ingress/annotations/clientbodybuffersize/main_test.go index 0f2c8474a..62257aeb9 100644 --- a/internal/ingress/annotations/clientbodybuffersize/main_test.go +++ b/internal/ingress/annotations/clientbodybuffersize/main_test.go @@ -57,6 +57,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/annotations/connection/main.go b/internal/ingress/annotations/connection/main.go index 9e96b6ab1..b0242ac23 100644 --- a/internal/ingress/annotations/connection/main.go +++ b/internal/ingress/annotations/connection/main.go @@ -29,15 +29,13 @@ const ( connectionProxyHeaderAnnotation = "connection-proxy-header" ) -var ( - validConnectionHeaderValue = regexp.MustCompile(`^(close|keep-alive)$`) -) +var validConnectionHeaderValue = regexp.MustCompile(`^(close|keep-alive)$`) var connectionHeadersAnnotations = parser.Annotation{ Group: "backend", Annotations: parser.AnnotationFields{ connectionProxyHeaderAnnotation: { - Validator: parser.ValidateRegex(*validConnectionHeaderValue, true), + Validator: parser.ValidateRegex(validConnectionHeaderValue, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation allows setting a specific value for "proxy_set_header Connection" directive. Right now it is restricted to "close" or "keep-alive"`, diff --git a/internal/ingress/annotations/connection/main_test.go b/internal/ingress/annotations/connection/main_test.go index a95288385..1b9361f31 100644 --- a/internal/ingress/annotations/connection/main_test.go +++ b/internal/ingress/annotations/connection/main_test.go @@ -66,6 +66,5 @@ func TestParse(t *testing.T) { if !p.Equal(testCase.expected) { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, p, testCase.annotations) } - } } diff --git a/internal/ingress/annotations/cors/main.go b/internal/ingress/annotations/cors/main.go index cc30b8405..39e02f21b 100644 --- a/internal/ingress/annotations/cors/main.go +++ b/internal/ingress/annotations/cors/main.go @@ -43,9 +43,9 @@ var ( // * Sets a group that can be (https?://)?*?.something.com:port? // * Allows this to be repeated as much as possible, and separated by comma // Otherwise it should be '*' - corsOriginRegexValidator = regexp.MustCompile(`^((((https?://)?(\*\.)?[A-Za-z0-9\-\.]*(:[0-9]+)?,?)+)|\*)?$`) + corsOriginRegexValidator = regexp.MustCompile(`^((((https?://)?(\*\.)?[A-Za-z0-9\-.]*(:\d+)?,?)+)|\*)?$`) // corsOriginRegex defines the regex for validation inside Parse - corsOriginRegex = regexp.MustCompile(`^(https?://(\*\.)?[A-Za-z0-9\-\.]*(:[0-9]+)?|\*)?$`) + corsOriginRegex = regexp.MustCompile(`^(https?://(\*\.)?[A-Za-z0-9\-.]*(:\d+)?|\*)?$`) // Method must contain valid methods list (PUT, GET, POST, BLA) // May contain or not spaces between each verb corsMethodsRegex = regexp.MustCompile(`^([A-Za-z]+,?\s?)+$`) @@ -74,7 +74,7 @@ var corsAnnotation = parser.Annotation{ Documentation: `This annotation enables Cross-Origin Resource Sharing (CORS) in an Ingress rule`, }, corsAllowOriginAnnotation: { - Validator: parser.ValidateRegex(*corsOriginRegexValidator, true), + Validator: parser.ValidateRegex(corsOriginRegexValidator, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation controls what's the accepted Origin for CORS. @@ -82,14 +82,14 @@ var corsAnnotation = parser.Annotation{ It also supports single level wildcard subdomains and follows this format: http(s)://*.foo.bar, http(s)://*.bar.foo:8080 or http(s)://*.abc.bar.foo:9000`, }, corsAllowHeadersAnnotation: { - Validator: parser.ValidateRegex(*parser.HeadersVariable, true), + Validator: parser.ValidateRegex(parser.HeadersVariable, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation controls which headers are accepted. This is a multi-valued field, separated by ',' and accepts letters, numbers, _ and -`, }, corsAllowMethodsAnnotation: { - Validator: parser.ValidateRegex(*corsMethodsRegex, true), + Validator: parser.ValidateRegex(corsMethodsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation controls which methods are accepted. @@ -102,7 +102,7 @@ var corsAnnotation = parser.Annotation{ Documentation: `This annotation controls if credentials can be passed during CORS operations.`, }, corsExposeHeadersAnnotation: { - Validator: parser.ValidateRegex(*corsExposeHeadersRegex, true), + Validator: parser.ValidateRegex(corsExposeHeadersRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation controls which headers are exposed to response. @@ -260,7 +260,7 @@ func (c cors) GetDocumentation() parser.AnnotationFields { return c.annotationConfig.Annotations } -func (a cors) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (c cors) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(c.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, corsAnnotation.Annotations) } diff --git a/internal/ingress/annotations/customhttperrors/main.go b/internal/ingress/annotations/customhttperrors/main.go index c3c9b5be3..f3c72a22f 100644 --- a/internal/ingress/annotations/customhttperrors/main.go +++ b/internal/ingress/annotations/customhttperrors/main.go @@ -31,16 +31,14 @@ const ( customHTTPErrorsAnnotation = "custom-http-errors" ) -var ( - // We accept anything between 400 and 599, on a comma separated. - arrayOfHTTPErrors = regexp.MustCompile(`^(?:[4,5][0-9][0-9],?)*$`) -) +// We accept anything between 400 and 599, on a comma separated. +var arrayOfHTTPErrors = regexp.MustCompile(`^(?:[4,5]\d{2},?)*$`) var customHTTPErrorsAnnotations = parser.Annotation{ Group: "backend", Annotations: parser.AnnotationFields{ customHTTPErrorsAnnotation: { - Validator: parser.ValidateRegex(*arrayOfHTTPErrors, true), + Validator: parser.ValidateRegex(arrayOfHTTPErrors, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `If a default backend annotation is specified on the ingress, the errors code specified on this annotation @@ -72,7 +70,7 @@ func (e customhttperrors) Parse(ing *networking.Ingress) (interface{}, error) { } cSplit := strings.Split(c, ",") - var codes []int + codes := make([]int, 0, len(cSplit)) for _, i := range cSplit { num, err := strconv.Atoi(i) if err != nil { @@ -88,7 +86,7 @@ func (e customhttperrors) GetDocumentation() parser.AnnotationFields { return e.annotationConfig.Annotations } -func (a customhttperrors) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (e customhttperrors) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(e.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, customHTTPErrorsAnnotations.Annotations) } diff --git a/internal/ingress/annotations/defaultbackend/main.go b/internal/ingress/annotations/defaultbackend/main.go index f3ca004dd..9ae44f052 100644 --- a/internal/ingress/annotations/defaultbackend/main.go +++ b/internal/ingress/annotations/defaultbackend/main.go @@ -57,14 +57,14 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // Parse parses the annotations contained in the ingress to use // a custom default backend -func (db backend) Parse(ing *networking.Ingress) (interface{}, error) { - s, err := parser.GetStringAnnotation(defaultBackendAnnotation, ing, db.annotationConfig.Annotations) +func (b backend) Parse(ing *networking.Ingress) (interface{}, error) { + s, err := parser.GetStringAnnotation(defaultBackendAnnotation, ing, b.annotationConfig.Annotations) if err != nil { return nil, err } name := fmt.Sprintf("%v/%v", ing.Namespace, s) - svc, err := db.r.GetService(name) + svc, err := b.r.GetService(name) if err != nil { return nil, fmt.Errorf("unexpected error reading service %s: %w", name, err) } @@ -72,11 +72,11 @@ func (db backend) Parse(ing *networking.Ingress) (interface{}, error) { return svc, nil } -func (db backend) GetDocumentation() parser.AnnotationFields { - return db.annotationConfig.Annotations +func (b backend) GetDocumentation() parser.AnnotationFields { + return b.annotationConfig.Annotations } -func (a backend) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (b backend) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(b.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, defaultBackendAnnotations.Annotations) } diff --git a/internal/ingress/annotations/fastcgi/main.go b/internal/ingress/annotations/fastcgi/main.go index 96dbc7159..882de5b1c 100644 --- a/internal/ingress/annotations/fastcgi/main.go +++ b/internal/ingress/annotations/fastcgi/main.go @@ -35,22 +35,20 @@ const ( fastCGIParamsAnnotation = "fastcgi-params-configmap" ) -var ( - // fast-cgi valid parameters is just a single file name (like index.php) - regexValidIndexAnnotationAndKey = regexp.MustCompile(`^[A-Za-z0-9\.\-\_]+$`) -) +// fast-cgi valid parameters is just a single file name (like index.php) +var regexValidIndexAnnotationAndKey = regexp.MustCompile(`^[A-Za-z0-9.\-\_]+$`) var fastCGIAnnotations = parser.Annotation{ Group: "fastcgi", Annotations: parser.AnnotationFields{ fastCGIIndexAnnotation: { - Validator: parser.ValidateRegex(*regexValidIndexAnnotationAndKey, true), + Validator: parser.ValidateRegex(regexValidIndexAnnotationAndKey, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation can be used to specify an index file`, }, fastCGIParamsAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation can be used to specify a ConfigMap containing the fastcgi parameters as a key/value. @@ -98,7 +96,6 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // ParseAnnotations parses the annotations contained in the ingress // rule used to indicate the fastcgiConfig. func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { - fcgiConfig := Config{} if ing.GetAnnotations() == nil { @@ -125,7 +122,7 @@ func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { cmns, cmn, err := cache.SplitMetaNamespaceKey(cm) if err != nil { - return fcgiConfig, ing_errors.LocationDenied{ + return fcgiConfig, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("error reading configmap name from annotation: %w", err), } } @@ -139,7 +136,7 @@ func (a fastcgi) Parse(ing *networking.Ingress) (interface{}, error) { cm = fmt.Sprintf("%v/%v", ing.Namespace, cmn) cmap, err := a.r.GetConfigMap(cm) if err != nil { - return fcgiConfig, ing_errors.LocationDenied{ + return fcgiConfig, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("unexpected error reading configmap %s: %w", cm, err), } } diff --git a/internal/ingress/annotations/fastcgi/main_test.go b/internal/ingress/annotations/fastcgi/main_test.go index 3296ded65..bc5e2755f 100644 --- a/internal/ingress/annotations/fastcgi/main_test.go +++ b/internal/ingress/annotations/fastcgi/main_test.go @@ -155,7 +155,6 @@ func TestParseFastCGIInvalidParamsConfigMapAnnotation(t *testing.T) { invalidConfigMapList := []string{"unknown/configMap", "unknown/config/map"} for _, configmap := range invalidConfigMapList { - data := map[string]string{} data[parser.GetAnnotationWithPrefix("fastcgi-params-configmap")] = configmap ing.SetAnnotations(data) @@ -239,11 +238,9 @@ func TestParseFastCGIParamsConfigMapAnnotationWithDifferentNS(t *testing.T) { if err == nil { t.Errorf("Different namespace configmap should return an error") } - } func TestConfigEquality(t *testing.T) { - var nilConfig *Config config := Config{ @@ -297,7 +294,6 @@ func TestConfigEquality(t *testing.T) { } func Test_fastcgi_Parse(t *testing.T) { - tests := []struct { name string index string @@ -378,7 +374,6 @@ func Test_fastcgi_Parse(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ing := buildIngress() data := map[string]string{} diff --git a/internal/ingress/annotations/globalratelimit/main.go b/internal/ingress/annotations/globalratelimit/main.go index 41f58fd57..0aec29f66 100644 --- a/internal/ingress/annotations/globalratelimit/main.go +++ b/internal/ingress/annotations/globalratelimit/main.go @@ -25,7 +25,6 @@ import ( "k8s.io/klog/v2" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" - "k8s.io/ingress-nginx/internal/ingress/errors" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/ingress-nginx/internal/net" @@ -57,7 +56,7 @@ var globalRateLimitAnnotationConfig = parser.Annotation{ Documentation: `Configures a time window (i.e 1m) that the limit is applied`, }, globalRateLimitKeyAnnotation: { - Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + Validator: parser.ValidateRegex(parser.NGINXVariable, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation Configures a key for counting the samples. Defaults to $remote_addr. @@ -123,23 +122,23 @@ func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { config := &Config{} limit, err := parser.GetIntAnnotation(globalRateLimitAnnotation, ing, a.annotationConfig.Annotations) - if err != nil && errors.IsInvalidContent(err) { + if err != nil && ing_errors.IsInvalidContent(err) { return nil, err } rawWindowSize, err := parser.GetStringAnnotation(globalRateLimitWindowAnnotation, ing, a.annotationConfig.Annotations) - if err != nil && errors.IsValidationError(err) { - return config, ing_errors.LocationDenied{ + if err != nil && ing_errors.IsValidationError(err) { + return config, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("failed to parse 'global-rate-limit-window' value: %w", err), } } - if limit == 0 || len(rawWindowSize) == 0 { + if limit == 0 || rawWindowSize == "" { return config, nil } windowSize, err := time.ParseDuration(rawWindowSize) if err != nil { - return config, ing_errors.LocationDenied{ + return config, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("failed to parse 'global-rate-limit-window' value: %w", err), } } @@ -148,12 +147,12 @@ func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { if err != nil { klog.Warningf("invalid %s, defaulting to %s", globalRateLimitKeyAnnotation, defaultKey) } - if len(key) == 0 { + if key == "" { key = defaultKey } rawIgnoredCIDRs, err := parser.GetStringAnnotation(globalRateLimitIgnoredCidrsAnnotation, ing, a.annotationConfig.Annotations) - if err != nil && errors.IsInvalidContent(err) { + if err != nil && ing_errors.IsInvalidContent(err) { return nil, err } ignoredCIDRs, err := net.ParseCIDRs(rawIgnoredCIDRs) @@ -161,7 +160,7 @@ func (a globalratelimit) Parse(ing *networking.Ingress) (interface{}, error) { return nil, err } - config.Namespace = strings.Replace(string(ing.UID), "-", "", -1) + config.Namespace = strings.ReplaceAll(string(ing.UID), "-", "") config.Limit = limit config.WindowSize = int(windowSize.Seconds()) config.Key = key diff --git a/internal/ingress/annotations/globalratelimit/main_test.go b/internal/ingress/annotations/globalratelimit/main_test.go index 5d7922666..b1a7ab71b 100644 --- a/internal/ingress/annotations/globalratelimit/main_test.go +++ b/internal/ingress/annotations/globalratelimit/main_test.go @@ -30,8 +30,10 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) -const UID = "31285d47-b150-4dcf-bd6f-12c46d769f6e" -const expectedUID = "31285d47b1504dcfbd6f12c46d769f6e" +const ( + UID = "31285d47-b150-4dcf-bd6f-12c46d769f6e" + expectedUID = "31285d47b1504dcfbd6f12c46d769f6e" +) func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ @@ -190,10 +192,19 @@ func TestGlobalRateLimiting(t *testing.T) { t.Errorf("expected error '%v' but got '%v'", testCase.expectedErr, actualErr) } - actualConfig := i.(*Config) + actualConfig, ok := i.(*Config) + if !ok { + t.Errorf("expected Config type but got %T", i) + } if !testCase.expectedConfig.Equal(actualConfig) { - expectedJSON, _ := json.Marshal(testCase.expectedConfig) - actualJSON, _ := json.Marshal(actualConfig) + expectedJSON, err := json.Marshal(testCase.expectedConfig) + if err != nil { + t.Errorf("failed to marshal expected config: %v", err) + } + actualJSON, err := json.Marshal(actualConfig) + if err != nil { + t.Errorf("failed to marshal actual config: %v", err) + } t.Errorf("%v: expected config '%s' but got '%s'", testCase.title, expectedJSON, actualJSON) } } diff --git a/internal/ingress/annotations/http2pushpreload/main.go b/internal/ingress/annotations/http2pushpreload/main.go index af9f90aa9..123940d9d 100644 --- a/internal/ingress/annotations/http2pushpreload/main.go +++ b/internal/ingress/annotations/http2pushpreload/main.go @@ -62,7 +62,7 @@ func (h2pp http2PushPreload) GetDocumentation() parser.AnnotationFields { return h2pp.annotationConfig.Annotations } -func (a http2PushPreload) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (h2pp http2PushPreload) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(h2pp.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, http2PushPreloadAnnotations.Annotations) } diff --git a/internal/ingress/annotations/ipallowlist/main.go b/internal/ingress/annotations/ipallowlist/main.go index d9d454c97..23a3bd9e7 100644 --- a/internal/ingress/annotations/ipallowlist/main.go +++ b/internal/ingress/annotations/ipallowlist/main.go @@ -96,16 +96,15 @@ func (a ipallowlist) Parse(ing *networking.Ingress) (interface{}, error) { return &SourceRange{CIDR: defaultAllowlistSourceRange}, nil } - return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDenied{ + return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDeniedError{ Reason: err, } - } values := strings.Split(val, ",") ipnets, ips, err := net.ParseIPNets(values...) if err != nil && len(ips) == 0 { - return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDenied{ + return &SourceRange{CIDR: defaultAllowlistSourceRange}, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("the annotation does not contain a valid IP address or network: %w", err), } } diff --git a/internal/ingress/annotations/ipdenylist/main.go b/internal/ingress/annotations/ipdenylist/main.go index f17ce079a..e8f02fe50 100644 --- a/internal/ingress/annotations/ipdenylist/main.go +++ b/internal/ingress/annotations/ipdenylist/main.go @@ -93,16 +93,15 @@ func (a ipdenylist) Parse(ing *networking.Ingress) (interface{}, error) { return &SourceRange{CIDR: defaultDenylistSourceRange}, nil } - return &SourceRange{CIDR: defaultDenylistSourceRange}, ing_errors.LocationDenied{ + return &SourceRange{CIDR: defaultDenylistSourceRange}, ing_errors.LocationDeniedError{ Reason: err, } - } values := strings.Split(val, ",") ipnets, ips, err := net.ParseIPNets(values...) if err != nil && len(ips) == 0 { - return &SourceRange{CIDR: defaultDenylistSourceRange}, ing_errors.LocationDenied{ + return &SourceRange{CIDR: defaultDenylistSourceRange}, ing_errors.LocationDeniedError{ Reason: fmt.Errorf("the annotation does not contain a valid IP address or network: %w", err), } } diff --git a/internal/ingress/annotations/loadbalancing/main_test.go b/internal/ingress/annotations/loadbalancing/main_test.go index b0442c37f..a5205e523 100644 --- a/internal/ingress/annotations/loadbalancing/main_test.go +++ b/internal/ingress/annotations/loadbalancing/main_test.go @@ -54,6 +54,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/annotations/log/main.go b/internal/ingress/annotations/log/main.go index ec08292a9..82d50bac3 100644 --- a/internal/ingress/annotations/log/main.go +++ b/internal/ingress/annotations/log/main.go @@ -101,7 +101,7 @@ func (l log) GetDocumentation() parser.AnnotationFields { return l.annotationConfig.Annotations } -func (a log) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (l log) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(l.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, logAnnotations.Annotations) } diff --git a/internal/ingress/annotations/log/main_test.go b/internal/ingress/annotations/log/main_test.go index df97c2e5b..950612b5b 100644 --- a/internal/ingress/annotations/log/main_test.go +++ b/internal/ingress/annotations/log/main_test.go @@ -76,7 +76,10 @@ func TestIngressAccessLogConfig(t *testing.T) { data[parser.GetAnnotationWithPrefix(enableAccessLogAnnotation)] = "false" ing.SetAnnotations(data) - log, _ := NewParser(&resolver.Mock{}).Parse(ing) + log, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } nginxLogs, ok := log.(*Config) if !ok { t.Errorf("expected a Config type") @@ -94,7 +97,10 @@ func TestIngressRewriteLogConfig(t *testing.T) { data[parser.GetAnnotationWithPrefix(enableRewriteLogAnnotation)] = "true" ing.SetAnnotations(data) - log, _ := NewParser(&resolver.Mock{}).Parse(ing) + log, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error parsing annotations %v", err) + } nginxLogs, ok := log.(*Config) if !ok { t.Errorf("expected a Config type") @@ -112,7 +118,10 @@ func TestInvalidBoolConfig(t *testing.T) { data[parser.GetAnnotationWithPrefix(enableRewriteLogAnnotation)] = "blo" ing.SetAnnotations(data) - log, _ := NewParser(&resolver.Mock{}).Parse(ing) + log, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } nginxLogs, ok := log.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/mirror/main.go b/internal/ingress/annotations/mirror/main.go index 2d417dece..d51bdd27c 100644 --- a/internal/ingress/annotations/mirror/main.go +++ b/internal/ingress/annotations/mirror/main.go @@ -34,15 +34,13 @@ const ( mirrorHostAnnotation = "mirror-host" ) -var ( - OnOffRegex = regexp.MustCompile(`^(on|off)$`) -) +var OnOffRegex = regexp.MustCompile(`^(on|off)$`) var mirrorAnnotation = parser.Annotation{ Group: "mirror", Annotations: parser.AnnotationFields{ mirrorRequestBodyAnnotation: { - Validator: parser.ValidateRegex(*OnOffRegex, true), + Validator: parser.ValidateRegex(OnOffRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `This annotation defines if the request-body should be sent to the mirror backend. Can be 'on' or 'off'`, diff --git a/internal/ingress/annotations/modsecurity/main.go b/internal/ingress/annotations/modsecurity/main.go index 5a9aaa729..80ae78937 100644 --- a/internal/ingress/annotations/modsecurity/main.go +++ b/internal/ingress/annotations/modsecurity/main.go @@ -27,7 +27,7 @@ import ( const ( modsecEnableAnnotation = "enable-modsecurity" modsecEnableOwaspCoreAnnotation = "enable-owasp-core-rules" - modesecTransactionIdAnnotation = "modsecurity-transaction-id" + modesecTransactionIDAnnotation = "modsecurity-transaction-id" modsecSnippetAnnotation = "modsecurity-snippet" ) @@ -46,8 +46,8 @@ var modsecurityAnnotation = parser.Annotation{ Risk: parser.AnnotationRiskLow, Documentation: `This annotation enables the OWASP Core Rule Set`, }, - modesecTransactionIdAnnotation: { - Validator: parser.ValidateRegex(*parser.NGINXVariable, true), + modesecTransactionIDAnnotation: { + Validator: parser.ValidateRegex(parser.NGINXVariable, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskHigh, Documentation: `This annotation enables passing an NGINX variable to ModSecurity.`, @@ -98,9 +98,9 @@ func (modsec1 *Config) Equal(modsec2 *Config) bool { } // NewParser creates a new ModSecurity annotation parser -func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { +func NewParser(r resolver.Resolver) parser.IngressAnnotation { return modSecurity{ - r: resolver, + r: r, annotationConfig: modsecurityAnnotation, } } @@ -134,10 +134,10 @@ func (a modSecurity) Parse(ing *networking.Ingress) (interface{}, error) { config.OWASPRules = false } - config.TransactionID, err = parser.GetStringAnnotation(modesecTransactionIdAnnotation, ing, a.annotationConfig.Annotations) + config.TransactionID, err = parser.GetStringAnnotation(modesecTransactionIDAnnotation, ing, a.annotationConfig.Annotations) if err != nil { if errors.IsInvalidContent(err) { - klog.Warningf("annotation %s contains invalid directive, defaulting", modesecTransactionIdAnnotation) + klog.Warningf("annotation %s contains invalid directive, defaulting", modesecTransactionIDAnnotation) } config.TransactionID = "" } diff --git a/internal/ingress/annotations/modsecurity/main_test.go b/internal/ingress/annotations/modsecurity/main_test.go index 2ddbdf7e3..0c9b3a9c7 100644 --- a/internal/ingress/annotations/modsecurity/main_test.go +++ b/internal/ingress/annotations/modsecurity/main_test.go @@ -69,8 +69,14 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) - result, _ := ap.Parse(ing) - config := result.(*Config) + result, err := ap.Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + config, ok := result.(*Config) + if !ok { + t.Errorf("unexpected type: %T", result) + } if !config.Equal(&testCase.expected) { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) } diff --git a/internal/ingress/annotations/opentelemetry/main.go b/internal/ingress/annotations/opentelemetry/main.go index a029087da..ca9108548 100644 --- a/internal/ingress/annotations/opentelemetry/main.go +++ b/internal/ingress/annotations/opentelemetry/main.go @@ -51,7 +51,7 @@ var otelAnnotations = parser.Annotation{ Documentation: `This annotation enables or disables using spans from incoming requests as parent for created ones`, }, otelOperationNameAnnotation: { - Validator: parser.ValidateRegex(*regexOperationName, true), + Validator: parser.ValidateRegex(regexOperationName, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines what operation name should be added to the span`, @@ -75,7 +75,6 @@ type Config struct { // Equal tests for equality between two Config types func (bd1 *Config) Equal(bd2 *Config) bool { - if bd1.Set != bd2.Set { return false } @@ -150,7 +149,7 @@ func (c opentelemetry) GetDocumentation() parser.AnnotationFields { return c.annotationConfig.Annotations } -func (a opentelemetry) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (c opentelemetry) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(c.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, otelAnnotations.Annotations) } diff --git a/internal/ingress/annotations/opentelemetry/main_test.go b/internal/ingress/annotations/opentelemetry/main_test.go index c78ebc8b3..e5c1de0b3 100644 --- a/internal/ingress/annotations/opentelemetry/main_test.go +++ b/internal/ingress/annotations/opentelemetry/main_test.go @@ -26,6 +26,8 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const enableAnnotation = "true" + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -73,10 +75,13 @@ func TestIngressAnnotationOpentelemetrySetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = enableAnnotation ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } openTelemetry, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -103,7 +108,10 @@ func TestIngressAnnotationOpentelemetrySetFalse(t *testing.T) { data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "false" ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } openTelemetry, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -123,8 +131,8 @@ func TestIngressAnnotationOpentelemetryTrustSetTrue(t *testing.T) { data := map[string]string{} opName := "foo-op" - data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" - data[parser.GetAnnotationWithPrefix(otelTrustSpanAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = enableAnnotation + data[parser.GetAnnotationWithPrefix(otelTrustSpanAnnotation)] = enableAnnotation data[parser.GetAnnotationWithPrefix(otelOperationNameAnnotation)] = opName ing.SetAnnotations(data) @@ -163,7 +171,7 @@ func TestIngressAnnotationOpentelemetryWithBadOpName(t *testing.T) { data := map[string]string{} opName := "fooxpto_123$la;" - data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(enableOpenTelemetryAnnotation)] = enableAnnotation data[parser.GetAnnotationWithPrefix(otelOperationNameAnnotation)] = opName ing.SetAnnotations(data) @@ -180,7 +188,10 @@ func TestIngressAnnotationOpentelemetryUnset(t *testing.T) { data := map[string]string{} ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } _, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/opentracing/main.go b/internal/ingress/annotations/opentracing/main.go index 7c8671f9d..9d7995a8a 100644 --- a/internal/ingress/annotations/opentracing/main.go +++ b/internal/ingress/annotations/opentracing/main.go @@ -89,13 +89,13 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { } } -func (s opentracing) Parse(ing *networking.Ingress) (interface{}, error) { - enabled, err := parser.GetBoolAnnotation(enableOpentracingAnnotation, ing, s.annotationConfig.Annotations) +func (o opentracing) Parse(ing *networking.Ingress) (interface{}, error) { + enabled, err := parser.GetBoolAnnotation(enableOpentracingAnnotation, ing, o.annotationConfig.Annotations) if err != nil { return &Config{}, nil } - trustSpan, err := parser.GetBoolAnnotation(opentracingTrustSpanAnnotation, ing, s.annotationConfig.Annotations) + trustSpan, err := parser.GetBoolAnnotation(opentracingTrustSpanAnnotation, ing, o.annotationConfig.Annotations) if err != nil { return &Config{Set: true, Enabled: enabled}, nil } @@ -103,11 +103,11 @@ func (s opentracing) Parse(ing *networking.Ingress) (interface{}, error) { return &Config{Set: true, Enabled: enabled, TrustSet: true, TrustEnabled: trustSpan}, nil } -func (s opentracing) GetDocumentation() parser.AnnotationFields { - return s.annotationConfig.Annotations +func (o opentracing) GetDocumentation() parser.AnnotationFields { + return o.annotationConfig.Annotations } -func (a opentracing) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (o opentracing) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(o.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, opentracingAnnotations.Annotations) } diff --git a/internal/ingress/annotations/opentracing/main_test.go b/internal/ingress/annotations/opentracing/main_test.go index b7b62ac9d..f59e60438 100644 --- a/internal/ingress/annotations/opentracing/main_test.go +++ b/internal/ingress/annotations/opentracing/main_test.go @@ -26,6 +26,8 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const enableAnnotation = "true" + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -73,10 +75,13 @@ func TestIngressAnnotationOpentracingSetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = enableAnnotation ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error %v", err) + } openTracing, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -95,7 +100,10 @@ func TestIngressAnnotationOpentracingSetFalse(t *testing.T) { data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "false" ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error %v", err) + } openTracing, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -110,11 +118,14 @@ func TestIngressAnnotationOpentracingTrustSetTrue(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = "true" - data[parser.GetAnnotationWithPrefix(opentracingTrustSpanAnnotation)] = "true" + data[parser.GetAnnotationWithPrefix(enableOpentracingAnnotation)] = enableAnnotation + data[parser.GetAnnotationWithPrefix(opentracingTrustSpanAnnotation)] = enableAnnotation ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error %v", err) + } openTracing, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") @@ -136,7 +147,11 @@ func TestIngressAnnotationOpentracingUnset(t *testing.T) { data := map[string]string{} ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } + _, ok := val.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/parser/main.go b/internal/ingress/annotations/parser/main.go index 951970e27..554ad9dde 100644 --- a/internal/ingress/annotations/parser/main.go +++ b/internal/ingress/annotations/parser/main.go @@ -118,7 +118,7 @@ func (a ingAnnotations) parseString(name string) (string, error) { val, ok := a[name] if ok { s := normalizeString(val) - if len(s) == 0 { + if s == "" { return "", errors.NewInvalidAnnotationContent(name, val) } @@ -248,13 +248,14 @@ func StringToURL(input string) (*url.URL, error) { return nil, fmt.Errorf("%v is not a valid URL: %v", input, err) } - if parsedURL.Scheme == "" { + switch { + case parsedURL.Scheme == "": return nil, fmt.Errorf("url scheme is empty") - } else if parsedURL.Host == "" { + case parsedURL.Host == "": return nil, fmt.Errorf("url host is empty") - } else if strings.Contains(parsedURL.Host, "..") { + case strings.Contains(parsedURL.Host, ".."): return nil, fmt.Errorf("invalid url host") + default: + return parsedURL, nil } - - return parsedURL, nil } diff --git a/internal/ingress/annotations/parser/main_test.go b/internal/ingress/annotations/parser/main_test.go index beca49370..0f7ecb459 100644 --- a/internal/ingress/annotations/parser/main_test.go +++ b/internal/ingress/annotations/parser/main_test.go @@ -93,14 +93,16 @@ func TestGetStringAnnotation(t *testing.T) { {"valid - A", "string", "A ", "A", false}, {"valid - B", "string", " B", "B", false}, {"empty", "string", " ", "", true}, - {"valid multiline", "string", ` + { + "valid multiline", "string", ` rewrite (?i)/arcgis/rest/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/rest/services/Utilities/Geometry/GeometryServer$1 break; rewrite (?i)/arcgis/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/services/Utilities/Geometry/GeometryServer$1 break; `, ` rewrite (?i)/arcgis/rest/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/rest/services/Utilities/Geometry/GeometryServer$1 break; rewrite (?i)/arcgis/services/Utilities/Geometry/GeometryServer(.*)$ /arcgis/services/Utilities/Geometry/GeometryServer$1 break; `, - false}, + false, + }, } data := map[string]string{} @@ -213,8 +215,10 @@ func TestGetIntAnnotation(t *testing.T) { func TestStringToURL(t *testing.T) { validURL := "http://bar.foo.com/external-auth" - validParsedURL, _ := url.Parse(validURL) - + validParsedURL, err := url.Parse(validURL) + if err != nil { + t.Errorf("unexpected error: %v", err) + } tests := []struct { title string url string diff --git a/internal/ingress/annotations/parser/validators.go b/internal/ingress/annotations/parser/validators.go index e14b486eb..ab9b4799f 100644 --- a/internal/ingress/annotations/parser/validators.go +++ b/internal/ingress/annotations/parser/validators.go @@ -52,7 +52,7 @@ var ( var IsValidRegex = regexp.MustCompile("^[/" + alphaNumericChars + regexEnabledChars + "]*$") // SizeRegex validates sizes understood by NGINX, like 1000, 100k, 1000M -var SizeRegex = regexp.MustCompile("^(?i)[0-9]+[bkmg]?$") +var SizeRegex = regexp.MustCompile(`^(?i)\d+[bkmg]?$`) // URLRegex is used to validate a URL but with only a specific set of characters: // It is alphanumericChar + ":", "?", "&" @@ -103,7 +103,7 @@ func ValidateServerName(value string) error { // ValidateRegex receives a regex as an argument and uses it to validate // the value of the field. // Annotation can define if the spaces should be trimmed before validating the value -func ValidateRegex(regex regexp.Regexp, removeSpace bool) AnnotationValidator { +func ValidateRegex(regex *regexp.Regexp, removeSpace bool) AnnotationValidator { return func(s string) error { if removeSpace { s = strings.ReplaceAll(s, " ", "") @@ -117,7 +117,7 @@ func ValidateRegex(regex regexp.Regexp, removeSpace bool) AnnotationValidator { // ValidateOptions receives an array of valid options that can be the value of annotation. // If no valid option is found, it will return an error -func ValidateOptions(options []string, caseSensitive bool, trimSpace bool) AnnotationValidator { +func ValidateOptions(options []string, caseSensitive, trimSpace bool) AnnotationValidator { return func(s string) error { if trimSpace { s = strings.TrimSpace(s) @@ -161,7 +161,7 @@ func ValidateDuration(value string) error { // ValidateNull always return null values and should not be widely used. // It is used on the "snippet" annotations, as it is up to the admin to allow its // usage, knowing it can be critical! -func ValidateNull(value string) error { +func ValidateNull(_ string) error { return nil } diff --git a/internal/ingress/annotations/parser/validators_test.go b/internal/ingress/annotations/parser/validators_test.go index 2aa6cec37..e7aeb15ca 100644 --- a/internal/ingress/annotations/parser/validators_test.go +++ b/internal/ingress/annotations/parser/validators_test.go @@ -223,7 +223,6 @@ func Test_checkAnnotation(t *testing.T) { } func TestCheckAnnotationRisk(t *testing.T) { - tests := []struct { name string annotations map[string]string diff --git a/internal/ingress/annotations/proxy/main.go b/internal/ingress/annotations/proxy/main.go index a2d10ca90..7fb1c814e 100644 --- a/internal/ingress/annotations/proxy/main.go +++ b/internal/ingress/annotations/proxy/main.go @@ -45,9 +45,7 @@ const ( proxyMaxTempFileSizeAnnotation = "proxy-max-temp-file-size" ) -var ( - validUpstreamAnnotation = regexp.MustCompile(`^((error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_403|http_404|http_429|non_idempotent|off)\s?)+$`) -) +var validUpstreamAnnotation = regexp.MustCompile(`^((error|timeout|invalid_header|http_500|http_502|http_503|http_504|http_403|http_404|http_429|non_idempotent|off)\s?)+$`) var proxyAnnotations = parser.Annotation{ Group: "backend", @@ -78,32 +76,32 @@ var proxyAnnotations = parser.Annotation{ By default proxy buffers number is set as 4`, }, proxyBufferSizeAnnotation: { - Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Validator: parser.ValidateRegex(parser.SizeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation sets the size of the buffer proxy_buffer_size used for reading the first part of the response received from the proxied server. By default proxy buffer size is set as "4k".`, }, proxyCookiePathAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation sets a text that should be changed in the path attribute of the "Set-Cookie" header fields of a proxied server response.`, }, proxyCookieDomainAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation ets a text that should be changed in the domain attribute of the "Set-Cookie" header fields of a proxied server response.`, }, proxyBodySizeAnnotation: { - Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Validator: parser.ValidateRegex(parser.SizeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows setting the maximum allowed size of a client request body.`, }, proxyNextUpstreamAnnotation: { - Validator: parser.ValidateRegex(*validUpstreamAnnotation, false), + Validator: parser.ValidateRegex(validUpstreamAnnotation, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines when the next upstream should be used. @@ -129,13 +127,13 @@ var proxyAnnotations = parser.Annotation{ Documentation: `This annotation enables or disables buffering of a client request body.`, }, proxyRedirectFromAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `The annotations proxy-redirect-from and proxy-redirect-to will set the first and second parameters of NGINX's proxy_redirect directive respectively`, }, proxyRedirectToAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `The annotations proxy-redirect-from and proxy-redirect-to will set the first and second parameters of NGINX's proxy_redirect directive respectively`, @@ -153,7 +151,7 @@ var proxyAnnotations = parser.Annotation{ Documentation: `This annotations sets the HTTP protocol version for proxying. Can be "1.0" or "1.1".`, }, proxyMaxTempFileSizeAnnotation: { - Validator: parser.ValidateRegex(*parser.SizeRegex, true), + Validator: parser.ValidateRegex(parser.SizeRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, Documentation: `This annotation defines the maximum size of a temporary file when buffering responses.`, @@ -253,7 +251,8 @@ type proxy struct { // NewParser creates a new reverse proxy configuration annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return proxy{r: r, + return proxy{ + r: r, annotationConfig: proxyAnnotations, } } diff --git a/internal/ingress/annotations/proxy/main_test.go b/internal/ingress/annotations/proxy/main_test.go index fa185551b..9446ae970 100644 --- a/internal/ingress/annotations/proxy/main_test.go +++ b/internal/ingress/annotations/proxy/main_test.go @@ -28,6 +28,12 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + off = "off" + proxyHTTPVersion = "1.0" + proxyMaxTempFileSize = "128k" +) + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -87,7 +93,7 @@ func (m mockBackend) GetDefaultBackend() defaults.Backend { ProxyNextUpstreamTimeout: 0, ProxyNextUpstreamTries: 3, ProxyRequestBuffering: "on", - ProxyBuffering: "off", + ProxyBuffering: off, ProxyHTTPVersion: "1.1", ProxyMaxTempFileSize: "1024m", } @@ -103,13 +109,13 @@ func TestProxy(t *testing.T) { data[parser.GetAnnotationWithPrefix("proxy-buffers-number")] = "8" data[parser.GetAnnotationWithPrefix("proxy-buffer-size")] = "1k" data[parser.GetAnnotationWithPrefix("proxy-body-size")] = "2k" - data[parser.GetAnnotationWithPrefix("proxy-next-upstream")] = "off" + data[parser.GetAnnotationWithPrefix("proxy-next-upstream")] = off data[parser.GetAnnotationWithPrefix("proxy-next-upstream-timeout")] = "5" data[parser.GetAnnotationWithPrefix("proxy-next-upstream-tries")] = "3" - data[parser.GetAnnotationWithPrefix("proxy-request-buffering")] = "off" + data[parser.GetAnnotationWithPrefix("proxy-request-buffering")] = off data[parser.GetAnnotationWithPrefix("proxy-buffering")] = "on" - data[parser.GetAnnotationWithPrefix("proxy-http-version")] = "1.0" - data[parser.GetAnnotationWithPrefix("proxy-max-temp-file-size")] = "128k" + data[parser.GetAnnotationWithPrefix("proxy-http-version")] = proxyHTTPVersion + data[parser.GetAnnotationWithPrefix("proxy-max-temp-file-size")] = proxyMaxTempFileSize ing.SetAnnotations(data) i, err := NewParser(mockBackend{}).Parse(ing) @@ -138,7 +144,7 @@ func TestProxy(t *testing.T) { if p.BodySize != "2k" { t.Errorf("expected 2k as body-size but returned %v", p.BodySize) } - if p.NextUpstream != "off" { + if p.NextUpstream != off { t.Errorf("expected off as next-upstream but returned %v", p.NextUpstream) } if p.NextUpstreamTimeout != 5 { @@ -147,16 +153,16 @@ func TestProxy(t *testing.T) { if p.NextUpstreamTries != 3 { t.Errorf("expected 3 as next-upstream-tries but returned %v", p.NextUpstreamTries) } - if p.RequestBuffering != "off" { + if p.RequestBuffering != off { t.Errorf("expected off as request-buffering but returned %v", p.RequestBuffering) } if p.ProxyBuffering != "on" { t.Errorf("expected on as proxy-buffering but returned %v", p.ProxyBuffering) } - if p.ProxyHTTPVersion != "1.0" { + if p.ProxyHTTPVersion != proxyHTTPVersion { t.Errorf("expected 1.0 as proxy-http-version but returned %v", p.ProxyHTTPVersion) } - if p.ProxyMaxTempFileSize != "128k" { + if p.ProxyMaxTempFileSize != proxyMaxTempFileSize { t.Errorf("expected 128k as proxy-max-temp-file-size but returned %v", p.ProxyMaxTempFileSize) } } @@ -176,8 +182,8 @@ func TestProxyComplex(t *testing.T) { data[parser.GetAnnotationWithPrefix("proxy-next-upstream-tries")] = "3" data[parser.GetAnnotationWithPrefix("proxy-request-buffering")] = "off" data[parser.GetAnnotationWithPrefix("proxy-buffering")] = "on" - data[parser.GetAnnotationWithPrefix("proxy-http-version")] = "1.0" - data[parser.GetAnnotationWithPrefix("proxy-max-temp-file-size")] = "128k" + data[parser.GetAnnotationWithPrefix("proxy-http-version")] = proxyHTTPVersion + data[parser.GetAnnotationWithPrefix("proxy-max-temp-file-size")] = proxyMaxTempFileSize ing.SetAnnotations(data) i, err := NewParser(mockBackend{}).Parse(ing) @@ -221,10 +227,10 @@ func TestProxyComplex(t *testing.T) { if p.ProxyBuffering != "on" { t.Errorf("expected on as proxy-buffering but returned %v", p.ProxyBuffering) } - if p.ProxyHTTPVersion != "1.0" { + if p.ProxyHTTPVersion != proxyHTTPVersion { t.Errorf("expected 1.0 as proxy-http-version but returned %v", p.ProxyHTTPVersion) } - if p.ProxyMaxTempFileSize != "128k" { + if p.ProxyMaxTempFileSize != proxyMaxTempFileSize { t.Errorf("expected 128k as proxy-max-temp-file-size but returned %v", p.ProxyMaxTempFileSize) } } diff --git a/internal/ingress/annotations/proxyssl/main.go b/internal/ingress/annotations/proxyssl/main.go index 40ee18aa0..0e854cd21 100644 --- a/internal/ingress/annotations/proxyssl/main.go +++ b/internal/ingress/annotations/proxyssl/main.go @@ -24,7 +24,6 @@ import ( networking "k8s.io/api/networking/v1" "k8s.io/ingress-nginx/internal/ingress/annotations/parser" - "k8s.io/ingress-nginx/internal/ingress/errors" ing_errors "k8s.io/ingress-nginx/internal/ingress/errors" "k8s.io/ingress-nginx/internal/ingress/resolver" "k8s.io/ingress-nginx/internal/k8s" @@ -42,7 +41,7 @@ const ( var ( proxySSLOnOffRegex = regexp.MustCompile(`^(on|off)$`) proxySSLProtocolRegex = regexp.MustCompile(`^(SSLv2|SSLv3|TLSv1|TLSv1\.1|TLSv1\.2|TLSv1\.3| )*$`) - proxySSLCiphersRegex = regexp.MustCompile(`^[A-Za-z0-9\+\:\_\-\!]*$`) + proxySSLCiphersRegex = regexp.MustCompile(`^[A-Za-z0-9\+:\_\-!]*$`) ) const ( @@ -59,7 +58,7 @@ var proxySSLAnnotation = parser.Annotation{ Group: "proxy", Annotations: parser.AnnotationFields{ proxySSLSecretAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation specifies a Secret with the certificate tls.crt, key tls.key in PEM format used for authentication to a proxied HTTPS server. @@ -68,14 +67,14 @@ var proxySSLAnnotation = parser.Annotation{ Just secrets on the same namespace of the ingress can be used.`, }, proxySSLCiphersAnnotation: { - Validator: parser.ValidateRegex(*proxySSLCiphersRegex, true), + Validator: parser.ValidateRegex(proxySSLCiphersRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation Specifies the enabled ciphers for requests to a proxied HTTPS server. The ciphers are specified in the format understood by the OpenSSL library.`, }, proxySSLProtocolsAnnotation: { - Validator: parser.ValidateRegex(*proxySSLProtocolRegex, true), + Validator: parser.ValidateRegex(proxySSLProtocolRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `This annotation enables the specified protocols for requests to a proxied HTTPS server.`, @@ -88,7 +87,7 @@ var proxySSLAnnotation = parser.Annotation{ This value is also passed through SNI when a connection is established to the proxied HTTPS server.`, }, proxySSLVerifyAnnotation: { - Validator: parser.ValidateRegex(*proxySSLOnOffRegex, true), + Validator: parser.ValidateRegex(proxySSLOnOffRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `This annotation enables or disables verification of the proxied HTTPS server certificate. (default: off)`, @@ -100,7 +99,7 @@ var proxySSLAnnotation = parser.Annotation{ Documentation: `This annotation Sets the verification depth in the proxied HTTPS server certificates chain. (default: 1).`, }, proxySSLServerNameAnnotation: { - Validator: parser.ValidateRegex(*proxySSLOnOffRegex, true), + Validator: parser.ValidateRegex(proxySSLOnOffRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `This annotation enables passing of the server name through TLS Server Name Indication extension (SNI, RFC 6066) when establishing a connection with the proxied HTTPS server.`, @@ -150,10 +149,11 @@ func (pssl1 *Config) Equal(pssl2 *Config) bool { } // NewParser creates a new TLS authentication annotation parser -func NewParser(resolver resolver.Resolver) parser.IngressAnnotation { +func NewParser(r resolver.Resolver) parser.IngressAnnotation { return proxySSL{ - r: resolver, - annotationConfig: proxySSLAnnotation} + r: r, + annotationConfig: proxySSLAnnotation, + } } type proxySSL struct { @@ -208,13 +208,13 @@ func (p proxySSL) Parse(ing *networking.Ingress) (interface{}, error) { proxyCert, err := p.r.GetAuthCertificate(proxysslsecret) if err != nil { e := fmt.Errorf("error obtaining certificate: %w", err) - return &Config{}, ing_errors.LocationDenied{Reason: e} + return &Config{}, ing_errors.LocationDeniedError{Reason: e} } config.AuthSSLCert = *proxyCert config.Ciphers, err = parser.GetStringAnnotation(proxySSLCiphersAnnotation, ing, p.annotationConfig.Annotations) if err != nil { - if errors.IsValidationError(err) { + if ing_errors.IsValidationError(err) { klog.Warningf("invalid value passed to proxy-ssl-ciphers, defaulting to %s", defaultProxySSLCiphers) } config.Ciphers = defaultProxySSLCiphers @@ -222,7 +222,7 @@ func (p proxySSL) Parse(ing *networking.Ingress) (interface{}, error) { config.Protocols, err = parser.GetStringAnnotation(proxySSLProtocolsAnnotation, ing, p.annotationConfig.Annotations) if err != nil { - if errors.IsValidationError(err) { + if ing_errors.IsValidationError(err) { klog.Warningf("invalid value passed to proxy-ssl-protocols, defaulting to %s", defaultProxySSLProtocols) } config.Protocols = defaultProxySSLProtocols @@ -232,7 +232,7 @@ func (p proxySSL) Parse(ing *networking.Ingress) (interface{}, error) { config.ProxySSLName, err = parser.GetStringAnnotation(proxySSLNameAnnotation, ing, p.annotationConfig.Annotations) if err != nil { - if errors.IsValidationError(err) { + if ing_errors.IsValidationError(err) { klog.Warningf("invalid value passed to proxy-ssl-name, defaulting to empty") } config.ProxySSLName = "" @@ -260,7 +260,7 @@ func (p proxySSL) GetDocumentation() parser.AnnotationFields { return p.annotationConfig.Annotations } -func (a proxySSL) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (p proxySSL) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(p.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, proxySSLAnnotation.Annotations) } diff --git a/internal/ingress/annotations/proxyssl/main_test.go b/internal/ingress/annotations/proxyssl/main_test.go index edd65343e..a20c6813d 100644 --- a/internal/ingress/annotations/proxyssl/main_test.go +++ b/internal/ingress/annotations/proxyssl/main_test.go @@ -27,6 +27,14 @@ import ( "k8s.io/ingress-nginx/internal/ingress/resolver" ) +const ( + defaultDemoSecret = "default/demo-secret" + proxySslCiphers = "HIGH:-SHA" + off = "off" + sslServerName = "w00t" + defaultProtocol = "SSLv2 TLSv1 TLSv1.2 TLSv1.3" +) + func buildIngress() *networking.Ingress { defaultBackend := networking.IngressBackend{ Service: &networking.IngressServiceBackend{ @@ -77,28 +85,27 @@ type mockSecret struct { // GetAuthCertificate from mockSecret mocks the GetAuthCertificate for backend certificate authentication func (m mockSecret) GetAuthCertificate(name string) (*resolver.AuthSSLCert, error) { - if name != "default/demo-secret" { + if name != defaultDemoSecret { return nil, errors.Errorf("there is no secret with name %v", name) } return &resolver.AuthSSLCert{ - Secret: "default/demo-secret", + Secret: defaultDemoSecret, CAFileName: "/ssl/ca.crt", CASHA: "abc", }, nil - } func TestAnnotations(t *testing.T) { ing := buildIngress() data := map[string]string{} - data[parser.GetAnnotationWithPrefix(proxySSLSecretAnnotation)] = "default/demo-secret" - data[parser.GetAnnotationWithPrefix("proxy-ssl-ciphers")] = "HIGH:-SHA" + data[parser.GetAnnotationWithPrefix(proxySSLSecretAnnotation)] = defaultDemoSecret + data[parser.GetAnnotationWithPrefix("proxy-ssl-ciphers")] = proxySslCiphers data[parser.GetAnnotationWithPrefix("proxy-ssl-name")] = "$host" data[parser.GetAnnotationWithPrefix("proxy-ssl-protocols")] = "TLSv1.3 SSLv2 TLSv1 TLSv1.2" data[parser.GetAnnotationWithPrefix("proxy-ssl-server-name")] = "on" - data[parser.GetAnnotationWithPrefix("proxy-ssl-session-reuse")] = "off" + data[parser.GetAnnotationWithPrefix("proxy-ssl-session-reuse")] = off data[parser.GetAnnotationWithPrefix("proxy-ssl-verify")] = "on" data[parser.GetAnnotationWithPrefix("proxy-ssl-verify-depth")] = "3" @@ -115,7 +122,7 @@ func TestAnnotations(t *testing.T) { t.Errorf("expected *Config but got %v", u) } - secret, err := fakeSecret.GetAuthCertificate("default/demo-secret") + secret, err := fakeSecret.GetAuthCertificate(defaultDemoSecret) if err != nil { t.Errorf("unexpected error getting secret %v", err) } @@ -123,11 +130,11 @@ func TestAnnotations(t *testing.T) { if u.AuthSSLCert.Secret != secret.Secret { t.Errorf("expected %v but got %v", secret.Secret, u.AuthSSLCert.Secret) } - if u.Ciphers != "HIGH:-SHA" { - t.Errorf("expected %v but got %v", "HIGH:-SHA", u.Ciphers) + if u.Ciphers != proxySslCiphers { + t.Errorf("expected %v but got %v", proxySslCiphers, u.Ciphers) } - if u.Protocols != "SSLv2 TLSv1 TLSv1.2 TLSv1.3" { - t.Errorf("expected %v but got %v", "SSLv2 TLSv1 TLSv1.2 TLSv1.3", u.Protocols) + if u.Protocols != defaultProtocol { + t.Errorf("expected %v but got %v", defaultProtocol, u.Protocols) } if u.Verify != "on" { t.Errorf("expected %v but got %v", "on", u.Verify) @@ -141,7 +148,6 @@ func TestAnnotations(t *testing.T) { if u.ProxySSLServerName != "on" { t.Errorf("expected %v but got %v", "on", u.ProxySSLServerName) } - } func TestInvalidAnnotations(t *testing.T) { @@ -172,11 +178,11 @@ func TestInvalidAnnotations(t *testing.T) { } // Invalid optional Annotations - data[parser.GetAnnotationWithPrefix("proxy-ssl-secret")] = "default/demo-secret" + data[parser.GetAnnotationWithPrefix("proxy-ssl-secret")] = defaultDemoSecret data[parser.GetAnnotationWithPrefix("proxy-ssl-protocols")] = "TLSv111 SSLv1" - data[parser.GetAnnotationWithPrefix("proxy-ssl-server-name")] = "w00t" - data[parser.GetAnnotationWithPrefix("proxy-ssl-session-reuse")] = "w00t" - data[parser.GetAnnotationWithPrefix("proxy-ssl-verify")] = "w00t" + data[parser.GetAnnotationWithPrefix("proxy-ssl-server-name")] = sslServerName + data[parser.GetAnnotationWithPrefix("proxy-ssl-session-reuse")] = sslServerName + data[parser.GetAnnotationWithPrefix("proxy-ssl-verify")] = sslServerName data[parser.GetAnnotationWithPrefix("proxy-ssl-verify-depth")] = "abcd" ing.SetAnnotations(data) @@ -207,21 +213,15 @@ func TestEquals(t *testing.T) { cfg1 := &Config{} cfg2 := &Config{} - // Same config - result := cfg1.Equal(cfg1) - if result != true { - t.Errorf("Expected true") - } - // compare nil - result = cfg1.Equal(nil) + result := cfg1.Equal(nil) if result != false { t.Errorf("Expected false") } // Different Certs sslCert1 := resolver.AuthSSLCert{ - Secret: "default/demo-secret", + Secret: defaultDemoSecret, CAFileName: "/ssl/ca.crt", CASHA: "abc", } @@ -240,7 +240,7 @@ func TestEquals(t *testing.T) { // Different Ciphers cfg1.Ciphers = "DEFAULT" - cfg2.Ciphers = "HIGH:-SHA" + cfg2.Ciphers = proxySslCiphers result = cfg1.Equal(cfg2) if result != false { t.Errorf("Expected false") @@ -248,22 +248,22 @@ func TestEquals(t *testing.T) { cfg2.Ciphers = "DEFAULT" // Different Protocols - cfg1.Protocols = "SSLv2 TLSv1 TLSv1.2 TLSv1.3" + cfg1.Protocols = defaultProtocol cfg2.Protocols = "SSLv3 TLSv1 TLSv1.2 TLSv1.3" result = cfg1.Equal(cfg2) if result != false { t.Errorf("Expected false") } - cfg2.Protocols = "SSLv2 TLSv1 TLSv1.2 TLSv1.3" + cfg2.Protocols = defaultProtocol // Different Verify - cfg1.Verify = "off" + cfg1.Verify = off cfg2.Verify = "on" result = cfg1.Equal(cfg2) if result != false { t.Errorf("Expected false") } - cfg2.Verify = "off" + cfg2.Verify = off // Different VerifyDepth cfg1.VerifyDepth = 1 @@ -275,13 +275,13 @@ func TestEquals(t *testing.T) { cfg2.VerifyDepth = 1 // Different ProxySSLServerName - cfg1.ProxySSLServerName = "off" + cfg1.ProxySSLServerName = off cfg2.ProxySSLServerName = "on" result = cfg1.Equal(cfg2) if result != false { t.Errorf("Expected false") } - cfg2.ProxySSLServerName = "off" + cfg2.ProxySSLServerName = off // Equal Configs result = cfg1.Equal(cfg2) diff --git a/internal/ingress/annotations/ratelimit/main.go b/internal/ingress/annotations/ratelimit/main.go index 39161a2c0..e79c698bf 100644 --- a/internal/ingress/annotations/ratelimit/main.go +++ b/internal/ingress/annotations/ratelimit/main.go @@ -288,7 +288,7 @@ func (a ratelimit) Parse(ing *networking.Ingress) (interface{}, error) { func encode(s string) string { str := base64.URLEncoding.EncodeToString([]byte(s)) - return strings.Replace(str, "=", "", -1) + return strings.ReplaceAll(str, "=", "") } func (a ratelimit) GetDocumentation() parser.AnnotationFields { diff --git a/internal/ingress/annotations/redirect/redirect.go b/internal/ingress/annotations/redirect/redirect.go index 89513c83c..b58e35171 100644 --- a/internal/ingress/annotations/redirect/redirect.go +++ b/internal/ingress/annotations/redirect/redirect.go @@ -54,14 +54,14 @@ var redirectAnnotations = parser.Annotation{ Documentation: `In some scenarios is required to redirect from www.domain.com to domain.com or vice versa. To enable this feature use this annotation.`, }, temporalRedirectAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, false), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium, as it allows arbitrary URLs that needs to be validated Documentation: `This annotation allows you to return a temporal redirect (Return Code 302) instead of sending data to the upstream. For example setting this annotation to https://www.google.com would redirect everything to Google with a Return Code of 302 (Moved Temporarily).`, }, permanentRedirectAnnotation: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, false), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, // Medium, as it allows arbitrary URLs that needs to be validated Documentation: `This annotation allows to return a permanent redirect (Return Code 301) instead of sending data to the upstream. @@ -174,11 +174,11 @@ func isValidURL(s string) error { return nil } -func (a redirect) GetDocumentation() parser.AnnotationFields { - return a.annotationConfig.Annotations +func (r redirect) GetDocumentation() parser.AnnotationFields { + return r.annotationConfig.Annotations } -func (a redirect) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (r redirect) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(r.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, redirectAnnotations.Annotations) } diff --git a/internal/ingress/annotations/redirect/redirect_test.go b/internal/ingress/annotations/redirect/redirect_test.go index 5a61f364d..bd2f98211 100644 --- a/internal/ingress/annotations/redirect/redirect_test.go +++ b/internal/ingress/annotations/redirect/redirect_test.go @@ -136,7 +136,6 @@ func TestTemporalRedirect(t *testing.T) { } func TestIsValidURL(t *testing.T) { - invalid := "ok.com" urlParse, err := url.Parse(invalid) if err != nil { diff --git a/internal/ingress/annotations/rewrite/main.go b/internal/ingress/annotations/rewrite/main.go index 84dc93bf0..cd9ed3993 100644 --- a/internal/ingress/annotations/rewrite/main.go +++ b/internal/ingress/annotations/rewrite/main.go @@ -40,7 +40,7 @@ var rewriteAnnotations = parser.Annotation{ Group: "rewrite", Annotations: parser.AnnotationFields{ rewriteTargetAnnotation: { - Validator: parser.ValidateRegex(*parser.RegexPathWithCapture, false), + Validator: parser.ValidateRegex(parser.RegexPathWithCapture, false), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows to specify the target URI where the traffic must be redirected. It can contain regular characters and captured @@ -72,7 +72,7 @@ var rewriteAnnotations = parser.Annotation{ the pathType should also be defined as 'ImplementationSpecific'.`, }, appRootAnnotation: { - Validator: parser.ValidateRegex(*parser.RegexPathWithCapture, false), + Validator: parser.ValidateRegex(parser.RegexPathWithCapture, false), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the Application Root that the Controller must redirect if it's in / context`, diff --git a/internal/ingress/annotations/rewrite/main_test.go b/internal/ingress/annotations/rewrite/main_test.go index 6b97d2e01..b68b901b4 100644 --- a/internal/ingress/annotations/rewrite/main_test.go +++ b/internal/ingress/annotations/rewrite/main_test.go @@ -120,7 +120,10 @@ func TestSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("rewrite-target")] = defRoute ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) + i, err := NewParser(mockBackend{redirect: true}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -132,7 +135,10 @@ func TestSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("rewrite-target")] = "/xpto/$1/abc/$2" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{redirect: true}).Parse(ing) + i, err = NewParser(mockBackend{redirect: true}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -144,7 +150,10 @@ func TestSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("rewrite-target")] = "/xpto/xas{445}" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{redirect: true}).Parse(ing) + i, err = NewParser(mockBackend{redirect: true}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -156,7 +165,10 @@ func TestSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("ssl-redirect")] = "false" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{redirect: false}).Parse(ing) + i, err = NewParser(mockBackend{redirect: false}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -173,7 +185,10 @@ func TestForceSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("rewrite-target")] = defRoute ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) + i, err := NewParser(mockBackend{redirect: true}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok := i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -185,7 +200,10 @@ func TestForceSSLRedirect(t *testing.T) { data[parser.GetAnnotationWithPrefix("force-ssl-redirect")] = "true" ing.SetAnnotations(data) - i, _ = NewParser(mockBackend{redirect: false}).Parse(ing) + i, err = NewParser(mockBackend{redirect: false}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok = i.(*Config) if !ok { t.Errorf("expected a Redirect type") @@ -194,6 +212,7 @@ func TestForceSSLRedirect(t *testing.T) { t.Errorf("Expected true but returned false") } } + func TestAppRoot(t *testing.T) { ap := NewParser(mockBackend{redirect: true}) @@ -241,7 +260,10 @@ func TestUseRegex(t *testing.T) { data[parser.GetAnnotationWithPrefix("use-regex")] = "true" ing.SetAnnotations(data) - i, _ := NewParser(mockBackend{redirect: true}).Parse(ing) + i, err := NewParser(mockBackend{redirect: true}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } redirect, ok := i.(*Config) if !ok { t.Errorf("expected a App Context") diff --git a/internal/ingress/annotations/satisfy/main.go b/internal/ingress/annotations/satisfy/main.go index 45187fe5c..13a4532c1 100644 --- a/internal/ingress/annotations/satisfy/main.go +++ b/internal/ingress/annotations/satisfy/main.go @@ -69,7 +69,7 @@ func (s satisfy) GetDocumentation() parser.AnnotationFields { return s.annotationConfig.Annotations } -func (a satisfy) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (s satisfy) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(s.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, satisfyAnnotations.Annotations) } diff --git a/internal/ingress/annotations/serversnippet/main_test.go b/internal/ingress/annotations/serversnippet/main_test.go index 601e11a42..72e757dc1 100644 --- a/internal/ingress/annotations/serversnippet/main_test.go +++ b/internal/ingress/annotations/serversnippet/main_test.go @@ -54,6 +54,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/annotations/serviceupstream/main.go b/internal/ingress/annotations/serviceupstream/main.go index e662f73c3..d1851bc7b 100644 --- a/internal/ingress/annotations/serviceupstream/main.go +++ b/internal/ingress/annotations/serviceupstream/main.go @@ -69,7 +69,7 @@ func (s serviceUpstream) GetDocumentation() parser.AnnotationFields { return s.annotationConfig.Annotations } -func (a serviceUpstream) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (s serviceUpstream) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(s.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, serviceUpstreamAnnotations.Annotations) } diff --git a/internal/ingress/annotations/serviceupstream/main_test.go b/internal/ingress/annotations/serviceupstream/main_test.go index 2751208ec..e6216ee5a 100644 --- a/internal/ingress/annotations/serviceupstream/main_test.go +++ b/internal/ingress/annotations/serviceupstream/main_test.go @@ -77,7 +77,10 @@ func TestIngressAnnotationServiceUpstreamEnabled(t *testing.T) { data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "true" ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } enabled, ok := val.(bool) if !ok { t.Errorf("expected a bool type") @@ -96,7 +99,10 @@ func TestIngressAnnotationServiceUpstreamSetFalse(t *testing.T) { data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "false" ing.SetAnnotations(data) - val, _ := NewParser(&resolver.Mock{}).Parse(ing) + val, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } enabled, ok := val.(bool) if !ok { t.Errorf("expected a bool type") @@ -110,7 +116,10 @@ func TestIngressAnnotationServiceUpstreamSetFalse(t *testing.T) { data = map[string]string{} ing.SetAnnotations(data) - val, _ = NewParser(&resolver.Mock{}).Parse(ing) + val, err = NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } enabled, ok = val.(bool) if !ok { t.Errorf("expected a bool type") @@ -137,7 +146,10 @@ func (m mockBackend) GetDefaultBackend() defaults.Backend { func TestParseAnnotationsWithDefaultConfig(t *testing.T) { ing := buildIngress() - val, _ := NewParser(mockBackend{}).Parse(ing) + val, err := NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } enabled, ok := val.(bool) if !ok { @@ -158,7 +170,10 @@ func TestParseAnnotationsOverridesDefaultConfig(t *testing.T) { data[parser.GetAnnotationWithPrefix(serviceUpstreamAnnotation)] = "false" ing.SetAnnotations(data) - val, _ := NewParser(mockBackend{}).Parse(ing) + val, err := NewParser(mockBackend{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error: %v", err) + } enabled, ok := val.(bool) if !ok { diff --git a/internal/ingress/annotations/sessionaffinity/main.go b/internal/ingress/annotations/sessionaffinity/main.go index 0a4a59dbc..cc2095de4 100644 --- a/internal/ingress/annotations/sessionaffinity/main.go +++ b/internal/ingress/annotations/sessionaffinity/main.go @@ -63,13 +63,15 @@ const ( // This is used to control the cookie change after request failure annotationAffinityCookieChangeOnFailure = "session-cookie-change-on-failure" + + cookieAffinity = "cookie" ) var sessionAffinityAnnotations = parser.Annotation{ Group: "affinity", Annotations: parser.AnnotationFields{ annotationAffinityType: { - Validator: parser.ValidateOptions([]string{"cookie"}, true, true), + Validator: parser.ValidateOptions([]string{cookieAffinity}, true, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `This annotation enables and sets the affinity type in all Upstreams of an Ingress. This way, a request will always be directed to the same upstream server. The only affinity type available for NGINX is cookie`, @@ -91,7 +93,7 @@ var sessionAffinityAnnotations = parser.Annotation{ Setting this to legacy will restore original canary behavior, when session affinity was ignored.`, }, annotationAffinityCookieName: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation allows to specify the name of the cookie that will be used to route the requests`, @@ -103,25 +105,25 @@ var sessionAffinityAnnotations = parser.Annotation{ Documentation: `This annotation set the cookie as secure regardless the protocol of the incoming request`, }, annotationAffinityCookieExpires: { - Validator: parser.ValidateRegex(*affinityCookieExpiresRegex, true), + Validator: parser.ValidateRegex(affinityCookieExpiresRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation is a legacy version of "session-cookie-max-age" for compatibility with older browsers, generates an "Expires" cookie directive by adding the seconds to the current date`, }, annotationAffinityCookieMaxAge: { - Validator: parser.ValidateRegex(*affinityCookieExpiresRegex, false), + Validator: parser.ValidateRegex(affinityCookieExpiresRegex, false), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation sets the time until the cookie expires`, }, annotationAffinityCookiePath: { - Validator: parser.ValidateRegex(*parser.URLIsValidRegex, true), + Validator: parser.ValidateRegex(parser.URLIsValidRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the Path that will be set on the cookie (required if your Ingress paths use regular expressions)`, }, annotationAffinityCookieDomain: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskMedium, Documentation: `This annotation defines the Domain attribute of the sticky cookie.`, @@ -149,9 +151,7 @@ var sessionAffinityAnnotations = parser.Annotation{ }, } -var ( - affinityCookieExpiresRegex = regexp.MustCompile(`(^0|-?[1-9]\d*$)`) -) +var affinityCookieExpiresRegex = regexp.MustCompile(`(^0|-?[1-9]\d*$)`) // Config describes the per ingress session affinity config type Config struct { @@ -186,6 +186,11 @@ type Cookie struct { ConditionalSameSiteNone bool `json:"conditional-samesite-none"` } +type affinity struct { + r resolver.Resolver + annotationConfig parser.Annotation +} + // cookieAffinityParse gets the annotation values related to Cookie Affinity // It also sets default values when no value or incorrect value is found func (a affinity) cookieAffinityParse(ing *networking.Ingress) *Cookie { @@ -252,11 +257,6 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { } } -type affinity struct { - r resolver.Resolver - annotationConfig parser.Annotation -} - // ParseAnnotations parses the annotations contained in the ingress // rule used to configure the affinity directives func (a affinity) Parse(ing *networking.Ingress) (interface{}, error) { @@ -279,11 +279,10 @@ func (a affinity) Parse(ing *networking.Ingress) (interface{}, error) { } switch at { - case "cookie": + case cookieAffinity: cookie = a.cookieAffinityParse(ing) default: klog.V(3).InfoS("No default affinity found", "ingress", ing.Name) - } return &Config{ diff --git a/internal/ingress/annotations/sessionaffinity/main_test.go b/internal/ingress/annotations/sessionaffinity/main_test.go index cffe57fec..cecf8cf8f 100644 --- a/internal/ingress/annotations/sessionaffinity/main_test.go +++ b/internal/ingress/annotations/sessionaffinity/main_test.go @@ -83,7 +83,11 @@ func TestIngressAffinityCookieConfig(t *testing.T) { data[parser.GetAnnotationWithPrefix(annotationAffinityCookieSecure)] = "true" ing.SetAnnotations(data) - affin, _ := NewParser(&resolver.Mock{}).Parse(ing) + affin, err := NewParser(&resolver.Mock{}).Parse(ing) + if err != nil { + t.Errorf("unexpected error parsing annotations: %v", err) + } + nginxAffinity, ok := affin.(*Config) if !ok { t.Errorf("expected a Config type") diff --git a/internal/ingress/annotations/snippet/main_test.go b/internal/ingress/annotations/snippet/main_test.go index 921afeea8..b29b2950d 100644 --- a/internal/ingress/annotations/snippet/main_test.go +++ b/internal/ingress/annotations/snippet/main_test.go @@ -54,6 +54,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/annotations/sslcipher/main.go b/internal/ingress/annotations/sslcipher/main.go index c30f12424..685ef90bf 100644 --- a/internal/ingress/annotations/sslcipher/main.go +++ b/internal/ingress/annotations/sslcipher/main.go @@ -31,10 +31,8 @@ const ( sslCipherAnnotation = "ssl-ciphers" ) -var ( - // Should cover something like "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP" - regexValidSSLCipher = regexp.MustCompile(`^[A-Za-z0-9!:+\-]*$`) -) +// Should cover something like "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP" +var regexValidSSLCipher = regexp.MustCompile(`^[A-Za-z0-9!:+\-]*$`) var sslCipherAnnotations = parser.Annotation{ Group: "backend", @@ -47,7 +45,7 @@ var sslCipherAnnotations = parser.Annotation{ This configuration specifies that server ciphers should be preferred over client ciphers when using the SSLv3 and TLS protocols.`, }, sslCipherAnnotation: { - Validator: parser.ValidateRegex(*regexValidSSLCipher, true), + Validator: parser.ValidateRegex(regexValidSSLCipher, true), Scope: parser.AnnotationScopeIngress, Risk: parser.AnnotationRiskLow, Documentation: `Using this annotation will set the ssl_ciphers directive at the server level. This configuration is active for all the paths in the host.`, @@ -104,7 +102,7 @@ func (sc sslCipher) GetDocumentation() parser.AnnotationFields { return sc.annotationConfig.Annotations } -func (a sslCipher) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (sc sslCipher) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(sc.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, sslCipherAnnotations.Annotations) } diff --git a/internal/ingress/annotations/sslcipher/main_test.go b/internal/ingress/annotations/sslcipher/main_test.go index ac6808e06..167466fef 100644 --- a/internal/ingress/annotations/sslcipher/main_test.go +++ b/internal/ingress/annotations/sslcipher/main_test.go @@ -42,8 +42,11 @@ func TestParse(t *testing.T) { expectErr bool }{ {map[string]string{annotationSSLCiphers: "ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP"}, Config{"ALL:!aNULL:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP", ""}, false}, - {map[string]string{annotationSSLCiphers: "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"}, - Config{"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", ""}, false}, + { + map[string]string{annotationSSLCiphers: "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"}, + Config{"ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256", ""}, + false, + }, {map[string]string{annotationSSLCiphers: ""}, Config{"", ""}, false}, {map[string]string{annotationSSLPreferServerCiphers: "true"}, Config{"", "on"}, false}, {map[string]string{annotationSSLPreferServerCiphers: "false"}, Config{"", "off"}, false}, diff --git a/internal/ingress/annotations/sslpassthrough/main.go b/internal/ingress/annotations/sslpassthrough/main.go index 1557d4243..c06db8715 100644 --- a/internal/ingress/annotations/sslpassthrough/main.go +++ b/internal/ingress/annotations/sslpassthrough/main.go @@ -47,7 +47,8 @@ type sslpt struct { // NewParser creates a new SSL passthrough annotation parser func NewParser(r resolver.Resolver) parser.IngressAnnotation { - return sslpt{r: r, + return sslpt{ + r: r, annotationConfig: sslPassthroughAnnotations, } } diff --git a/internal/ingress/annotations/streamsnippet/main_test.go b/internal/ingress/annotations/streamsnippet/main_test.go index 997b7be70..e8a1ff8d0 100644 --- a/internal/ingress/annotations/streamsnippet/main_test.go +++ b/internal/ingress/annotations/streamsnippet/main_test.go @@ -38,7 +38,8 @@ func TestParse(t *testing.T) { annotations map[string]string expected string }{ - {map[string]string{annotation: "server { listen: 8000; proxy_pass 127.0.0.1:80}"}, + { + map[string]string{annotation: "server { listen: 8000; proxy_pass 127.0.0.1:80}"}, "server { listen: 8000; proxy_pass 127.0.0.1:80}", }, {map[string]string{annotation: "false"}, "false"}, @@ -56,6 +57,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/annotations/upstreamhashby/main.go b/internal/ingress/annotations/upstreamhashby/main.go index bc07f70fb..25cc88b8e 100644 --- a/internal/ingress/annotations/upstreamhashby/main.go +++ b/internal/ingress/annotations/upstreamhashby/main.go @@ -41,7 +41,7 @@ var upstreamHashByAnnotations = parser.Annotation{ Group: "backend", Annotations: parser.AnnotationFields{ upstreamHashByAnnotation: { - Validator: parser.ValidateRegex(*hashByRegex, true), + Validator: parser.ValidateRegex(hashByRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskHigh, // High, this annotation allows accessing NGINX variables Documentation: `This annotation defines the nginx variable, text value or any combination thereof to use for consistent hashing. diff --git a/internal/ingress/annotations/xforwardedprefix/main.go b/internal/ingress/annotations/xforwardedprefix/main.go index fc4d5798d..530afbb01 100644 --- a/internal/ingress/annotations/xforwardedprefix/main.go +++ b/internal/ingress/annotations/xforwardedprefix/main.go @@ -31,7 +31,7 @@ var xForwardedForAnnotations = parser.Annotation{ Group: "backend", Annotations: parser.AnnotationFields{ xForwardedForPrefixAnnotation: { - Validator: parser.ValidateRegex(*parser.BasicCharsRegex, true), + Validator: parser.ValidateRegex(parser.BasicCharsRegex, true), Scope: parser.AnnotationScopeLocation, Risk: parser.AnnotationRiskLow, // Low, as it allows regexes but on a very limited set Documentation: `This annotation can be used to add the non-standard X-Forwarded-Prefix header to the upstream request with a string value`, @@ -54,15 +54,15 @@ func NewParser(r resolver.Resolver) parser.IngressAnnotation { // Parse parses the annotations contained in the ingress rule // used to add an x-forwarded-prefix header to the request -func (cbbs xforwardedprefix) Parse(ing *networking.Ingress) (interface{}, error) { - return parser.GetStringAnnotation(xForwardedForPrefixAnnotation, ing, cbbs.annotationConfig.Annotations) +func (x xforwardedprefix) Parse(ing *networking.Ingress) (interface{}, error) { + return parser.GetStringAnnotation(xForwardedForPrefixAnnotation, ing, x.annotationConfig.Annotations) } -func (cbbs xforwardedprefix) GetDocumentation() parser.AnnotationFields { - return cbbs.annotationConfig.Annotations +func (x xforwardedprefix) GetDocumentation() parser.AnnotationFields { + return x.annotationConfig.Annotations } -func (a xforwardedprefix) Validate(anns map[string]string) error { - maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel) +func (x xforwardedprefix) Validate(anns map[string]string) error { + maxrisk := parser.StringRiskToRisk(x.r.GetSecurityConfiguration().AnnotationsRiskLevel) return parser.CheckAnnotationRisk(anns, maxrisk, xForwardedForAnnotations.Annotations) } diff --git a/internal/ingress/annotations/xforwardedprefix/main_test.go b/internal/ingress/annotations/xforwardedprefix/main_test.go index d873a4412..f28b6b10e 100644 --- a/internal/ingress/annotations/xforwardedprefix/main_test.go +++ b/internal/ingress/annotations/xforwardedprefix/main_test.go @@ -54,6 +54,7 @@ func TestParse(t *testing.T) { for _, testCase := range testCases { ing.SetAnnotations(testCase.annotations) + //nolint:errcheck // Ignore the error since invalid cases will be checked with expected results result, _ := ap.Parse(ing) if result != testCase.expected { t.Errorf("expected %v but returned %v, annotations: %s", testCase.expected, result, testCase.annotations) diff --git a/internal/ingress/controller/certificate.go b/internal/ingress/controller/certificate.go index e8707c716..76aafec3c 100644 --- a/internal/ingress/controller/certificate.go +++ b/internal/ingress/controller/certificate.go @@ -100,7 +100,7 @@ func matchHostnames(pattern, host string) bool { host = strings.TrimSuffix(host, ".") pattern = strings.TrimSuffix(pattern, ".") - if len(pattern) == 0 || len(host) == 0 { + if pattern == "" || host == "" { return false } diff --git a/internal/ingress/controller/checker.go b/internal/ingress/controller/checker.go index 3229778bb..d1bf19ddf 100644 --- a/internal/ingress/controller/checker.go +++ b/internal/ingress/controller/checker.go @@ -29,7 +29,7 @@ import ( ) // Name returns the healthcheck name -func (n NGINXController) Name() string { +func (n *NGINXController) Name() string { return "nginx-ingress-controller" } diff --git a/internal/ingress/controller/checker_test.go b/internal/ingress/controller/checker_test.go index 2d63efc09..5fb6b09fd 100644 --- a/internal/ingress/controller/checker_test.go +++ b/internal/ingress/controller/checker_test.go @@ -32,7 +32,7 @@ import ( ) func TestNginxCheck(t *testing.T) { - var tests = []struct { + tests := []struct { healthzPath string }{ {"/healthz"}, @@ -42,7 +42,6 @@ func TestNginxCheck(t *testing.T) { for _, tt := range tests { testName := fmt.Sprintf("health path: %s", tt.healthzPath) t.Run(testName, func(t *testing.T) { - mux := http.NewServeMux() listener, err := tryListen("tcp", fmt.Sprintf(":%v", nginx.StatusPort)) @@ -50,7 +49,7 @@ func TestNginxCheck(t *testing.T) { t.Fatalf("creating tcp listener: %s", err) } defer listener.Close() - + //nolint:gosec // Ignore not configured ReadHeaderTimeout in testing server := &httptest.Server{ Listener: listener, Config: &http.Server{ @@ -103,10 +102,10 @@ func TestNginxCheck(t *testing.T) { } }() go func() { - cmd.Wait() //nolint:errcheck + cmd.Wait() //nolint:errcheck // Ignore the error }() - if _, err := pidFile.Write([]byte(fmt.Sprintf("%v", pid))); err != nil { + if _, err := fmt.Fprintf(pidFile, "%v", pid); err != nil { t.Errorf("unexpected error writing the pid file: %v", err) } @@ -121,7 +120,7 @@ func TestNginxCheck(t *testing.T) { }) // pollute pid file - pidFile.Write([]byte("999999")) //nolint:errcheck + pidFile.WriteString("999999") //nolint:errcheck // Ignore the error pidFile.Close() t.Run("bad pid", func(t *testing.T) { @@ -134,7 +133,7 @@ func TestNginxCheck(t *testing.T) { } func callHealthz(expErr bool, healthzPath string, mux *http.ServeMux) error { - req, err := http.NewRequest(http.MethodGet, healthzPath, nil) + req, err := http.NewRequest(http.MethodGet, healthzPath, http.NoBody) if err != nil { return fmt.Errorf("healthz error: %v", err) } diff --git a/internal/ingress/controller/config/config.go b/internal/ingress/controller/config/config.go index 60cef489a..0dafa78a2 100644 --- a/internal/ingress/controller/config/config.go +++ b/internal/ingress/controller/config/config.go @@ -29,10 +29,8 @@ import ( "k8s.io/ingress-nginx/pkg/util/runtime" ) -var ( - // EnableSSLChainCompletion Autocomplete SSL certificate chains with missing intermediate CA certificates. - EnableSSLChainCompletion = false -) +// EnableSSLChainCompletion Autocomplete SSL certificate chains with missing intermediate CA certificates. +var EnableSSLChainCompletion = false const ( // http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size @@ -91,7 +89,7 @@ const ( // Configuration represents the content of nginx.conf file type Configuration struct { - defaults.Backend `json:",squash"` //nolint:staticcheck + defaults.Backend `json:",squash"` //nolint:staticcheck // Ignore unknown JSON option "squash" error // AllowSnippetAnnotations enable users to add their own snippets via ingress annotation. // If disabled, only snippets added via ConfigMap are added to ingress. @@ -141,9 +139,9 @@ type Configuration struct { // By default access logs go to /var/log/nginx/access.log AccessLogPath string `json:"access-log-path,omitempty"` - // HttpAccessLogPath sets the path of the access logs for http context globally if enabled + // HTTPAccessLogPath sets the path of the access logs for http context globally if enabled // http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log - HttpAccessLogPath string `json:"http-access-log-path,omitempty"` + HTTPAccessLogPath string `json:"http-access-log-path,omitempty"` // StreamAccessLogPath sets the path of the access logs for stream context globally if enabled // http://nginx.org/en/docs/stream/ngx_stream_log_module.html#access_log @@ -230,19 +228,19 @@ type Configuration struct { // https://nginx.org/en/docs/http/ngx_http_v2_module.html#http2_max_field_size // HTTP2MaxFieldSize Limits the maximum size of an HPACK-compressed request header field - // NOTE: Deprecated + // Deprecated: HTTP2MaxFieldSize is deprecated. HTTP2MaxFieldSize string `json:"http2-max-field-size,omitempty"` // https://nginx.org/en/docs/http/ngx_http_v2_module.html#http2_max_header_size // HTTP2MaxHeaderSize Limits the maximum size of the entire request header list after HPACK decompression - // NOTE: Deprecated + // Deprecated: HTTP2MaxHeaderSize is deprecated. HTTP2MaxHeaderSize string `json:"http2-max-header-size,omitempty"` // http://nginx.org/en/docs/http/ngx_http_v2_module.html#http2_max_requests // HTTP2MaxRequests Sets the maximum number of requests (including push requests) that can be served // through one HTTP/2 connection, after which the next client request will lead to connection closing // and the need of establishing a new connection. - // NOTE: Deprecated + // Deprecated: HTTP2MaxRequests is deprecated. HTTP2MaxRequests int `json:"http2-max-requests,omitempty"` // http://nginx.org/en/docs/http/ngx_http_v2_module.html#http2_max_concurrent_streams @@ -552,7 +550,7 @@ type Configuration struct { UseForwardedHeaders bool `json:"use-forwarded-headers"` // Sets whether to enable the real ip module - EnableRealIp bool `json:"enable-real-ip"` + EnableRealIP bool `json:"enable-real-ip"` // Sets the header field for identifying the originating IP address of a client // Default is X-Forwarded-For @@ -621,7 +619,7 @@ type Configuration struct { // Default: 0.01 OtelSamplerRatio float32 `json:"otel-sampler-ratio"` - //OtelSamplerParentBased specifies the parent based sampler to be use for any traces created + // OtelSamplerParentBased specifies the parent based sampler to be use for any traces created // Default: true OtelSamplerParentBased bool `json:"otel-sampler-parent-based"` @@ -891,7 +889,7 @@ func NewDefault() Configuration { EnableUnderscoresInHeaders: false, ErrorLogLevel: errorLevel, UseForwardedHeaders: false, - EnableRealIp: false, + EnableRealIP: false, ForwardedForHeader: "X-Forwarded-For", ComputeFullForwardedFor: false, ProxyAddOriginalURIHeader: false, @@ -1039,41 +1037,41 @@ func NewDefault() Configuration { // TemplateConfig contains the nginx configuration to render the file nginx.conf type TemplateConfig struct { - ProxySetHeaders map[string]string - AddHeaders map[string]string - BacklogSize int - Backends []*ingress.Backend - PassthroughBackends []*ingress.SSLPassthroughBackend - Servers []*ingress.Server - TCPBackends []ingress.L4Service - UDPBackends []ingress.L4Service - HealthzURI string - Cfg Configuration - IsIPV6Enabled bool - IsSSLPassthroughEnabled bool - NginxStatusIpv4Whitelist []string - NginxStatusIpv6Whitelist []string - RedirectServers interface{} - ListenPorts *ListenPorts - PublishService *apiv1.Service - EnableMetrics bool - MaxmindEditionFiles *[]string - MonitorMaxBatchSize int - PID string - StatusPath string - StatusPort int - StreamPort int - StreamSnippets []string + ProxySetHeaders map[string]string `json:"ProxySetHeaders"` + AddHeaders map[string]string `json:"AddHeaders"` + BacklogSize int `json:"BacklogSize"` + Backends []*ingress.Backend `json:"Backends"` + PassthroughBackends []*ingress.SSLPassthroughBackend `json:"PassthroughBackends"` + Servers []*ingress.Server `json:"Servers"` + TCPBackends []ingress.L4Service `json:"TCPBackends"` + UDPBackends []ingress.L4Service `json:"UDPBackends"` + HealthzURI string `json:"HealthzURI"` + Cfg Configuration `json:"Cfg"` + IsIPV6Enabled bool `json:"IsIPV6Enabled"` + IsSSLPassthroughEnabled bool `json:"IsSSLPassthroughEnabled"` + NginxStatusIpv4Whitelist []string `json:"NginxStatusIpv4Whitelist"` + NginxStatusIpv6Whitelist []string `json:"NginxStatusIpv6Whitelist"` + RedirectServers interface{} `json:"RedirectServers"` + ListenPorts *ListenPorts `json:"ListenPorts"` + PublishService *apiv1.Service `json:"PublishService"` + EnableMetrics bool `json:"EnableMetrics"` + MaxmindEditionFiles *[]string `json:"MaxmindEditionFiles"` + MonitorMaxBatchSize int `json:"MonitorMaxBatchSize"` + PID string `json:"PID"` + StatusPath string `json:"StatusPath"` + StatusPort int `json:"StatusPort"` + StreamPort int `json:"StreamPort"` + StreamSnippets []string `json:"StreamSnippets"` } // ListenPorts describe the ports required to run the // NGINX Ingress controller type ListenPorts struct { - HTTP int - HTTPS int - Health int - Default int - SSLProxy int + HTTP int `json:"HTTP"` + HTTPS int `json:"HTTPS"` + Health int `json:"Health"` + Default int `json:"Default"` + SSLProxy int `json:"SSLProxy"` } // GlobalExternalAuth describe external authentication configuration for the diff --git a/internal/ingress/controller/controller.go b/internal/ingress/controller/controller.go index f405bdcbb..f2ad4639b 100644 --- a/internal/ingress/controller/controller.go +++ b/internal/ingress/controller/controller.go @@ -114,7 +114,7 @@ type Configuration struct { DisableCatchAll bool - IngressClassConfiguration *ingressclass.IngressClassConfiguration + IngressClassConfiguration *ingressclass.Configuration ValidationWebhook string ValidationWebhookCertPath string @@ -143,7 +143,7 @@ type Configuration struct { func getIngressPodZone(svc *apiv1.Service) string { svcKey := k8s.MetaNamespaceKey(svc) if svcZoneAnnotation, ok := svc.ObjectMeta.GetAnnotations()[apiv1.AnnotationTopologyMode]; ok { - if strings.ToLower(svcZoneAnnotation) == "auto" { + if strings.EqualFold(svcZoneAnnotation, "auto") { if foundZone, ok := k8s.IngressNodeDetails.GetLabels()[apiv1.LabelTopologyZone]; ok { klog.V(3).Infof("Svc has topology aware annotation enabled, try to use zone %q where controller pod is running for Service %q ", foundZone, svcKey) return foundZone @@ -154,7 +154,7 @@ func getIngressPodZone(svc *apiv1.Service) string { } // GetPublishService returns the Service used to set the load-balancer status of Ingresses. -func (n NGINXController) GetPublishService() *apiv1.Service { +func (n *NGINXController) GetPublishService() *apiv1.Service { s, err := n.store.GetService(n.cfg.PublishService) if err != nil { return nil @@ -189,13 +189,16 @@ func (n *NGINXController) syncIngress(interface{}) error { if !utilingress.IsDynamicConfigurationEnough(pcfg, n.runningConfig) { klog.InfoS("Configuration changes detected, backend reload required") - hash, _ := hashstructure.Hash(pcfg, hashstructure.FormatV1, &hashstructure.HashOptions{ + hash, err := hashstructure.Hash(pcfg, hashstructure.FormatV1, &hashstructure.HashOptions{ TagName: "json", }) + if err != nil { + klog.Errorf("unexpected error hashing configuration: %v", err) + } pcfg.ConfigurationChecksum = fmt.Sprintf("%v", hash) - err := n.OnUpdate(*pcfg) + err = n.OnUpdate(*pcfg) if err != nil { n.metricCollector.IncReloadErrorCount() n.metricCollector.ConfigSuccess(hash, false) @@ -263,7 +266,7 @@ func (n *NGINXController) syncIngress(interface{}) error { func (n *NGINXController) CheckWarning(ing *networking.Ingress) ([]string, error) { warnings := make([]string, 0) - var deprecatedAnnotations = sets.NewString() + deprecatedAnnotations := sets.NewString() deprecatedAnnotations.Insert( "enable-influxdb", "influxdb-measurement", @@ -335,7 +338,7 @@ func (n *NGINXController) CheckIngress(ing *networking.Ingress) error { } if n.cfg.DisableCatchAll && ing.Spec.DefaultBackend != nil { - return fmt.Errorf("This deployment is trying to create a catch-all ingress while DisableCatchAll flag is set to true. Remove '.spec.defaultBackend' or set DisableCatchAll flag to false.") + return fmt.Errorf("this deployment is trying to create a catch-all ingress while DisableCatchAll flag is set to true. Remove '.spec.defaultBackend' or set DisableCatchAll flag to false") } startRender := time.Now().UnixNano() / 1000000 cfg := n.store.GetBackendConfiguration() @@ -355,10 +358,9 @@ func (n *NGINXController) CheckIngress(ing *networking.Ingress) error { } for key, value := range ing.ObjectMeta.GetAnnotations() { - if parser.AnnotationsPrefix != parser.DefaultAnnotationsPrefix { if strings.HasPrefix(key, fmt.Sprintf("%s/", parser.DefaultAnnotationsPrefix)) { - return fmt.Errorf("This deployment has a custom annotation prefix defined. Use '%s' instead of '%s'", parser.AnnotationsPrefix, parser.DefaultAnnotationsPrefix) + return fmt.Errorf("this deployment has a custom annotation prefix defined. Use '%s' instead of '%s'", parser.AnnotationsPrefix, parser.DefaultAnnotationsPrefix) } } @@ -374,10 +376,9 @@ func (n *NGINXController) CheckIngress(ing *networking.Ingress) error { return fmt.Errorf("%s annotation cannot be used. Snippet directives are disabled by the Ingress administrator", key) } - if len(cfg.GlobalRateLimitMemcachedHost) == 0 && strings.HasPrefix(key, fmt.Sprintf("%s/%s", parser.AnnotationsPrefix, "global-rate-limit")) { + if cfg.GlobalRateLimitMemcachedHost == "" && strings.HasPrefix(key, fmt.Sprintf("%s/%s", parser.AnnotationsPrefix, "global-rate-limit")) { return fmt.Errorf("'global-rate-limit*' annotations require 'global-rate-limit-memcached-host' settings configured in the global configmap") } - } k8s.SetDefaultNGINXPathType(ing) @@ -401,7 +402,7 @@ func (n *NGINXController) CheckIngress(ing *networking.Ingress) error { startTest := time.Now().UnixNano() / 1000000 _, servers, pcfg := n.getConfiguration(ings) - err = checkOverlap(ing, allIngresses, servers) + err = checkOverlap(ing, servers) if err != nil { n.metricCollector.IncCheckErrorCount(ing.ObjectMeta.Namespace, ing.Name) return err @@ -452,7 +453,7 @@ func (n *NGINXController) getStreamServices(configmapName string, proto apiv1.Pr return []ingress.L4Service{} } - var svcs []ingress.L4Service + svcs := make([]ingress.L4Service, 0, len(configmap.Data)) var svcProxyProtocol ingress.ProxyProtocol rp := []int{ @@ -489,10 +490,10 @@ func (n *NGINXController) getStreamServices(configmapName string, proto apiv1.Pr svcProxyProtocol.Encode = false // Proxy Protocol is only compatible with TCP Services if len(nsSvcPort) >= 3 && proto == apiv1.ProtocolTCP { - if len(nsSvcPort) >= 3 && strings.ToUpper(nsSvcPort[2]) == "PROXY" { + if len(nsSvcPort) >= 3 && strings.EqualFold(nsSvcPort[2], "PROXY") { svcProxyProtocol.Decode = true } - if len(nsSvcPort) == 4 && strings.ToUpper(nsSvcPort[3]) == "PROXY" { + if len(nsSvcPort) == 4 && strings.EqualFold(nsSvcPort[3], "PROXY") { svcProxyProtocol.Encode = true } } @@ -532,6 +533,7 @@ func (n *NGINXController) getStreamServices(configmapName string, proto apiv1.Pr klog.V(3).Infof("Searching Endpoints with %v port number %d for Service %q", proto, targetPort, nsName) for i := range svc.Spec.Ports { sp := svc.Spec.Ports[i] + //nolint:gosec // Ignore G109 error if sp.Port == int32(targetPort) { if sp.Protocol == proto { endps = getEndpointsFromSlices(svc, &sp, proto, zone, n.store.GetServiceEndpointsSlices) @@ -574,7 +576,7 @@ func (n *NGINXController) getDefaultUpstream() *ingress.Backend { } svcKey := n.cfg.DefaultService - if len(svcKey) == 0 { + if svcKey == "" { upstream.Endpoints = append(upstream.Endpoints, n.DefaultEndpoint()) return upstream } @@ -690,13 +692,14 @@ func dropSnippetDirectives(anns *annotations.Ingress, ingKey string) { klog.V(3).Infof("Ingress %q tried to use stream-snippet and the annotation is disabled by the admin. Removing the annotation", ingKey) anns.StreamSnippet = "" } - } } // getBackendServers returns a list of Upstream and Server to be used by the // backend. An upstream can be used in multiple servers if the namespace, // service name and port are the same. +// +//nolint:gocyclo // Ignore function complexity error func (n *NGINXController) getBackendServers(ingresses []*ingress.Ingress) ([]*ingress.Backend, []*ingress.Server) { du := n.getDefaultUpstream() upstreams := n.createUpstreams(ingresses, du) @@ -1030,7 +1033,7 @@ func (n *NGINXController) createUpstreams(data []*ingress.Ingress, du *ingress.B // configure traffic shaping for canary if anns.Canary.Enabled { upstreams[defBackend].NoServer = true - upstreams[defBackend].TrafficShapingPolicy = newTrafficShapingPolicy(anns.Canary) + upstreams[defBackend].TrafficShapingPolicy = newTrafficShapingPolicy(&anns.Canary) } if len(upstreams[defBackend].Endpoints) == 0 { @@ -1095,7 +1098,7 @@ func (n *NGINXController) createUpstreams(data []*ingress.Ingress, du *ingress.B // configure traffic shaping for canary if anns.Canary.Enabled { upstreams[name].NoServer = true - upstreams[name].TrafficShapingPolicy = newTrafficShapingPolicy(anns.Canary) + upstreams[name].TrafficShapingPolicy = newTrafficShapingPolicy(&anns.Canary) } if len(upstreams[name].Endpoints) == 0 { @@ -1206,7 +1209,6 @@ func (n *NGINXController) serviceEndpoints(svcKey, backendPort string) ([]ingres if strconv.Itoa(int(servicePort.Port)) == backendPort || servicePort.TargetPort.String() == backendPort || servicePort.Name == backendPort { - endps := getEndpointsFromSlices(svc, &servicePort, apiv1.ProtocolTCP, zone, n.store.GetServiceEndpointsSlices) if len(endps) == 0 { klog.Warningf("Service %q does not have any active Endpoint.", svcKey) @@ -1239,8 +1241,8 @@ func (n *NGINXController) getDefaultSSLCertificate() *ingress.SSLCert { // one root location, which uses a default backend if left unspecified. func (n *NGINXController) createServers(data []*ingress.Ingress, upstreams map[string]*ingress.Backend, - du *ingress.Backend) map[string]*ingress.Server { - + du *ingress.Backend, +) map[string]*ingress.Server { servers := make(map[string]*ingress.Server, len(data)) allAliases := make(map[string][]string, len(data)) @@ -1282,7 +1284,8 @@ func (n *NGINXController) createServers(data []*ingress.Ingress, Rewrite: false, }, }, - }} + }, + } // initialize all other servers for _, ing := range data { @@ -1532,7 +1535,7 @@ func locationApplyAnnotations(loc *ingress.Location, anns *annotations.Ingress) } // OK to merge canary ingresses iff there exists one or more ingresses to potentially merge into -func nonCanaryIngressExists(ingresses []*ingress.Ingress, canaryIngresses []*ingress.Ingress) bool { +func nonCanaryIngressExists(ingresses, canaryIngresses []*ingress.Ingress) bool { return len(ingresses)-len(canaryIngresses) > 0 } @@ -1540,12 +1543,12 @@ func nonCanaryIngressExists(ingresses []*ingress.Ingress, canaryIngresses []*ing // 1) names of backends do not match and canary doesn't merge into itself // 2) primary name is not the default upstream // 3) the primary has a server -func canMergeBackend(primary *ingress.Backend, alternative *ingress.Backend) bool { +func canMergeBackend(primary, alternative *ingress.Backend) bool { return alternative != nil && primary.Name != alternative.Name && primary.Name != defUpstreamName && !primary.NoServer } // Performs the merge action and checks to ensure that one two alternative backends do not merge into each other -func mergeAlternativeBackend(ing *ingress.Ingress, priUps *ingress.Backend, altUps *ingress.Backend) bool { +func mergeAlternativeBackend(ing *ingress.Ingress, priUps, altUps *ingress.Backend) bool { if priUps.NoServer { klog.Warningf("unable to merge alternative backend %v into primary backend %v because %v is a primary backend", altUps.Name, priUps.Name, priUps.Name) @@ -1563,8 +1566,7 @@ func mergeAlternativeBackend(ing *ingress.Ingress, priUps *ingress.Backend, altU priUps.SessionAffinity.DeepCopyInto(&altUps.SessionAffinity) } - priUps.AlternativeBackends = - append(priUps.AlternativeBackends, altUps.Name) + priUps.AlternativeBackends = append(priUps.AlternativeBackends, altUps.Name) return true } @@ -1574,8 +1576,8 @@ func mergeAlternativeBackend(ing *ingress.Ingress, priUps *ingress.Backend, altU // to a backend's alternative list. // If no match is found, then the serverless backend is deleted. func mergeAlternativeBackends(ing *ingress.Ingress, upstreams map[string]*ingress.Backend, - servers map[string]*ingress.Server) { - + servers map[string]*ingress.Server, +) { // merge catch-all alternative backends if ing.Spec.DefaultBackend != nil { upsName := upstreamName(ing.Namespace, ing.Spec.DefaultBackend.Service) @@ -1585,7 +1587,6 @@ func mergeAlternativeBackends(ing *ingress.Ingress, upstreams map[string]*ingres if altUps == nil { klog.Warningf("alternative backend %s has already been removed", upsName) } else { - merged := false altEqualsPri := false @@ -1676,8 +1677,8 @@ func mergeAlternativeBackends(ing *ingress.Ingress, upstreams map[string]*ingres // extractTLSSecretName returns the name of the Secret containing a SSL // certificate for the given host name, or an empty string. func extractTLSSecretName(host string, ing *ingress.Ingress, - getLocalSSLCert func(string) (*ingress.SSLCert, error)) string { - + getLocalSSLCert func(string) (*ingress.SSLCert, error), +) string { if ing == nil { return "" } @@ -1694,7 +1695,6 @@ func extractTLSSecretName(host string, ing *ingress.Ingress, // no TLS host matching host name, try each TLS host for matching SAN or CN for _, tls := range ing.Spec.TLS { - if tls.SecretName == "" { // There's no secretName specified, so it will never be available continue @@ -1753,6 +1753,7 @@ func externalNamePorts(name string, svc *apiv1.Service) *apiv1.ServicePort { } for _, svcPort := range svc.Spec.Ports { + //nolint:gosec // Ignore G109 error if svcPort.Port != int32(port) { continue } @@ -1771,13 +1772,14 @@ func externalNamePorts(name string, svc *apiv1.Service) *apiv1.ServicePort { // ExternalName without port return &apiv1.ServicePort{ - Protocol: "TCP", + Protocol: "TCP", + //nolint:gosec // Ignore G109 error Port: int32(port), TargetPort: intstr.FromInt(port), } } -func checkOverlap(ing *networking.Ingress, ingresses []*ingress.Ingress, servers []*ingress.Server) error { +func checkOverlap(ing *networking.Ingress, servers []*ingress.Server) error { for _, rule := range ing.Spec.Rules { if rule.HTTP == nil { continue @@ -1870,7 +1872,7 @@ func (n *NGINXController) getStreamSnippets(ingresses []*ingress.Ingress) []stri } // newTrafficShapingPolicy creates new ingress.TrafficShapingPolicy instance using canary configuration -func newTrafficShapingPolicy(cfg canary.Config) ingress.TrafficShapingPolicy { +func newTrafficShapingPolicy(cfg *canary.Config) ingress.TrafficShapingPolicy { return ingress.TrafficShapingPolicy{ Weight: cfg.Weight, WeightTotal: cfg.WeightTotal, diff --git a/internal/ingress/controller/controller_test.go b/internal/ingress/controller/controller_test.go index c353d1b5e..c07fcfadf 100644 --- a/internal/ingress/controller/controller_test.go +++ b/internal/ingress/controller/controller_test.go @@ -60,51 +60,56 @@ import ( "k8s.io/ingress-nginx/pkg/util/file" ) +const ( + exampleBackend = "example-http-svc-1-80" + TRUE = "true" +) + type fakeIngressStore struct { ingresses []*ingress.Ingress configuration ngx_config.Configuration } -func (fakeIngressStore) GetIngressClass(ing *networking.Ingress, icConfig *ingressclass.IngressClassConfiguration) (string, error) { +func (fakeIngressStore) GetIngressClass(_ *networking.Ingress, _ *ingressclass.Configuration) (string, error) { return "nginx", nil } -func (fis fakeIngressStore) GetBackendConfiguration() ngx_config.Configuration { +func (fis *fakeIngressStore) GetBackendConfiguration() ngx_config.Configuration { return fis.configuration } -func (fis fakeIngressStore) GetSecurityConfiguration() defaults.SecurityConfiguration { +func (fis *fakeIngressStore) GetSecurityConfiguration() defaults.SecurityConfiguration { return defaults.SecurityConfiguration{ AnnotationsRiskLevel: fis.configuration.AnnotationsRiskLevel, AllowCrossNamespaceResources: fis.configuration.AllowCrossNamespaceResources, } } -func (fakeIngressStore) GetConfigMap(key string) (*corev1.ConfigMap, error) { +func (fakeIngressStore) GetConfigMap(_ string) (*corev1.ConfigMap, error) { return nil, fmt.Errorf("test error") } -func (fakeIngressStore) GetSecret(key string) (*corev1.Secret, error) { +func (fakeIngressStore) GetSecret(_ string) (*corev1.Secret, error) { return nil, fmt.Errorf("test error") } -func (fakeIngressStore) GetService(key string) (*corev1.Service, error) { +func (fakeIngressStore) GetService(_ string) (*corev1.Service, error) { return nil, fmt.Errorf("test error") } -func (fakeIngressStore) GetServiceEndpointsSlices(key string) ([]*discoveryv1.EndpointSlice, error) { +func (fakeIngressStore) GetServiceEndpointsSlices(_ string) ([]*discoveryv1.EndpointSlice, error) { return nil, fmt.Errorf("test error") } -func (fis fakeIngressStore) ListIngresses() []*ingress.Ingress { +func (fis *fakeIngressStore) ListIngresses() []*ingress.Ingress { return fis.ingresses } -func (fis fakeIngressStore) FilterIngresses(ingresses []*ingress.Ingress, filterFunc store.IngressFilterFunc) []*ingress.Ingress { +func (fis *fakeIngressStore) FilterIngresses(ingresses []*ingress.Ingress, _ store.IngressFilterFunc) []*ingress.Ingress { return ingresses } -func (fakeIngressStore) GetLocalSSLCert(name string) (*ingress.SSLCert, error) { +func (fakeIngressStore) GetLocalSSLCert(_ string) (*ingress.SSLCert, error) { return nil, fmt.Errorf("test error") } @@ -120,7 +125,7 @@ func (fakeIngressStore) GetDefaultBackend() defaults.Backend { return defaults.Backend{} } -func (fakeIngressStore) Run(stopCh chan struct{}) {} +func (fakeIngressStore) Run(_ chan struct{}) {} type testNginxTestCommand struct { t *testing.T @@ -129,7 +134,7 @@ type testNginxTestCommand struct { err error } -func (ntc testNginxTestCommand) ExecCommand(args ...string) *exec.Cmd { +func (ntc testNginxTestCommand) ExecCommand(_ ...string) *exec.Cmd { return nil } @@ -152,7 +157,7 @@ func (ntc testNginxTestCommand) Test(cfg string) ([]byte, error) { type fakeTemplate struct{} -func (fakeTemplate) Write(conf ngx_config.TemplateConfig) ([]byte, error) { +func (fakeTemplate) Write(conf *ngx_config.TemplateConfig) ([]byte, error) { r := []byte{} for _, s := range conf.Servers { if len(r) > 0 { @@ -196,7 +201,7 @@ func TestCheckIngress(t *testing.T) { nginx.metricCollector = metric.DummyCollector{} nginx.t = fakeTemplate{} - nginx.store = fakeIngressStore{ + nginx.store = &fakeIngressStore{ ingresses: []*ingress.Ingress{}, } @@ -226,7 +231,7 @@ func TestCheckIngress(t *testing.T) { } t.Run("When the hostname is updated", func(t *testing.T) { - nginx.store = fakeIngressStore{ + nginx.store = &fakeIngressStore{ ingresses: []*ingress.Ingress{ { Ingress: *ing, @@ -273,7 +278,7 @@ func TestCheckIngress(t *testing.T) { }) t.Run("When snippets are disabled and user tries to use snippet annotation", func(t *testing.T) { - nginx.store = fakeIngressStore{ + nginx.store = &fakeIngressStore{ ingresses: []*ingress.Ingress{}, configuration: ngx_config.Configuration{ AllowSnippetAnnotations: false, @@ -290,7 +295,7 @@ func TestCheckIngress(t *testing.T) { }) t.Run("When invalid directives are used in annotation values", func(t *testing.T) { - nginx.store = fakeIngressStore{ + nginx.store = &fakeIngressStore{ ingresses: []*ingress.Ingress{}, configuration: ngx_config.Configuration{ AnnotationValueWordBlocklist: "invalid_directive, another_directive", @@ -366,12 +371,11 @@ func TestCheckIngress(t *testing.T) { } func TestCheckWarning(t *testing.T) { - // Ensure no panic with wrong arguments - var nginx = &NGINXController{} + nginx := &NGINXController{} nginx.t = fakeTemplate{} - nginx.store = fakeIngressStore{ + nginx.store = &fakeIngressStore{ ingresses: []*ingress.Ingress{}, } @@ -390,7 +394,7 @@ func TestCheckWarning(t *testing.T) { }, } t.Run("when a deprecated annotation is used a warning should be returned", func(t *testing.T) { - ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("enable-influxdb")] = "true" + ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("enable-influxdb")] = TRUE defer func() { ing.ObjectMeta.Annotations = map[string]string{} }() @@ -407,7 +411,6 @@ func TestCheckWarning(t *testing.T) { }) t.Run("When an invalid pathType is used, a warning should be returned", func(t *testing.T) { - rules := ing.Spec.DeepCopy().Rules ing.Spec.Rules = []networking.IngressRule{ { @@ -443,8 +446,8 @@ func TestCheckWarning(t *testing.T) { } t.Run("adding invalid annotations increases the warning count", func(t *testing.T) { - ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("enable-influxdb")] = "true" - ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("secure-verify-ca-secret")] = "true" + ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("enable-influxdb")] = TRUE + ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("secure-verify-ca-secret")] = TRUE ing.ObjectMeta.Annotations[parser.GetAnnotationWithPrefix("influxdb-host")] = "blabla" defer func() { ing.ObjectMeta.Annotations = map[string]string{} @@ -472,6 +475,7 @@ func TestCheckWarning(t *testing.T) { }) } +//nolint:dupl // Ignore dupl errors for similar test case func TestMergeAlternativeBackends(t *testing.T) { testCases := map[string]struct { ingress *ingress.Ingress @@ -1537,8 +1541,8 @@ func TestExtractTLSSecretName(t *testing.T) { } } +//nolint:gocyclo // Ignore function complexity error func TestGetBackendServers(t *testing.T) { - testCases := []struct { Ingresses []*ingress.Ingress Validate func(ingresses []*ingress.Ingress, upstreams []*ingress.Backend, servers []*ingress.Server) @@ -2078,7 +2082,7 @@ func TestGetBackendServers(t *testing.T) { t.Errorf("server hostname should be 'example.com', got '%s'", s.Hostname) } - if s.Locations[0].Backend != "example-http-svc-1-80" || s.Locations[1].Backend != "example-http-svc-1-80" || s.Locations[2].Backend != "example-http-svc-1-80" { + if s.Locations[0].Backend != exampleBackend || s.Locations[1].Backend != exampleBackend || s.Locations[2].Backend != exampleBackend { t.Errorf("all location backend should be 'example-http-svc-1-80'") } @@ -2087,7 +2091,7 @@ func TestGetBackendServers(t *testing.T) { return } - if upstreams[0].Name != "example-http-svc-1-80" { + if upstreams[0].Name != exampleBackend { t.Errorf("example-http-svc-1-80 should be first upstream, got %s", upstreams[0].Name) return } @@ -2101,6 +2105,7 @@ func TestGetBackendServers(t *testing.T) { SetConfigMap: testConfigMap, }, { + //nolint:dupl // Ignore dupl errors for similar test case Ingresses: []*ingress.Ingress{ { Ingress: networking.Ingress{ @@ -2208,6 +2213,7 @@ func TestGetBackendServers(t *testing.T) { SetConfigMap: testConfigMap, }, { + //nolint:dupl // Ignore dupl errors for similar test case Ingresses: []*ingress.Ingress{ { Ingress: networking.Ingress{ @@ -2319,7 +2325,7 @@ func TestGetBackendServers(t *testing.T) { SelfLink: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/config", ns), }, Data: map[string]string{ - "proxy-ssl-location-only": "true", + "proxy-ssl-location-only": TRUE, }, } }, @@ -2380,7 +2386,7 @@ func TestGetBackendServers(t *testing.T) { SelfLink: fmt.Sprintf("/api/v1/namespaces/%s/configmaps/config", ns), }, Data: map[string]string{ - "proxy-ssl-location-only": "true", + "proxy-ssl-location-only": TRUE, }, } }, @@ -2449,7 +2455,6 @@ func TestGetBackendServers(t *testing.T) { if len(s.Locations[0].Allowlist.CIDR) != 1 || s.Locations[0].Allowlist.CIDR[0] != "10.0.0.0/24" { t.Errorf("allow list was incorrectly dropped, len should be 1 and contain 10.0.0.0/24") } - }, SetConfigMap: func(ns string) *corev1.ConfigMap { return &corev1.ConfigMap{ @@ -2520,7 +2525,7 @@ func newNGINXController(t *testing.T) *NGINXController { channels.NewRingChannel(10), false, true, - &ingressclass.IngressClassConfiguration{ + &ingressclass.Configuration{ Controller: "k8s.io/ingress-nginx", AnnotationValue: "nginx", }, @@ -2586,7 +2591,7 @@ func newDynamicNginxController(t *testing.T, setConfigMap func(string) *corev1.C channels.NewRingChannel(10), false, true, - &ingressclass.IngressClassConfiguration{ + &ingressclass.Configuration{ Controller: "k8s.io/ingress-nginx", AnnotationValue: "nginx", }, diff --git a/internal/ingress/controller/endpointslices.go b/internal/ingress/controller/endpointslices.go index ca6e595c8..4f98e3ce7 100644 --- a/internal/ingress/controller/endpointslices.go +++ b/internal/ingress/controller/endpointslices.go @@ -36,8 +36,8 @@ import ( // getEndpointsFromSlices returns a list of Endpoint structs for a given service/target port combination. func getEndpointsFromSlices(s *corev1.Service, port *corev1.ServicePort, proto corev1.Protocol, zoneForHints string, - getServiceEndpointsSlices func(string) ([]*discoveryv1.EndpointSlice, error)) []ingress.Endpoint { - + getServiceEndpointsSlices func(string) ([]*discoveryv1.EndpointSlice, error), +) []ingress.Endpoint { upsServers := []ingress.Endpoint{} if s == nil || port == nil { @@ -94,7 +94,7 @@ func getEndpointsFromSlices(s *corev1.Service, port *corev1.ServicePort, proto c if !reflect.DeepEqual(*epPort.Protocol, proto) { continue } - var targetPort int32 = 0 + var targetPort int32 if port.Name == "" { // port.Name is optional if there is only one port targetPort = *epPort.Port diff --git a/internal/ingress/controller/endpointslices_test.go b/internal/ingress/controller/endpointslices_test.go index b61e9a4f3..69ef3ef1b 100644 --- a/internal/ingress/controller/endpointslices_test.go +++ b/internal/ingress/controller/endpointslices_test.go @@ -27,6 +27,7 @@ import ( "k8s.io/ingress-nginx/pkg/apis/ingress" ) +//nolint:dupl // Ignore dupl errors for similar test case func TestGetEndpointsFromSlices(t *testing.T) { tests := []struct { name string diff --git a/internal/ingress/controller/ingressclass/ingressclass.go b/internal/ingress/controller/ingressclass/ingressclass.go index 95bd98d0f..90c6a4d67 100644 --- a/internal/ingress/controller/ingressclass/ingressclass.go +++ b/internal/ingress/controller/ingressclass/ingressclass.go @@ -29,9 +29,9 @@ const ( DefaultAnnotationValue = "nginx" ) -// IngressClassConfiguration defines the various aspects of IngressClass parsing +// Configuration defines the various aspects of IngressClass parsing // and how the controller should behave in each case -type IngressClassConfiguration struct { +type Configuration struct { // Controller defines the controller value this daemon watch to. // Defaults to "k8s.io/ingress-nginx" defined in flags Controller string @@ -45,7 +45,7 @@ type IngressClassConfiguration struct { // IgnoreIngressClass defines if Controller should ignore the IngressClass Object if no permissions are // granted on IngressClass IgnoreIngressClass bool - //IngressClassByName defines if the Controller should watch for Ingress Classes by + // IngressClassByName defines if the Controller should watch for Ingress Classes by // .metadata.name together with .spec.Controller IngressClassByName bool } diff --git a/internal/ingress/controller/nginx.go b/internal/ingress/controller/nginx.go index 6c25aa34f..30f785586 100644 --- a/internal/ingress/controller/nginx.go +++ b/internal/ingress/controller/nginx.go @@ -113,7 +113,7 @@ func NewNGINXController(config *Configuration, mc metric.Collector) *NGINXContro if n.cfg.ValidationWebhook != "" { n.validationWebhookServer = &http.Server{ Addr: config.ValidationWebhook, - //G112 (CWE-400): Potential Slowloris Attack + // G112 (CWE-400): Potential Slowloris Attack ReadHeaderTimeout: 10 * time.Second, Handler: adm_controller.NewAdmissionControllerServer(&adm_controller.IngressAdmission{Checker: n}), TLSConfig: ssl.NewTLSListener(n.cfg.ValidationWebhookCertPath, n.cfg.ValidationWebhookKeyPath).TLSConfig(), @@ -429,7 +429,7 @@ func (n *NGINXController) start(cmd *exec.Cmd) { } // DefaultEndpoint returns the default endpoint to be use as default server that returns 404. -func (n NGINXController) DefaultEndpoint() ingress.Endpoint { +func (n *NGINXController) DefaultEndpoint() ingress.Endpoint { return ingress.Endpoint{ Address: "127.0.0.1", Port: fmt.Sprintf("%v", n.cfg.ListenPorts.Default), @@ -438,8 +438,9 @@ func (n NGINXController) DefaultEndpoint() ingress.Endpoint { } // generateTemplate returns the nginx configuration file content -func (n NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressCfg ingress.Configuration) ([]byte, error) { - +// +//nolint:gocritic // the cfg shouldn't be changed, and shouldn't be mutated by other processes while being rendered. +func (n *NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressCfg ingress.Configuration) ([]byte, error) { if n.cfg.EnableSSLPassthrough { servers := []*tcpproxy.TCPServer{} for _, pb := range ingressCfg.PassthroughBackends { @@ -458,6 +459,7 @@ func (n NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressC } } else { for _, sp := range svc.Spec.Ports { + //nolint:gosec // Ignore G109 error if sp.Port == int32(port) { port = int(sp.Port) break @@ -563,7 +565,7 @@ func (n NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressC if err != nil { klog.Warningf("Error reading Secret %q from local store: %v", secretName, err) } else { - nsSecName := strings.Replace(secretName, "/", "-", -1) + nsSecName := strings.ReplaceAll(secretName, "/", "-") dh, ok := secret.Data["dhparam.pem"] if ok { pemFileName, err := ssl.AddOrUpdateDHParam(nsSecName, dh) @@ -589,7 +591,7 @@ func (n NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressC } } - tc := ngx_config.TemplateConfig{ + tc := &ngx_config.TemplateConfig{ ProxySetHeaders: setHeaders, AddHeaders: addHeaders, BacklogSize: sysctlSomaxconn(), @@ -623,7 +625,7 @@ func (n NGINXController) generateTemplate(cfg ngx_config.Configuration, ingressC // testTemplate checks if the NGINX configuration inside the byte array is valid // running the command "nginx -t" using a temporal file. -func (n NGINXController) testTemplate(cfg []byte) error { +func (n *NGINXController) testTemplate(cfg []byte) error { if len(cfg) == 0 { return fmt.Errorf("invalid NGINX configuration (empty)") } @@ -658,6 +660,8 @@ Error: %v // changes were detected. The received backend Configuration is merged with the // configuration ConfigMap before generating the final configuration file. // Returns nil in case the backend was successfully reloaded. +// +//nolint:gocritic // the cfg shouldn't be changed, and shouldn't be mutated by other processes while being rendered. func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error { cfg := n.store.GetBackendConfiguration() cfg.Resolver = n.resolver @@ -667,12 +671,12 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error { return err } - err = createOpentracingCfg(cfg) + err = createOpentracingCfg(&cfg) if err != nil { return err } - err = createOpentelemetryCfg(cfg) + err = createOpentelemetryCfg(&cfg) if err != nil { return err } @@ -683,7 +687,10 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error { } if klog.V(2).Enabled() { - src, _ := os.ReadFile(cfgPath) + src, err := os.ReadFile(cfgPath) + if err != nil { + return err + } if !bytes.Equal(src, content) { tmpfile, err := os.CreateTemp("", "new-nginx-cfg") if err != nil { @@ -694,11 +701,14 @@ func (n *NGINXController) OnUpdate(ingressCfg ingress.Configuration) error { if err != nil { return err } - + //nolint:gosec //Ignore G204 error diffOutput, err := exec.Command("diff", "-I", "'# Configuration.*'", "-u", cfgPath, tmpfile.Name()).CombinedOutput() if err != nil { if exitError, ok := err.(*exec.ExitError); ok { - ws := exitError.Sys().(syscall.WaitStatus) + ws, ok := exitError.Sys().(syscall.WaitStatus) + if !ok { + klog.Errorf("unexpected type: %T", exitError.Sys()) + } if ws.ExitStatus() == 2 { klog.Warningf("Failed to executing diff command: %v", err) } @@ -828,9 +838,10 @@ func (n *NGINXController) configureDynamically(pcfg *ingress.Configuration) erro return nil } -func updateStreamConfiguration(TCPEndpoints []ingress.L4Service, UDPEndpoints []ingress.L4Service) error { +func updateStreamConfiguration(tcpEndpoints, udpEndpoints []ingress.L4Service) error { streams := make([]ingress.Backend, 0) - for _, ep := range TCPEndpoints { + for i := range tcpEndpoints { + ep := &tcpEndpoints[i] var service *apiv1.Service if ep.Service != nil { service = &apiv1.Service{Spec: ep.Service.Spec} @@ -844,7 +855,8 @@ func updateStreamConfiguration(TCPEndpoints []ingress.L4Service, UDPEndpoints [] Service: service, }) } - for _, ep := range UDPEndpoints { + for i := range udpEndpoints { + ep := &udpEndpoints[i] var service *apiv1.Service if ep.Service != nil { service = &apiv1.Service{Spec: ep.Service.Spec} @@ -1034,7 +1046,7 @@ ratio = {{ .OtelSamplerRatio }} parent_based = {{ .OtelSamplerParentBased }} ` -func datadogOpentracingCfg(cfg ngx_config.Configuration) (string, error) { +func datadogOpentracingCfg(cfg *ngx_config.Configuration) (string, error) { m := map[string]interface{}{ "service": cfg.DatadogServiceName, "agent_host": cfg.DatadogCollectorHost, @@ -1058,7 +1070,7 @@ func datadogOpentracingCfg(cfg ngx_config.Configuration) (string, error) { return string(buf), nil } -func opentracingCfgFromTemplate(cfg ngx_config.Configuration, tmplName string, tmplText string) (string, error) { +func opentracingCfgFromTemplate(cfg *ngx_config.Configuration, tmplName, tmplText string) (string, error) { tmpl, err := template.New(tmplName).Parse(tmplText) if err != nil { return "", err @@ -1073,17 +1085,18 @@ func opentracingCfgFromTemplate(cfg ngx_config.Configuration, tmplName string, t return tmplBuf.String(), nil } -func createOpentracingCfg(cfg ngx_config.Configuration) error { +func createOpentracingCfg(cfg *ngx_config.Configuration) error { var configData string var err error - if cfg.ZipkinCollectorHost != "" { + switch { + case cfg.ZipkinCollectorHost != "": configData, err = opentracingCfgFromTemplate(cfg, "zipkin", zipkinTmpl) - } else if cfg.JaegerCollectorHost != "" || cfg.JaegerEndpoint != "" { + case cfg.JaegerCollectorHost != "" || cfg.JaegerEndpoint != "": configData, err = opentracingCfgFromTemplate(cfg, "jaeger", jaegerTmpl) - } else if cfg.DatadogCollectorHost != "" { + case cfg.DatadogCollectorHost != "": configData, err = datadogOpentracingCfg(cfg) - } else { + default: configData = "{}" } @@ -1097,8 +1110,7 @@ func createOpentracingCfg(cfg ngx_config.Configuration) error { return os.WriteFile("/etc/nginx/opentracing.json", []byte(expanded), file.ReadWriteByUser) } -func createOpentelemetryCfg(cfg ngx_config.Configuration) error { - +func createOpentelemetryCfg(cfg *ngx_config.Configuration) error { tmpl, err := template.New("otel").Parse(otelTmpl) if err != nil { return err @@ -1123,7 +1135,10 @@ func cleanTempNginxCfg() error { return filepath.SkipDir } - dur, _ := time.ParseDuration("-5m") + dur, err := time.ParseDuration("-5m") + if err != nil { + return err + } fiveMinutesAgo := time.Now().Add(dur) if strings.HasPrefix(info.Name(), tempNginxPattern) && info.ModTime().Before(fiveMinutesAgo) { files = append(files, path) diff --git a/internal/ingress/controller/nginx_test.go b/internal/ingress/controller/nginx_test.go index 56eb0f324..c68b0b188 100644 --- a/internal/ingress/controller/nginx_test.go +++ b/internal/ingress/controller/nginx_test.go @@ -58,6 +58,7 @@ func TestConfigureDynamically(t *testing.T) { server := &httptest.Server{ Listener: listener, + //nolint:gosec // Ignore not configured ReadHeaderTimeout in testing Config: &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) @@ -76,23 +77,17 @@ func TestConfigureDynamically(t *testing.T) { switch r.URL.Path { case "/configuration/backends": - { - if strings.Contains(body, "target") { - t.Errorf("unexpected target reference in JSON content: %v", body) - } + if strings.Contains(body, "target") { + t.Errorf("unexpected target reference in JSON content: %v", body) + } - if !strings.Contains(body, "service") { - t.Errorf("service reference should be present in JSON content: %v", body) - } + if !strings.Contains(body, "service") { + t.Errorf("service reference should be present in JSON content: %v", body) } case "/configuration/general": - { - } case "/configuration/servers": - { - if !strings.Contains(body, `{"certificates":{},"servers":{"myapp.fake":"-1"}}`) { - t.Errorf("should be present in JSON content: %v", body) - } + if !strings.Contains(body, `{"certificates":{},"servers":{"myapp.fake":"-1"}}`) { + t.Errorf("should be present in JSON content: %v", body) } default: t.Errorf("unknown request to %s", r.URL.Path) @@ -218,6 +213,7 @@ func TestConfigureCertificates(t *testing.T) { server := &httptest.Server{ Listener: listener, + //nolint:gosec // Ignore not configured ReadHeaderTimeout in testing Config: &http.Server{ Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) @@ -414,6 +410,7 @@ func TestCleanTempNginxCfg(t *testing.T) { } } +//nolint:unparam // Ingnore `network` always receives `"tcp"` error func tryListen(network, address string) (l net.Listener, err error) { condFunc := func() (bool, error) { l, err = net.Listen(network, address) diff --git a/internal/ingress/controller/process/nginx.go b/internal/ingress/controller/process/nginx.go index 70227ac2e..fdf501616 100644 --- a/internal/ingress/controller/process/nginx.go +++ b/internal/ingress/controller/process/nginx.go @@ -30,7 +30,10 @@ func IsRespawnIfRequired(err error) bool { return false } - waitStatus := exitError.Sys().(syscall.WaitStatus) + waitStatus, ok := exitError.Sys().(syscall.WaitStatus) + if !ok { + return false + } klog.Warningf(` ------------------------------------------------------------------------------- NGINX master process died (%v): %v diff --git a/internal/ingress/controller/status.go b/internal/ingress/controller/status.go index 3b0a41ab8..e061b2cb7 100644 --- a/internal/ingress/controller/status.go +++ b/internal/ingress/controller/status.go @@ -50,7 +50,7 @@ func setupLeaderElection(config *leaderElectionConfig) { var cancelContext context.CancelFunc - var newLeaderCtx = func(ctx context.Context) context.CancelFunc { + newLeaderCtx := func(ctx context.Context) context.CancelFunc { // allow to cancel the context in case we stop being the leader leaderCtx, cancel := context.WithCancel(ctx) go elector.Run(leaderCtx) @@ -86,8 +86,10 @@ func setupLeaderElection(config *leaderElectionConfig) { } broadcaster := record.NewBroadcaster() - hostname, _ := os.Hostname() - + hostname, err := os.Hostname() + if err != nil { + klog.Errorf("unexpected error getting hostname: %v", err) + } recorder := broadcaster.NewRecorder(scheme.Scheme, apiv1.EventSource{ Component: "ingress-leader-elector", Host: hostname, @@ -107,7 +109,7 @@ func setupLeaderElection(config *leaderElectionConfig) { ttl := 30 * time.Second - elector, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{ + elector, err = leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{ Lock: lock, LeaseDuration: ttl, RenewDeadline: ttl / 2, diff --git a/internal/ingress/controller/store/backend_ssl.go b/internal/ingress/controller/store/backend_ssl.go index 6f0fcf189..81b508cd2 100644 --- a/internal/ingress/controller/store/backend_ssl.go +++ b/internal/ingress/controller/store/backend_ssl.go @@ -88,10 +88,11 @@ func (s *k8sStore) getPemCertificate(secretName string) (*ingress.SSLCert, error auth := secret.Data["auth"] // namespace/secretName -> namespace-secretName - nsSecName := strings.Replace(secretName, "/", "-", -1) + nsSecName := strings.ReplaceAll(secretName, "/", "-") var sslCert *ingress.SSLCert - if okcert && okkey { + switch { + case okcert && okkey: if cert == nil { return nil, fmt.Errorf("key 'tls.crt' missing from Secret %q", secretName) } @@ -144,7 +145,7 @@ func (s *k8sStore) getPemCertificate(secretName string) (*ingress.SSLCert, error } klog.V(3).InfoS(msg) - } else if len(ca) > 0 { + case len(ca) > 0: sslCert, err = ssl.CreateCACert(ca) if err != nil { return nil, fmt.Errorf("unexpected error creating SSL Cert: %v", err) @@ -166,7 +167,7 @@ func (s *k8sStore) getPemCertificate(secretName string) (*ingress.SSLCert, error // makes this secret in 'syncSecret' to be used for Certificate Authentication // this does not enable Certificate Authentication klog.V(3).InfoS("Configuring Secret for TLS authentication", "secret", secretName) - } else { + default: if auth != nil { return nil, ErrSecretForAuth } diff --git a/internal/ingress/controller/store/endpointslice.go b/internal/ingress/controller/store/endpointslice.go index 78d088695..61bc63ae7 100644 --- a/internal/ingress/controller/store/endpointslice.go +++ b/internal/ingress/controller/store/endpointslice.go @@ -38,7 +38,7 @@ func (s *EndpointSliceLister) MatchByKey(key string) ([]*discoveryv1.EndpointSli keyNsLen = 0 } else { // count '/' char - keyNsLen += 1 + keyNsLen++ } // filter endpointSlices owned by svc for _, listKey := range s.ListKeys() { diff --git a/internal/ingress/controller/store/endpointslice_test.go b/internal/ingress/controller/store/endpointslice_test.go index 1342575ae..5d423a3a6 100644 --- a/internal/ingress/controller/store/endpointslice_test.go +++ b/internal/ingress/controller/store/endpointslice_test.go @@ -87,7 +87,6 @@ func TestEndpointSliceLister(t *testing.T) { t.Errorf("unexpected error %v", err) } eps, err := el.MatchByKey(key) - if err != nil { t.Errorf("unexpeted error %v", err) } diff --git a/internal/ingress/controller/store/store.go b/internal/ingress/controller/store/store.go index c11e35d76..918dfd41a 100644 --- a/internal/ingress/controller/store/store.go +++ b/internal/ingress/controller/store/store.go @@ -105,7 +105,7 @@ type Storer interface { Run(stopCh chan struct{}) // GetIngressClass validates given ingress against ingress class configuration and returns the ingress class. - GetIngressClass(ing *networkingv1.Ingress, icConfig *ingressclass.IngressClassConfiguration) (string, error) + GetIngressClass(ing *networkingv1.Ingress, icConfig *ingressclass.Configuration) (string, error) } // EventType type of event associated with an informer @@ -242,7 +242,9 @@ type k8sStore struct { defaultSSLCertificate string } -// New creates a new object store to be used in the ingress controller +// New creates a new object store to be used in the ingress controller. +// +//nolint:gocyclo // Ignore function complexity error. func New( namespace string, namespaceSelector labels.Selector, @@ -252,9 +254,9 @@ func New( updateCh *channels.RingChannel, disableCatchAll bool, deepInspector bool, - icConfig *ingressclass.IngressClassConfiguration, - disableSyncEvents bool) Storer { - + icConfig *ingressclass.Configuration, + disableSyncEvents bool, +) Storer { store := &k8sStore{ informers: &Informer{}, listers: &Lister{}, @@ -474,7 +476,8 @@ func New( _, errOld = store.GetIngressClass(oldIng, icConfig) classCur, errCur = store.GetIngressClass(curIng, icConfig) } - if errOld != nil && errCur == nil { + switch { + case errOld != nil && errCur == nil: if hasCatchAllIngressRule(curIng.Spec) && disableCatchAll { klog.InfoS("ignoring update for catch-all ingress because of --disable-catch-all", "ingress", klog.KObj(curIng)) return @@ -482,11 +485,11 @@ func New( klog.InfoS("creating ingress", "ingress", klog.KObj(curIng), "ingressclass", classCur) recorder.Eventf(curIng, corev1.EventTypeNormal, "Sync", "Scheduled for sync") - } else if errOld == nil && errCur != nil { + case errOld == nil && errCur != nil: klog.InfoS("removing ingress because of unknown ingressclass", "ingress", klog.KObj(curIng)) ingDeleteHandler(old) return - } else if errCur == nil && !reflect.DeepEqual(old, cur) { + case errCur == nil && !reflect.DeepEqual(old, cur): if hasCatchAllIngressRule(curIng.Spec) && disableCatchAll { klog.InfoS("ignoring update for catch-all ingress and delete old one because of --disable-catch-all", "ingress", klog.KObj(curIng)) ingDeleteHandler(old) @@ -494,7 +497,7 @@ func New( } recorder.Eventf(curIng, corev1.EventTypeNormal, "Sync", "Scheduled for sync") - } else { + default: klog.V(3).InfoS("No changes on ingress. Skipping update", "ingress", klog.KObj(curIng)) return } @@ -519,7 +522,10 @@ func New( ingressClassEventHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - ingressclass := obj.(*networkingv1.IngressClass) + ingressclass, ok := obj.(*networkingv1.IngressClass) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } foundClassByName := false if icConfig.IngressClassByName && ingressclass.Name == icConfig.AnnotationValue { klog.InfoS("adding ingressclass as ingress-class-by-name is configured", "ingressclass", klog.KObj(ingressclass)) @@ -541,7 +547,10 @@ func New( } }, DeleteFunc: func(obj interface{}) { - ingressclass := obj.(*networkingv1.IngressClass) + ingressclass, ok := obj.(*networkingv1.IngressClass) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } if ingressclass.Spec.Controller != icConfig.Controller { klog.InfoS("ignoring ingressclass as the spec.controller is not the same of this ingress", "ingressclass", klog.KObj(ingressclass)) return @@ -557,8 +566,14 @@ func New( } }, UpdateFunc: func(old, cur interface{}) { - oic := old.(*networkingv1.IngressClass) - cic := cur.(*networkingv1.IngressClass) + oic, ok := old.(*networkingv1.IngressClass) + if !ok { + klog.Errorf("unexpected type: %T", old) + } + cic, ok := cur.(*networkingv1.IngressClass) + if !ok { + klog.Errorf("unexpected type: %T", cur) + } if cic.Spec.Controller != icConfig.Controller { klog.InfoS("ignoring ingressclass as the spec.controller is not the same of this ingress", "ingressclass", klog.KObj(cic)) return @@ -581,7 +596,10 @@ func New( secrEventHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - sec := obj.(*corev1.Secret) + sec, ok := obj.(*corev1.Secret) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } key := k8s.MetaNamespaceKey(sec) if store.defaultSSLCertificate == key { @@ -608,7 +626,10 @@ func New( }, UpdateFunc: func(old, cur interface{}) { if !reflect.DeepEqual(old, cur) { - sec := cur.(*corev1.Secret) + sec, ok := cur.(*corev1.Secret) + if !ok { + klog.Errorf("unexpected type: %T", cur) + } key := k8s.MetaNamespaceKey(sec) if !watchedNamespace(sec.Namespace) { @@ -695,8 +716,14 @@ func New( } }, UpdateFunc: func(old, cur interface{}) { - oeps := old.(*discoveryv1.EndpointSlice) - ceps := cur.(*discoveryv1.EndpointSlice) + oeps, ok := old.(*discoveryv1.EndpointSlice) + if !ok { + klog.Errorf("unexpected type: %T", old) + } + ceps, ok := cur.(*discoveryv1.EndpointSlice) + if !ok { + klog.Errorf("unexpected type: %T", cur) + } if !reflect.DeepEqual(ceps.Endpoints, oeps.Endpoints) { updateCh.In() <- Event{ Type: UpdateEvent, @@ -750,7 +777,10 @@ func New( cmEventHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - cfgMap := obj.(*corev1.ConfigMap) + cfgMap, ok := obj.(*corev1.ConfigMap) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } key := k8s.MetaNamespaceKey(cfgMap) handleCfgMapEvent(key, cfgMap, "CREATE") }, @@ -759,7 +789,10 @@ func New( return } - cfgMap := cur.(*corev1.ConfigMap) + cfgMap, ok := cur.(*corev1.ConfigMap) + if !ok { + klog.Errorf("unexpected type: %T", cur) + } key := k8s.MetaNamespaceKey(cfgMap) handleCfgMapEvent(key, cfgMap, "UPDATE") }, @@ -767,7 +800,10 @@ func New( serviceHandler := cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { - svc := obj.(*corev1.Service) + svc, ok := obj.(*corev1.Service) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } if svc.Spec.Type == corev1.ServiceTypeExternalName { updateCh.In() <- Event{ Type: CreateEvent, @@ -776,7 +812,10 @@ func New( } }, DeleteFunc: func(obj interface{}) { - svc := obj.(*corev1.Service) + svc, ok := obj.(*corev1.Service) + if !ok { + klog.Errorf("unexpected type: %T", obj) + } if svc.Spec.Type == corev1.ServiceTypeExternalName { updateCh.In() <- Event{ Type: DeleteEvent, @@ -785,8 +824,14 @@ func New( } }, UpdateFunc: func(old, cur interface{}) { - oldSvc := old.(*corev1.Service) - curSvc := cur.(*corev1.Service) + oldSvc, ok := old.(*corev1.Service) + if !ok { + klog.Errorf("unexpected type: %T", old) + } + curSvc, ok := cur.(*corev1.Service) + if !ok { + klog.Errorf("unexpected type: %T", cur) + } if reflect.DeepEqual(oldSvc, curSvc) { return @@ -821,7 +866,10 @@ func New( } // do not wait for informers to read the configmap configuration - ns, name, _ := k8s.ParseNameNS(configmap) + ns, name, err := k8s.ParseNameNS(configmap) + if err != nil { + klog.Errorf("unexpected error parsing name and ns: %v", err) + } cm, err := client.CoreV1().ConfigMaps(ns).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { klog.Warningf("Unexpected error reading configuration configmap: %v", err) @@ -837,10 +885,10 @@ func hasCatchAllIngressRule(spec networkingv1.IngressSpec) bool { return spec.DefaultBackend != nil } -func checkBadAnnotationValue(annotations map[string]string, badwords string) error { +func checkBadAnnotationValue(annotationMap map[string]string, badwords string) error { arraybadWords := strings.Split(strings.TrimSpace(badwords), ",") - for annotation, value := range annotations { + for annotation, value := range annotationMap { if strings.HasPrefix(annotation, fmt.Sprintf("%s/", parser.AnnotationsPrefix)) { for _, forbiddenvalue := range arraybadWords { if strings.Contains(value, forbiddenvalue) { @@ -999,7 +1047,7 @@ func (s *k8sStore) GetService(key string) (*corev1.Service, error) { return s.listers.Service.ByKey(key) } -func (s *k8sStore) GetIngressClass(ing *networkingv1.Ingress, icConfig *ingressclass.IngressClassConfiguration) (string, error) { +func (s *k8sStore) GetIngressClass(ing *networkingv1.Ingress, icConfig *ingressclass.Configuration) (string, error) { // First we try ingressClassName if !icConfig.IgnoreIngressClass && ing.Spec.IngressClassName != nil { iclass, err := s.listers.IngressClass.ByKey(*ing.Spec.IngressClassName) @@ -1010,11 +1058,11 @@ func (s *k8sStore) GetIngressClass(ing *networkingv1.Ingress, icConfig *ingressc } // Then we try annotation - if ingressclass, ok := ing.GetAnnotations()[ingressclass.IngressKey]; ok { - if ingressclass != icConfig.AnnotationValue { + if class, ok := ing.GetAnnotations()[ingressclass.IngressKey]; ok { + if class != icConfig.AnnotationValue { return "", fmt.Errorf("ingress class annotation is not equal to the expected by Ingress Controller") } - return ingressclass, nil + return class, nil } // Then we accept if the WithoutClass is enabled @@ -1055,7 +1103,10 @@ func (s *k8sStore) ListIngresses() []*ingress.Ingress { // filter ingress rules ingresses := make([]*ingress.Ingress, 0) for _, item := range s.listers.IngressWithAnnotation.List() { - ing := item.(*ingress.Ingress) + ing, ok := item.(*ingress.Ingress) + if !ok { + klog.Errorf("unexpected type: %T", item) + } ingresses = append(ingresses, ing) } diff --git a/internal/ingress/controller/store/store_test.go b/internal/ingress/controller/store/store_test.go index 774a45676..317c0f36c 100644 --- a/internal/ingress/controller/store/store_test.go +++ b/internal/ingress/controller/store/store_test.go @@ -44,29 +44,27 @@ import ( var pathPrefix networking.PathType = networking.PathTypePrefix -var DefaultClassConfig = &ingressclass.IngressClassConfiguration{ +var DefaultClassConfig = &ingressclass.Configuration{ Controller: ingressclass.DefaultControllerName, AnnotationValue: ingressclass.DefaultAnnotationValue, WatchWithoutClass: false, } -var ( - commonIngressSpec = networking.IngressSpec{ - Rules: []networking.IngressRule{ - { - Host: "dummy", - IngressRuleValue: networking.IngressRuleValue{ - HTTP: &networking.HTTPIngressRuleValue{ - Paths: []networking.HTTPIngressPath{ - { - Path: "/", - PathType: &pathPrefix, - Backend: networking.IngressBackend{ - Service: &networking.IngressServiceBackend{ - Name: "http-svc", - Port: networking.ServiceBackendPort{ - Number: 80, - }, +var commonIngressSpec = networking.IngressSpec{ + Rules: []networking.IngressRule{ + { + Host: "dummy", + IngressRuleValue: networking.IngressRuleValue{ + HTTP: &networking.HTTPIngressRuleValue{ + Paths: []networking.HTTPIngressPath{ + { + Path: "/", + PathType: &pathPrefix, + Backend: networking.IngressBackend{ + Service: &networking.IngressServiceBackend{ + Name: "http-svc", + Port: networking.ServiceBackendPort{ + Number: 80, }, }, }, @@ -75,12 +73,15 @@ var ( }, }, }, - } -) + }, +} +const updateDummyHost = "update-dummy" + +//nolint:gocyclo // Ignore function complexity error func TestStore(t *testing.T) { - //TODO: move env definition to docker image? - os.Setenv("KUBEBUILDER_ASSETS", "/usr/local/bin") + // TODO: move env definition to docker image? + t.Setenv("KUBEBUILDER_ASSETS", "/usr/local/bin") pathPrefix = networking.PathTypePrefix @@ -90,9 +91,12 @@ func TestStore(t *testing.T) { t.Fatalf("error: %v", err) } - emptySelector, _ := labels.Parse("") + emptySelector, err := labels.Parse("") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } - defer te.Stop() //nolint:errcheck + defer te.Stop() //nolint:errcheck // Ignore the error clientSet, err := kubernetes.NewForConfig(cfg) if err != nil { @@ -176,7 +180,11 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } + if e.Obj == nil { continue } @@ -230,7 +238,7 @@ func TestStore(t *testing.T) { time.Sleep(1 * time.Second) ni := ing.DeepCopy() - ni.Spec.Rules[0].Host = "update-dummy" + ni.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(ni, clientSet, t) if err != nil { t.Errorf("error creating ingress: %v", err) @@ -281,7 +289,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -343,7 +354,7 @@ func TestStore(t *testing.T) { defer deleteIngress(invalidIngress, clientSet, t) ni := ing.DeepCopy() - ni.Spec.Rules[0].Host = "update-dummy" + ni.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(ni, clientSet, t) if err != nil { t.Errorf("error creating ingress: %v", err) @@ -392,7 +403,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -411,7 +425,7 @@ func TestStore(t *testing.T) { } }(updateCh) - ingressClassconfig := &ingressclass.IngressClassConfiguration{ + ingressClassconfig := &ingressclass.Configuration{ Controller: ingressclass.DefaultControllerName, AnnotationValue: ingressclass.DefaultAnnotationValue, WatchWithoutClass: true, @@ -463,7 +477,7 @@ func TestStore(t *testing.T) { time.Sleep(1 * time.Second) validIngressUpdated := validIngress1.DeepCopy() - validIngressUpdated.Spec.Rules[0].Host = "update-dummy" + validIngressUpdated.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(validIngressUpdated, clientSet, t) if err != nil { t.Errorf("error updating ingress: %v", err) @@ -523,7 +537,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -542,7 +559,7 @@ func TestStore(t *testing.T) { } }(updateCh) - ingressClassconfig := &ingressclass.IngressClassConfiguration{ + ingressClassconfig := &ingressclass.Configuration{ Controller: ingressclass.DefaultControllerName, AnnotationValue: ic, IngressClassByName: true, @@ -581,7 +598,7 @@ func TestStore(t *testing.T) { time.Sleep(1 * time.Second) ingressUpdated := ing.DeepCopy() - ingressUpdated.Spec.Rules[0].Host = "update-dummy" + ingressUpdated.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(ingressUpdated, clientSet, t) if err != nil { t.Errorf("error updating ingress: %v", err) @@ -630,7 +647,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -684,7 +704,7 @@ func TestStore(t *testing.T) { time.Sleep(1 * time.Second) invalidIngressUpdated := invalidIngress.DeepCopy() - invalidIngressUpdated.Spec.Rules[0].Host = "update-dummy" + invalidIngressUpdated.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(invalidIngressUpdated, clientSet, t) if err != nil { t.Errorf("error creating ingress: %v", err) @@ -725,7 +745,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -778,7 +801,7 @@ func TestStore(t *testing.T) { time.Sleep(1 * time.Second) invalidIngressUpdated := invalidIngress.DeepCopy() - invalidIngressUpdated.Spec.Rules[0].Host = "update-dummy" + invalidIngressUpdated.Spec.Rules[0].Host = updateDummyHost _ = ensureIngress(invalidIngressUpdated, clientSet, t) if err != nil { t.Errorf("error creating ingress: %v", err) @@ -816,7 +839,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -908,7 +934,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -1008,7 +1037,6 @@ func TestStore(t *testing.T) { if atomic.LoadUint64(&del) != 1 { t.Errorf("expected 1 events of type Delete but %v occurred", del) } - }) t.Run("should create an ingress with a secret which does not exist", func(t *testing.T) { @@ -1032,7 +1060,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -1159,7 +1190,10 @@ func TestStore(t *testing.T) { return } - e := evt.(Event) + e, ok := evt.(Event) + if !ok { + return + } if e.Obj == nil { continue } @@ -1174,7 +1208,10 @@ func TestStore(t *testing.T) { } }(updateCh) - namesapceSelector, _ := labels.Parse("foo=bar") + namesapceSelector, err := labels.Parse("foo=bar") + if err != nil { + t.Errorf("unexpected error: %v", err) + } storer := New( ns, namesapceSelector, @@ -1236,7 +1273,6 @@ func TestStore(t *testing.T) { if atomic.LoadUint64(&del) != 0 { t.Errorf("expected 0 events of type Delete but %v occurred", del) } - }) // test add ingress with secret it doesn't exists and then add secret // check secret is generated on fs @@ -1274,16 +1310,16 @@ func deleteNamespace(ns string, clientSet kubernetes.Interface, t *testing.T) { func createIngressClass(clientSet kubernetes.Interface, t *testing.T, controller string) string { t.Helper() - ingressclass := &networking.IngressClass{ + class := &networking.IngressClass{ ObjectMeta: metav1.ObjectMeta{ Name: fmt.Sprintf("ingress-nginx-%v", time.Now().Unix()), - //Namespace: "xpto" // TODO: We don't support namespaced ingress-class yet + // Namespace: "xpto" // TODO: We don't support namespaced ingress-class yet }, Spec: networking.IngressClassSpec{ Controller: controller, }, } - ic, err := clientSet.NetworkingV1().IngressClasses().Create(context.TODO(), ingressclass, metav1.CreateOptions{}) + ic, err := clientSet.NetworkingV1().IngressClasses().Create(context.TODO(), class, metav1.CreateOptions{}) if err != nil { t.Errorf("error creating ingress class: %v", err) } @@ -1299,7 +1335,7 @@ func deleteIngressClass(ic string, clientSet kubernetes.Interface, t *testing.T) } } -func createConfigMap(clientSet kubernetes.Interface, ns string, t *testing.T) string { +func createConfigMap(clientSet kubernetes.Interface, ns string, t *testing.T) { t.Helper() configMap := &v1.ConfigMap{ @@ -1308,51 +1344,47 @@ func createConfigMap(clientSet kubernetes.Interface, ns string, t *testing.T) st }, } - cm, err := clientSet.CoreV1().ConfigMaps(ns).Create(context.TODO(), configMap, metav1.CreateOptions{}) + _, err := clientSet.CoreV1().ConfigMaps(ns).Create(context.TODO(), configMap, metav1.CreateOptions{}) if err != nil { t.Errorf("error creating the configuration map: %v", err) } - - return cm.Name } -func ensureIngress(ingress *networking.Ingress, clientSet kubernetes.Interface, t *testing.T) *networking.Ingress { +func ensureIngress(ing *networking.Ingress, clientSet kubernetes.Interface, t *testing.T) *networking.Ingress { t.Helper() - ing, err := clientSet.NetworkingV1().Ingresses(ingress.Namespace).Update(context.TODO(), ingress, metav1.UpdateOptions{}) - + newIngress, err := clientSet.NetworkingV1().Ingresses(ing.Namespace).Update(context.TODO(), ing, metav1.UpdateOptions{}) if err != nil { if k8sErrors.IsNotFound(err) { - t.Logf("Ingress %v not found, creating", ingress) + t.Logf("Ingress %v not found, creating", ing) - ing, err = clientSet.NetworkingV1().Ingresses(ingress.Namespace).Create(context.TODO(), ingress, metav1.CreateOptions{}) + newIngress, err = clientSet.NetworkingV1().Ingresses(ing.Namespace).Create(context.TODO(), ing, metav1.CreateOptions{}) if err != nil { - t.Fatalf("error creating ingress %+v: %v", ingress, err) + t.Fatalf("error creating ingress %+v: %v", ing, err) } - t.Logf("Ingress %+v created", ingress) - return ing + t.Logf("Ingress %+v created", ing) + return newIngress } - t.Fatalf("error updating ingress %+v: %v", ingress, err) + t.Fatalf("error updating ingress %+v: %v", ing, err) } - return ing + return newIngress } -func deleteIngress(ingress *networking.Ingress, clientSet kubernetes.Interface, t *testing.T) { +func deleteIngress(ing *networking.Ingress, clientSet kubernetes.Interface, t *testing.T) { t.Helper() - err := clientSet.NetworkingV1().Ingresses(ingress.Namespace).Delete(context.TODO(), ingress.Name, metav1.DeleteOptions{}) - + err := clientSet.NetworkingV1().Ingresses(ing.Namespace).Delete(context.TODO(), ing.Name, metav1.DeleteOptions{}) if err != nil { - t.Errorf("failed to delete ingress %+v: %v", ingress, err) + t.Errorf("failed to delete ingress %+v: %v", ing, err) } - t.Logf("Ingress %+v deleted", ingress) + t.Logf("Ingress %+v deleted", ing) } // newStore creates a new mock object store for tests which do not require the // use of Informers. -func newStore(t *testing.T) *k8sStore { +func newStore() *k8sStore { return &k8sStore{ listers: &Lister{ // add more listers if needed @@ -1369,7 +1401,7 @@ func newStore(t *testing.T) *k8sStore { } func TestUpdateSecretIngressMap(t *testing.T) { - s := newStore(t) + s := newStore() ingTpl := &networking.Ingress{ ObjectMeta: metav1.ObjectMeta{ @@ -1431,7 +1463,9 @@ func TestUpdateSecretIngressMap(t *testing.T) { ing.ObjectMeta.SetAnnotations(map[string]string{ parser.GetAnnotationWithPrefix("auth-secret"): "anotherns/auth", }) - s.listers.Ingress.Update(ing) + if err := s.listers.Ingress.Update(ing); err != nil { + t.Errorf("error updating the Ingress: %v", err) + } s.updateSecretIngressMap(ing) if l := s.secretIngressMap.Len(); l != 0 { @@ -1456,7 +1490,7 @@ func TestUpdateSecretIngressMap(t *testing.T) { } func TestListIngresses(t *testing.T) { - s := newStore(t) + s := newStore() invalidIngressClass := "something" validIngressClass := ingressclass.DefaultControllerName @@ -1586,7 +1620,7 @@ func TestWriteSSLSessionTicketKey(t *testing.T) { } for _, test := range tests { - s := newStore(t) + s := newStore() cmap := &v1.ConfigMap{ Data: map[string]string{ diff --git a/internal/ingress/controller/template/configmap.go b/internal/ingress/controller/template/configmap.go index c73f3b6c0..9dc019bcc 100644 --- a/internal/ingress/controller/template/configmap.go +++ b/internal/ingress/controller/template/configmap.go @@ -91,6 +91,8 @@ const ( ) // ReadConfig obtains the configuration defined by the user merged with the defaults. +// +//nolint:gocyclo // Ignore function complexity error func ReadConfig(src map[string]string) config.Configuration { conf := map[string]string{} // we need to copy the configmap data because the content is altered @@ -116,12 +118,12 @@ func ReadConfig(src map[string]string) config.Configuration { luaSharedDicts := make(map[string]int) debugConnectionsList := make([]string, 0) - //parse lua shared dict values + // parse lua shared dict values if val, ok := conf[luaSharedDictsKey]; ok { delete(conf, luaSharedDictsKey) lsd := splitAndTrimSpace(val, ",") for _, v := range lsd { - v = strings.Replace(v, " ", "", -1) + v = strings.ReplaceAll(v, " ", "") results := strings.SplitN(v, ":", 2) dictName := results[0] size := dictStrToKb(results[1]) @@ -196,7 +198,7 @@ func ReadConfig(src map[string]string) config.Configuration { if ing_net.IsIPV6(ns) { bindAddressIpv6List = append(bindAddressIpv6List, fmt.Sprintf("[%v]", ns)) } else { - bindAddressIpv4List = append(bindAddressIpv4List, fmt.Sprintf("%v", ns)) + bindAddressIpv4List = append(bindAddressIpv4List, ns.String()) } } else { klog.Warningf("%v is not a valid textual representation of an IP address", i) @@ -250,7 +252,7 @@ func ReadConfig(src map[string]string) config.Configuration { if val, ok := conf[globalAuthMethod]; ok { delete(conf, globalAuthMethod) - if len(val) != 0 && !authreq.ValidMethod(val) { + if val != "" && !authreq.ValidMethod(val) { klog.Warningf("Global auth location denied - %v.", "invalid HTTP method") } else { to.GlobalExternalAuth.Method = val @@ -261,7 +263,10 @@ func ReadConfig(src map[string]string) config.Configuration { if val, ok := conf[globalAuthSignin]; ok { delete(conf, globalAuthSignin) - signinURL, _ := parser.StringToURL(val) + signinURL, err := parser.StringToURL(val) + if err != nil { + klog.Errorf("string to URL conversion failed: %v", err) + } if signinURL == nil { klog.Warningf("Global auth location denied - %v.", "global-auth-signin setting is undefined and will not be set") } else { @@ -274,7 +279,10 @@ func ReadConfig(src map[string]string) config.Configuration { delete(conf, globalAuthSigninRedirectParam) redirectParam := strings.TrimSpace(val) - dummySigninURL, _ := parser.StringToURL(fmt.Sprintf("%s?%s=dummy", to.GlobalExternalAuth.SigninURL, redirectParam)) + dummySigninURL, err := parser.StringToURL(fmt.Sprintf("%s?%s=dummy", to.GlobalExternalAuth.SigninURL, redirectParam)) + if err != nil { + klog.Errorf("string to URL conversion failed: %v", err) + } if dummySigninURL == nil { klog.Warningf("Global auth redirect parameter denied - %v.", "global-auth-signin-redirect-param setting is invalid and will not be set") } else { @@ -286,7 +294,7 @@ func ReadConfig(src map[string]string) config.Configuration { if val, ok := conf[globalAuthResponseHeaders]; ok { delete(conf, globalAuthResponseHeaders) - if len(val) != 0 { + if val != "" { harr := splitAndTrimSpace(val, ",") for _, header := range harr { if !authreq.ValidHeader(header) { @@ -385,8 +393,8 @@ func ReadConfig(src map[string]string) config.Configuration { if val, ok := conf[debugConnections]; ok { delete(conf, debugConnections) for _, i := range splitAndTrimSpace(val, ",") { - validIp := net.ParseIP(i) - if validIp != nil { + validIP := net.ParseIP(i) + if validIP != nil { debugConnectionsList = append(debugConnectionsList, i) } else { _, _, err := net.ParseCIDR(i) @@ -415,14 +423,14 @@ func ReadConfig(src map[string]string) config.Configuration { to.DisableIpv6DNS = !ing_net.IsIPv6Enabled() to.LuaSharedDicts = luaSharedDicts - config := &mapstructure.DecoderConfig{ + decoderConfig := &mapstructure.DecoderConfig{ Metadata: nil, WeaklyTypedInput: true, Result: &to, TagName: "json", } - decoder, err := mapstructure.NewDecoder(config) + decoder, err := mapstructure.NewDecoder(decoderConfig) if err != nil { klog.Warningf("unexpected error merging defaults: %v", err) } @@ -456,6 +464,7 @@ func filterErrors(codes []int) []int { return fa } +//nolint:unparam // Ignore `sep` always receives `,` error func splitAndTrimSpace(s, sep string) []string { f := func(c rune) bool { return strings.EqualFold(string(c), sep) @@ -474,8 +483,11 @@ func dictStrToKb(sizeStr string) int { if sizeMatch == nil { return -1 } - size, _ := strconv.Atoi(sizeMatch[1]) // validated already with regex - if sizeMatch[2] == "" || strings.ToLower(sizeMatch[2]) == "m" { + size, err := strconv.Atoi(sizeMatch[1]) // validated already with regex + if err != nil { + klog.Errorf("unexpected error converting size string %s to int: %v", sizeStr, err) + } + if sizeMatch[2] == "" || strings.EqualFold(sizeMatch[2], "m") { size *= 1024 } return size diff --git a/internal/ingress/controller/template/template.go b/internal/ingress/controller/template/template.go index 147455771..4e51ac665 100644 --- a/internal/ingress/controller/template/template.go +++ b/internal/ingress/controller/template/template.go @@ -52,6 +52,12 @@ const ( nonIdempotent = "non_idempotent" defBufferSize = 65535 writeIndentOnEmptyLines = true // backward-compatibility + httpProtocol = "HTTP" + autoHTTPProtocol = "AUTO_HTTP" + httpsProtocol = "HTTPS" + grpcProtocol = "GRPC" + grpcsProtocol = "GRPCS" + fcgiProtocol = "FCGI" ) const ( @@ -64,13 +70,13 @@ 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) + Write(conf *config.TemplateConfig) ([]byte, error) } -// Template ... +// Template ingress template type Template struct { tmpl *text_template.Template - //fw watch.FileWatcher + bp *BufferPool } @@ -97,7 +103,7 @@ func NewTemplate(file string) (*Template, error) { // 2. Collapses multiple empty lines to single one // 3. Re-indent // (ATW: always returns nil) -func cleanConf(in *bytes.Buffer, out *bytes.Buffer) error { +func cleanConf(in, out *bytes.Buffer) error { depth := 0 lineStarted := false emptyLineWritten := false @@ -176,7 +182,7 @@ func cleanConf(in *bytes.Buffer, out *bytes.Buffer) error { // 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) { +func (t *Template) Write(conf *config.TemplateConfig) ([]byte, error) { tmplBuf := t.bp.Get() defer t.bp.Put(tmplBuf) @@ -184,14 +190,14 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) { defer t.bp.Put(outCmdBuf) if klog.V(3).Enabled() { - b, err := json.Marshal(conf) + b, err := json.Marshal(*conf) if err != nil { klog.Errorf("unexpected error: %v", err) } klog.InfoS("NGINX", "configuration", string(b)) } - err := t.tmpl.Execute(tmplBuf, conf) + err := t.tmpl.Execute(tmplBuf, *conf) if err != nil { return nil, err } @@ -211,78 +217,76 @@ func (t *Template) Write(conf config.TemplateConfig) ([]byte, error) { return res, nil } -var ( - funcMap = text_template.FuncMap{ - "empty": func(input interface{}) bool { - check, ok := input.(string) - if ok { - return len(check) == 0 - } - 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, - "buildOpentracing": buildOpentracing, - "buildOpentelemetry": buildOpentelemetry, - "proxySetHeader": proxySetHeader, - "enforceRegexModifier": enforceRegexModifier, - "buildCustomErrorDeps": buildCustomErrorDeps, - "buildCustomErrorLocationsPerServer": buildCustomErrorLocationsPerServer, - "shouldLoadModSecurityModule": shouldLoadModSecurityModule, - "buildHTTPListener": buildHTTPListener, - "buildHTTPSListener": buildHTTPSListener, - "buildOpentracingForLocation": buildOpentracingForLocation, - "buildOpentelemetryForLocation": buildOpentelemetryForLocation, - "shouldLoadOpentracingModule": shouldLoadOpentracingModule, - "shouldLoadOpentelemetryModule": shouldLoadOpentelemetryModule, - "buildModSecurityForLocation": buildModSecurityForLocation, - "buildMirrorLocations": buildMirrorLocations, - "shouldLoadAuthDigestModule": shouldLoadAuthDigestModule, - "buildServerName": buildServerName, - "buildCorsOriginRegex": buildCorsOriginRegex, - } -) +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, + "buildOpentracing": buildOpentracing, + "buildOpentelemetry": buildOpentelemetry, + "proxySetHeader": proxySetHeader, + "enforceRegexModifier": enforceRegexModifier, + "buildCustomErrorDeps": buildCustomErrorDeps, + "buildCustomErrorLocationsPerServer": buildCustomErrorLocationsPerServer, + "shouldLoadModSecurityModule": shouldLoadModSecurityModule, + "buildHTTPListener": buildHTTPListener, + "buildHTTPSListener": buildHTTPSListener, + "buildOpentracingForLocation": buildOpentracingForLocation, + "buildOpentelemetryForLocation": buildOpentelemetryForLocation, + "shouldLoadOpentracingModule": shouldLoadOpentracingModule, + "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 @@ -296,7 +300,7 @@ func escapeLiteralDollar(input interface{}) string { if !ok { return "" } - return strings.Replace(inputStr, `$`, `${literal_dollar}`, -1) + return strings.ReplaceAll(inputStr, `$`, `${literal_dollar}`) } // formatIP will wrap IPv6 addresses in [] and return IPv4 addresses @@ -328,9 +332,7 @@ func quote(input interface{}) string { return fmt.Sprintf("%q", inputStr) } -func buildLuaSharedDictionaries(c interface{}, s interface{}) string { - var out []string - +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) @@ -343,6 +345,7 @@ func buildLuaSharedDictionaries(c interface{}, s interface{}) string { 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)) @@ -364,7 +367,7 @@ func luaConfigurationRequestBodySize(c interface{}) string { if size < cfg.LuaSharedDicts["certificate_data"] { size = cfg.LuaSharedDicts["certificate_data"] } - size = size + 1024 + size += 1024 return dictKbToStr(size) } @@ -418,7 +421,7 @@ func configForLua(input interface{}) string { } // locationConfigForLua formats some location specific configuration into Lua table represented as string -func locationConfigForLua(l interface{}, a interface{}) 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) @@ -459,7 +462,7 @@ func locationConfigForLua(l interface{}, a interface{}) string { } // buildResolvers returns the resolvers reading the /etc/resolv.conf file -func buildResolvers(res interface{}, disableIpv6 interface{}) string { +func buildResolvers(res, disableIpv6 interface{}) string { // NGINX need IPV6 addresses to be surrounded by brackets nss, ok := res.([]net.IP) if !ok { @@ -484,7 +487,7 @@ func buildResolvers(res interface{}, disableIpv6 interface{}) string { } r = append(r, fmt.Sprintf("[%v]", ns)) } else { - r = append(r, fmt.Sprintf("%v", ns)) + r = append(r, ns.String()) } } r = append(r, "valid=30s") @@ -554,7 +557,7 @@ func buildAuthLocation(input interface{}, globalExternalAuthURL string) string { str := base64.URLEncoding.EncodeToString([]byte(location.Path)) // removes "=" after encoding - str = strings.Replace(str, "=", "", -1) + str = strings.ReplaceAll(str, "=", "") pathType := "default" if location.PathType != nil { @@ -644,7 +647,7 @@ func buildAuthUpstreamName(input interface{}, host string) string { // shouldApplyAuthUpstream returns true only in case when ExternalAuth.URL and // ExternalAuth.KeepaliveConnections are all set -func shouldApplyAuthUpstream(l interface{}, c interface{}) bool { +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) @@ -672,14 +675,14 @@ func shouldApplyAuthUpstream(l interface{}, c interface{}) bool { } // extractHostPort will extract the host:port part from the URL specified by url -func extractHostPort(url string) string { - if url == "" { +func extractHostPort(newURL string) string { + if newURL == "" { return "" } - authURL, err := parser.StringToURL(url) + authURL, err := parser.StringToURL(newURL) if err != nil { - klog.Errorf("expected a valid URL but %s was returned", url) + klog.Errorf("expected a valid URL but %s was returned", newURL) return "" } @@ -687,14 +690,14 @@ func extractHostPort(url string) string { } // changeHostPort will change the host:port part of the url to value -func changeHostPort(url string, value string) string { - if url == "" { +func changeHostPort(newURL, value string) string { + if newURL == "" { return "" } - authURL, err := parser.StringToURL(url) + authURL, err := parser.StringToURL(newURL) if err != nil { - klog.Errorf("expected a valid URL but %s was returned", url) + klog.Errorf("expected a valid URL but %s was returned", newURL) return "" } @@ -707,7 +710,7 @@ func changeHostPort(url string, value string) string { // (specified through the nginx.ingress.kubernetes.io/rewrite-target annotation) // If the annotation nginx.ingress.kubernetes.io/add-base-url:"true" is specified it will // add a base tag in the head of the response from the service -func buildProxyPass(host string, b interface{}, loc interface{}) string { +func buildProxyPass(_ string, b, loc interface{}) string { backends, ok := b.([]*ingress.Backend) if !ok { klog.Errorf("expected an '[]*ingress.Backend' type but %T was returned", b) @@ -726,17 +729,17 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string { proxyPass := "proxy_pass" switch location.BackendProtocol { - case "AUTO_HTTP": + case autoHTTPProtocol: proto = "$scheme://" - case "HTTPS": + case httpsProtocol: proto = "https://" - case "GRPC": + case grpcProtocol: proto = "grpc://" proxyPass = "grpc_pass" - case "GRPCS": + case grpcsProtocol: proto = "grpcs://" proxyPass = "grpc_pass" - case "FCGI": + case fcgiProtocol: proto = "" proxyPass = "fastcgi_pass" } @@ -748,7 +751,7 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string { if backend.SSLPassthrough { proto = "https://" - if location.BackendProtocol == "GRPCS" { + if location.BackendProtocol == grpcsProtocol { proto = "grpcs://" } } @@ -775,7 +778,7 @@ func buildProxyPass(host string, b interface{}, loc interface{}) string { var xForwardedPrefix string if len(location.XForwardedPrefix) > 0 { - xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix \"%s\";\n", proxySetHeader(location), location.XForwardedPrefix) + xForwardedPrefix = fmt.Sprintf("%s X-Forwarded-Prefix %q;\n", proxySetHeader(location), location.XForwardedPrefix) } return fmt.Sprintf(` @@ -935,9 +938,7 @@ func isLocationAllowed(input interface{}) bool { return loc.Denied == nil } -var ( - denyPathSlugMap = map[string]string{} -) +var denyPathSlugMap = map[string]string{} // buildDenyVariable returns a nginx variable for a location in a // server to be used in the whitelist check @@ -977,7 +978,11 @@ func buildNextUpstream(i, r interface{}) string { return "" } - retryNonIdempotent := r.(bool) + retryNonIdempotent, ok := r.(bool) + if !ok { + klog.Errorf("expected a 'bool' type but %T was returned", i) + return "" + } parts := strings.Split(nextUpstream, " ") @@ -1002,8 +1007,10 @@ func buildNextUpstream(i, r interface{}) string { // 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("^[0-9]+[kKmM]{0,1}$") -var nginxOffsetRegex = regexp.MustCompile("^[0-9]+[kKmMgG]{0,1}$") +var ( + nginxSizeRegex = regexp.MustCompile(`^\d+[kKmM]?$`) + nginxOffsetRegex = regexp.MustCompile(`^\d+[kKmMgG]?$`) +) // isValidByteSize validates size units valid in nginx // http://nginx.org/en/docs/syntax.html @@ -1153,13 +1160,17 @@ func buildForwardedFor(input interface{}) string { return "" } - ffh := strings.Replace(s, "-", "_", -1) + ffh := strings.ReplaceAll(s, "-", "_") ffh = strings.ToLower(ffh) return fmt.Sprintf("$http_%v", ffh) } func buildAuthSignURL(authSignURL, authRedirectParam string) string { - u, _ := url.Parse(authSignURL) + u, err := url.Parse(authSignURL) + if err != nil { + klog.Errorf("error parsing authSignURL: %v", err) + return "" + } q := u.Query() if authRedirectParam == "" { authRedirectParam = defaultGlobalAuthRedirectParam @@ -1198,7 +1209,7 @@ func randomString() string { return string(b) } -func buildOpentracing(c interface{}, s interface{}) string { +func buildOpentracing(c, s interface{}) string { cfg, ok := c.(config.Configuration) if !ok { klog.Errorf("expected a 'config.Configuration' type but %T was returned", c) @@ -1217,6 +1228,7 @@ func buildOpentracing(c interface{}, s interface{}) string { buf := bytes.NewBufferString("") + //nolint:gocritic // rewriting if-else to switch statement is not more readable if cfg.DatadogCollectorHost != "" { buf.WriteString("opentracing_load_tracer /usr/local/lib/libdd_opentracing.so /etc/nginx/opentracing.json;") } else if cfg.ZipkinCollectorHost != "" { @@ -1228,16 +1240,16 @@ func buildOpentracing(c interface{}, s interface{}) string { buf.WriteString("\r\n") if cfg.OpentracingOperationName != "" { - buf.WriteString(fmt.Sprintf("opentracing_operation_name \"%s\";\n", cfg.OpentracingOperationName)) + fmt.Fprintf(buf, "opentracing_operation_name \"%s\";\n", cfg.OpentracingOperationName) } if cfg.OpentracingLocationOperationName != "" { - buf.WriteString(fmt.Sprintf("opentracing_location_operation_name \"%s\";\n", cfg.OpentracingLocationOperationName)) + fmt.Fprintf(buf, "opentracing_location_operation_name \"%s\";\n", cfg.OpentracingLocationOperationName) } return buf.String() } -func buildOpentelemetry(c interface{}, s interface{}) string { +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) @@ -1259,7 +1271,7 @@ func buildOpentelemetry(c interface{}, s interface{}) string { buf.WriteString("\r\n") if cfg.OpentelemetryOperationName != "" { - buf.WriteString(fmt.Sprintf("opentelemetry_operation_name \"%s\";\n", cfg.OpentelemetryOperationName)) + fmt.Fprintf(buf, "opentelemetry_operation_name \"%s\";\n", cfg.OpentelemetryOperationName) } return buf.String() } @@ -1271,7 +1283,7 @@ func proxySetHeader(loc interface{}) string { return "proxy_set_header" } - if location.BackendProtocol == "GRPC" || location.BackendProtocol == "GRPCS" { + if location.BackendProtocol == grpcProtocol || location.BackendProtocol == grpcsProtocol { return "grpc_set_header" } @@ -1280,7 +1292,7 @@ func proxySetHeader(loc interface{}) string { // 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 bool, modsecurityEnabled bool) interface{} { +func buildCustomErrorDeps(upstreamName string, errorCodes []int, enableMetrics, modsecurityEnabled bool) interface{} { return struct { UpstreamName string ErrorCodes []int @@ -1355,7 +1367,7 @@ func opentracingPropagateContext(location *ingress.Location) string { return "" } - if location.BackendProtocol == "GRPC" || location.BackendProtocol == "GRPCS" { + if location.BackendProtocol == grpcProtocol || location.BackendProtocol == grpcsProtocol { return "opentracing_grpc_propagate_context;" } @@ -1372,7 +1384,7 @@ func opentelemetryPropagateContext(location *ingress.Location) string { // 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 interface{}, s interface{}) bool { +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) @@ -1403,7 +1415,7 @@ func shouldLoadModSecurityModule(c interface{}, s interface{}) bool { return false } -func buildHTTPListener(t interface{}, s interface{}) string { +func buildHTTPListener(t, s interface{}) string { var out []string tc, ok := t.(config.TemplateConfig) @@ -1423,9 +1435,9 @@ func buildHTTPListener(t interface{}, s interface{}) string { addrV4 = tc.Cfg.BindAddressIpv4 } - co := commonListenOptions(tc, hostname) + co := commonListenOptions(&tc, hostname) - out = append(out, httpListener(addrV4, co, tc)...) + out = append(out, httpListener(addrV4, co, &tc)...) if !tc.IsIPV6Enabled { return strings.Join(out, "\n") @@ -1436,12 +1448,12 @@ func buildHTTPListener(t interface{}, s interface{}) string { addrV6 = tc.Cfg.BindAddressIpv6 } - out = append(out, httpListener(addrV6, co, tc)...) + out = append(out, httpListener(addrV6, co, &tc)...) return strings.Join(out, "\n") } -func buildHTTPSListener(t interface{}, s interface{}) string { +func buildHTTPSListener(t, s interface{}) string { var out []string tc, ok := t.(config.TemplateConfig) @@ -1456,14 +1468,14 @@ func buildHTTPSListener(t interface{}, s interface{}) string { return "" } - co := commonListenOptions(tc, hostname) + co := commonListenOptions(&tc, hostname) addrV4 := []string{""} if len(tc.Cfg.BindAddressIpv4) > 0 { addrV4 = tc.Cfg.BindAddressIpv4 } - out = append(out, httpsListener(addrV4, co, tc)...) + out = append(out, httpsListener(addrV4, co, &tc)...) if !tc.IsIPV6Enabled { return strings.Join(out, "\n") @@ -1474,12 +1486,12 @@ func buildHTTPSListener(t interface{}, s interface{}) string { addrV6 = tc.Cfg.BindAddressIpv6 } - out = append(out, httpsListener(addrV6, co, tc)...) + out = append(out, httpsListener(addrV6, co, &tc)...) return strings.Join(out, "\n") } -func commonListenOptions(template config.TemplateConfig, hostname string) string { +func commonListenOptions(template *config.TemplateConfig, hostname string) string { var out []string if template.Cfg.UseProxyProtocol { @@ -1503,7 +1515,7 @@ func commonListenOptions(template config.TemplateConfig, hostname string) string return strings.Join(out, " ") } -func httpListener(addresses []string, co string, tc config.TemplateConfig) []string { +func httpListener(addresses []string, co string, tc *config.TemplateConfig) []string { out := make([]string, 0) for _, address := range addresses { lo := []string{"listen"} @@ -1514,15 +1526,14 @@ func httpListener(addresses []string, co string, tc config.TemplateConfig) []str lo = append(lo, fmt.Sprintf("%v:%v", address, tc.ListenPorts.HTTP)) } - lo = append(lo, co) - lo = append(lo, ";") + lo = append(lo, co, ";") out = append(out, strings.Join(lo, " ")) } return out } -func httpsListener(addresses []string, co string, tc config.TemplateConfig) []string { +func httpsListener(addresses []string, co string, tc *config.TemplateConfig) []string { out := make([]string, 0) for _, address := range addresses { lo := []string{"listen"} @@ -1545,8 +1556,7 @@ func httpsListener(addresses []string, co string, tc config.TemplateConfig) []st } } - lo = append(lo, co) - lo = append(lo, "ssl") + lo = append(lo, co, "ssl") if tc.Cfg.UseHTTP2 { lo = append(lo, "http2") @@ -1559,7 +1569,7 @@ func httpsListener(addresses []string, co string, tc config.TemplateConfig) []st return out } -func buildOpentracingForLocation(isOTEnabled bool, isOTTrustSet bool, location *ingress.Location) string { +func buildOpentracingForLocation(isOTEnabled, isOTTrustSet bool, location *ingress.Location) string { isOTEnabledInLoc := location.Opentracing.Enabled isOTSetInLoc := location.Opentracing.Set @@ -1578,13 +1588,13 @@ func buildOpentracingForLocation(isOTEnabled bool, isOTTrustSet bool, location * if (!isOTTrustSet && !location.Opentracing.TrustSet) || (location.Opentracing.TrustSet && !location.Opentracing.TrustEnabled) { - opc = opc + "\nopentracing_trust_incoming_span off;" + opc += "\nopentracing_trust_incoming_span off;" } return opc } -func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location *ingress.Location) string { +func buildOpentelemetryForLocation(isOTEnabled, isOTTrustSet bool, location *ingress.Location) string { isOTEnabledInLoc := location.Opentelemetry.Enabled isOTSetInLoc := location.Opentelemetry.Set @@ -1602,14 +1612,14 @@ func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location } if location.Opentelemetry.OperationName != "" { - opc = opc + "\nopentelemetry_operation_name " + location.Opentelemetry.OperationName + ";" + opc += "\nopentelemetry_operation_name " + location.Opentelemetry.OperationName + ";" } if (!isOTTrustSet && !location.Opentelemetry.TrustSet) || (location.Opentelemetry.TrustSet && !location.Opentelemetry.TrustEnabled) { - opc = opc + "\nopentelemetry_trust_incoming_spans off;" + opc += "\nopentelemetry_trust_incoming_spans off;" } else { - opc = opc + "\nopentelemetry_trust_incoming_spans on;" + opc += "\nopentelemetry_trust_incoming_spans on;" } return opc } @@ -1617,7 +1627,7 @@ func buildOpentelemetryForLocation(isOTEnabled bool, isOTTrustSet bool, location // shouldLoadOpentracingModule determines whether or not the Opentracing module needs to be loaded. // First, it checks if `enable-opentracing` is set in the ConfigMap. If it is not, it iterates over all locations to // check if Opentracing is enabled by the annotation `nginx.ingress.kubernetes.io/enable-opentracing`. -func shouldLoadOpentracingModule(c interface{}, s interface{}) bool { +func shouldLoadOpentracingModule(c, s interface{}) bool { cfg, ok := c.(config.Configuration) if !ok { klog.Errorf("expected a 'config.Configuration' type but %T was returned", c) @@ -1647,7 +1657,7 @@ func shouldLoadOpentracingModule(c interface{}, s interface{}) bool { // 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 interface{}, s interface{}) bool { +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) @@ -1674,6 +1684,7 @@ func shouldLoadOpentelemetryModule(c interface{}, s interface{}) bool { 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 @@ -1807,7 +1818,7 @@ func convertGoSliceIntoLuaTable(goSliceInterface interface{}, emptyStringAsNil b switch kind { case reflect.String: - if emptyStringAsNil && len(goSlice.Interface().(string)) == 0 { + if emptyStringAsNil && goSlice.Interface().(string) == "" { return "nil", nil } return fmt.Sprintf(`"%v"`, goSlice.Interface()), nil @@ -1840,17 +1851,17 @@ func buildCorsOriginRegex(corsOrigins []string) string { return "set $http_origin *;\nset $cors 'true';" } - var originsRegex string = "if ($http_origin ~* (" + originsRegex := "if ($http_origin ~* (" for i, origin := range corsOrigins { originTrimmed := strings.TrimSpace(origin) if len(originTrimmed) > 0 { builtOrigin := buildOriginRegex(originTrimmed) originsRegex += builtOrigin if i != len(corsOrigins)-1 { - originsRegex = originsRegex + "|" + originsRegex += "|" } } } - originsRegex = originsRegex + ")$ ) { set $cors 'true'; }" + originsRegex += ")$ ) { set $cors 'true'; }" return originsRegex } diff --git a/internal/ingress/controller/template/template_test.go b/internal/ingress/controller/template/template_test.go index a2c3b8299..110967711 100644 --- a/internal/ingress/controller/template/template_test.go +++ b/internal/ingress/controller/template/template_test.go @@ -48,9 +48,9 @@ import ( func init() { // the default value of nginx.TemplatePath assumes the template exists in // the root filesystem and not in the rootfs directory - path, err := filepath.Abs(filepath.Join("../../../../rootfs/", nginx.TemplatePath)) + absPath, err := filepath.Abs(filepath.Join("..", "..", "..", "..", "rootfs", nginx.TemplatePath)) if err == nil { - nginx.TemplatePath = path + nginx.TemplatePath = absPath } } @@ -63,7 +63,7 @@ var ( Target string Location string ProxyPass string - AutoHttpProxyPass string + AutoHTTPProxyPass string Sticky bool XForwardedPrefix string SecureBackend bool @@ -200,6 +200,12 @@ proxy_pass $scheme://upstream_balancer;`, } ) +const ( + defaultBackend = "upstream-name" + defaultHost = "example.com" + fooAuthHost = "foo.com/auth" +) + func getTestDataDir() (string, error) { pwd, err := os.Getwd() if err != nil { @@ -326,9 +332,6 @@ func TestBuildLocation(t *testing.T) { } func TestBuildProxyPass(t *testing.T) { - defaultBackend := "upstream-name" - defaultHost := "example.com" - for k, tc := range tmplFuncTestcases { loc := &ingress.Location{ Path: tc.Path, @@ -339,7 +342,7 @@ func TestBuildProxyPass(t *testing.T) { } if tc.SecureBackend { - loc.BackendProtocol = "HTTPS" + loc.BackendProtocol = httpsProtocol } backend := &ingress.Backend{ @@ -367,9 +370,6 @@ func TestBuildProxyPass(t *testing.T) { } func TestBuildProxyPassAutoHttp(t *testing.T) { - defaultBackend := "upstream-name" - defaultHost := "example.com" - for k, tc := range tmplFuncTestcases { loc := &ingress.Location{ Path: tc.Path, @@ -379,9 +379,9 @@ func TestBuildProxyPassAutoHttp(t *testing.T) { } if tc.SecureBackend { - loc.BackendProtocol = "HTTPS" + loc.BackendProtocol = httpsProtocol } else { - loc.BackendProtocol = "AUTO_HTTP" + loc.BackendProtocol = autoHTTPProtocol } backend := &ingress.Backend{ @@ -402,7 +402,7 @@ func TestBuildProxyPassAutoHttp(t *testing.T) { backends := []*ingress.Backend{backend} pp := buildProxyPass(defaultHost, backends, loc) - if !strings.EqualFold(tc.AutoHttpProxyPass, pp) { + if !strings.EqualFold(tc.AutoHTTPProxyPass, pp) { t.Errorf("%s: expected \n'%v'\nbut returned \n'%v'", k, tc.ProxyPass, pp) } } @@ -417,7 +417,7 @@ func TestBuildAuthLocation(t *testing.T) { t.Errorf("Expected '%v' but returned '%v'", expected, actual) } - authURL := "foo.com/auth" + authURL := fooAuthHost globalAuthURL := "foo.com/global-auth" loc := &ingress.Location{ @@ -428,7 +428,7 @@ func TestBuildAuthLocation(t *testing.T) { EnableGlobalAuth: true, } - encodedAuthURL := strings.Replace(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "", -1) + encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "") externalAuthPath := fmt.Sprintf("/_external-auth-%v-default", encodedAuthURL) testCases := []struct { @@ -460,8 +460,7 @@ func TestBuildAuthLocation(t *testing.T) { } func TestShouldApplyGlobalAuth(t *testing.T) { - - authURL := "foo.com/auth" + authURL := fooAuthHost globalAuthURL := "foo.com/global-auth" loc := &ingress.Location{ @@ -579,12 +578,12 @@ func TestBuildAuthUpstreamName(t *testing.T) { loc := &ingress.Location{ ExternalAuth: authreq.Config{ - URL: "foo.com/auth", + URL: fooAuthHost, }, Path: "/cat", } - encodedAuthURL := strings.Replace(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "", -1) + encodedAuthURL := strings.ReplaceAll(base64.URLEncoding.EncodeToString([]byte(loc.Path)), "=", "") externalAuthPath := fmt.Sprintf("external-auth-%v-default", encodedAuthURL) testCases := []struct { @@ -606,7 +605,7 @@ func TestBuildAuthUpstreamName(t *testing.T) { } func TestShouldApplyAuthUpstream(t *testing.T) { - authURL := "foo.com/auth" + authURL := fooAuthHost loc := &ingress.Location{ ExternalAuth: authreq.Config{ @@ -702,7 +701,10 @@ func TestChangeHostPort(t *testing.T) { } func TestTemplateWithData(t *testing.T) { - pwd, _ := os.Getwd() + pwd, err := os.Getwd() + if err != nil { + t.Errorf("unexpected error: %v", err) + } f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json")) if err != nil { t.Errorf("unexpected error reading json file: %v", err) @@ -727,7 +729,7 @@ func TestTemplateWithData(t *testing.T) { dat.Cfg.DefaultSSLCertificate = &ingress.SSLCert{} - rt, err := ngxTpl.Write(dat) + rt, err := ngxTpl.Write(&dat) if err != nil { t.Errorf("invalid NGINX template: %v", err) } @@ -746,7 +748,10 @@ func TestTemplateWithData(t *testing.T) { } func BenchmarkTemplateWithData(b *testing.B) { - pwd, _ := os.Getwd() + pwd, err := os.Getwd() + if err != nil { + b.Errorf("unexpected error: %v", err) + } f, err := os.Open(path.Join(pwd, "../../../../test/data/config.json")) if err != nil { b.Errorf("unexpected error reading json file: %v", err) @@ -767,7 +772,7 @@ func BenchmarkTemplateWithData(b *testing.B) { } for i := 0; i < b.N; i++ { - if _, err := ngxTpl.Write(dat); err != nil { + if _, err := ngxTpl.Write(&dat); err != nil { b.Errorf("unexpected error writing template: %v", err) } } @@ -1066,9 +1071,6 @@ func TestBuildUpstreamName(t *testing.T) { t.Errorf("Expected '%v' but returned '%v'", expected, actual) } - defaultBackend := "upstream-name" - defaultHost := "example.com" - for k, tc := range tmplFuncTestcases { loc := &ingress.Location{ Path: tc.Path, @@ -1079,7 +1081,7 @@ func TestBuildUpstreamName(t *testing.T) { } if tc.SecureBackend { - loc.BackendProtocol = "HTTPS" + loc.BackendProtocol = httpsProtocol } backend := &ingress.Backend{ @@ -1134,13 +1136,13 @@ func TestEscapeLiteralDollar(t *testing.T) { func TestOpentracingPropagateContext(t *testing.T) { tests := map[*ingress.Location]string{ - {BackendProtocol: "HTTP"}: "opentracing_propagate_context;", - {BackendProtocol: "HTTPS"}: "opentracing_propagate_context;", - {BackendProtocol: "AUTO_HTTP"}: "opentracing_propagate_context;", - {BackendProtocol: "GRPC"}: "opentracing_grpc_propagate_context;", - {BackendProtocol: "GRPCS"}: "opentracing_grpc_propagate_context;", - {BackendProtocol: "FCGI"}: "opentracing_propagate_context;", - nil: "", + {BackendProtocol: httpProtocol}: "opentracing_propagate_context;", + {BackendProtocol: httpsProtocol}: "opentracing_propagate_context;", + {BackendProtocol: autoHTTPProtocol}: "opentracing_propagate_context;", + {BackendProtocol: grpcProtocol}: "opentracing_grpc_propagate_context;", + {BackendProtocol: grpcsProtocol}: "opentracing_grpc_propagate_context;", + {BackendProtocol: fcgiProtocol}: "opentracing_propagate_context;", + nil: "", } for loc, expectedDirective := range tests { @@ -1153,13 +1155,13 @@ func TestOpentracingPropagateContext(t *testing.T) { func TestOpentelemetryPropagateContext(t *testing.T) { tests := map[*ingress.Location]string{ - {BackendProtocol: "HTTP"}: "opentelemetry_propagate;", - {BackendProtocol: "HTTPS"}: "opentelemetry_propagate;", - {BackendProtocol: "AUTO_HTTP"}: "opentelemetry_propagate;", - {BackendProtocol: "GRPC"}: "opentelemetry_propagate;", - {BackendProtocol: "GRPCS"}: "opentelemetry_propagate;", - {BackendProtocol: "FCGI"}: "opentelemetry_propagate;", - nil: "", + {BackendProtocol: httpProtocol}: "opentelemetry_propagate;", + {BackendProtocol: httpsProtocol}: "opentelemetry_propagate;", + {BackendProtocol: autoHTTPProtocol}: "opentelemetry_propagate;", + {BackendProtocol: grpcProtocol}: "opentelemetry_propagate;", + {BackendProtocol: grpcsProtocol}: "opentelemetry_propagate;", + {BackendProtocol: fcgiProtocol}: "opentelemetry_propagate;", + nil: "", } for loc, expectedDirective := range tests { @@ -1171,7 +1173,6 @@ func TestOpentelemetryPropagateContext(t *testing.T) { } func TestGetIngressInformation(t *testing.T) { - testcases := map[string]struct { Ingress interface{} Host string @@ -1625,7 +1626,7 @@ func TestProxySetHeader(t *testing.T) { { name: "gRPC backend", loc: &ingress.Location{ - BackendProtocol: "GRPC", + BackendProtocol: grpcProtocol, }, expected: "grpc_set_header", }, @@ -1716,7 +1717,6 @@ func TestBuildOpenTracing(t *testing.T) { if expected != actual { t.Errorf("Expected '%v' but returned '%v'", expected, actual) } - } func TestBuildOpenTelemetry(t *testing.T) { @@ -1777,6 +1777,7 @@ func TestEnforceRegexModifier(t *testing.T) { } } +//nolint:dupl // Ignore dupl errors for similar test case func TestShouldLoadModSecurityModule(t *testing.T) { // ### Invalid argument type tests ### // The first tests should return false. @@ -1877,6 +1878,7 @@ opentracing_trust_incoming_span off;` } } +//nolint:dupl // Ignore dupl errors for similar test case func TestShouldLoadOpentracingModule(t *testing.T) { // ### Invalid argument type tests ### // The first tests should return false. @@ -1978,6 +1980,7 @@ opentelemetry_trust_incoming_spans off;` } } +//nolint:dupl // Ignore dupl errors for similar test case func TestShouldLoadOpentelemetryModule(t *testing.T) { // ### Invalid argument type tests ### // The first tests should return false. @@ -2104,7 +2107,6 @@ func TestModSecurityForLocation(t *testing.T) { } func TestBuildServerName(t *testing.T) { - testCases := []struct { title string hostname string diff --git a/internal/ingress/controller/util.go b/internal/ingress/controller/util.go index 6562dd17c..8851f323f 100644 --- a/internal/ingress/controller/util.go +++ b/internal/ingress/controller/util.go @@ -135,11 +135,13 @@ func (nc NginxCommand) ExecCommand(args ...string) *exec.Cmd { cmdArgs = append(cmdArgs, "-c", cfgPath) cmdArgs = append(cmdArgs, args...) + //nolint:gosec // Ignore G204 error return exec.Command(nc.Binary, cmdArgs...) } // Test checks if config file is a syntax valid nginx configuration func (nc NginxCommand) Test(cfg string) ([]byte, error) { + //nolint:gosec // Ignore G204 error return exec.Command(nc.Binary, "-c", cfg, "-t").CombinedOutput() } diff --git a/internal/ingress/defaults/main.go b/internal/ingress/defaults/main.go index 8cd0e8ba5..0526d443e 100644 --- a/internal/ingress/defaults/main.go +++ b/internal/ingress/defaults/main.go @@ -100,7 +100,7 @@ type Backend struct { // Name server/s used to resolve names of upstream servers into IP addresses. // The file /etc/resolv.conf is used as DNS resolution configuration. - Resolver []net.IP + Resolver []net.IP `json:"Resolver"` // SkipAccessLogURLs sets a list of URLs that should not appear in the NGINX access log // This is useful with urls like `/health` or `health-check` that make "complex" reading the logs diff --git a/internal/ingress/errors/errors.go b/internal/ingress/errors/errors.go index e6f7fb52c..d70218334 100644 --- a/internal/ingress/errors/errors.go +++ b/internal/ingress/errors/errors.go @@ -33,57 +33,57 @@ var ( // NewInvalidAnnotationConfiguration returns a new InvalidConfiguration error for use when // annotations are not correctly configured -func NewInvalidAnnotationConfiguration(name string, reason string) error { - return InvalidConfiguration{ +func NewInvalidAnnotationConfiguration(name, reason string) error { + return InvalidConfigurationError{ Name: fmt.Sprintf("the annotation %v does not contain a valid configuration: %v", name, reason), } } // NewInvalidAnnotationContent returns a new InvalidContent error func NewInvalidAnnotationContent(name string, val interface{}) error { - return InvalidContent{ + return InvalidContentError{ Name: fmt.Sprintf("the annotation %v does not contain a valid value (%v)", name, val), } } // NewLocationDenied returns a new LocationDenied error func NewLocationDenied(reason string) error { - return LocationDenied{ - Reason: fmt.Errorf("Location denied, reason: %v", reason), + return LocationDeniedError{ + Reason: fmt.Errorf("location denied, reason: %v", reason), } } -// InvalidConfiguration Error -type InvalidConfiguration struct { +// InvalidConfigurationError +type InvalidConfigurationError struct { Name string } -func (e InvalidConfiguration) Error() string { +func (e InvalidConfigurationError) Error() string { return e.Name } -// InvalidContent error -type InvalidContent struct { +// InvalidContentError +type InvalidContentError struct { Name string } -func (e InvalidContent) Error() string { +func (e InvalidContentError) Error() string { return e.Name } -// LocationDenied error -type LocationDenied struct { +// LocationDeniedError +type LocationDeniedError struct { Reason error } -func (e LocationDenied) Error() string { +func (e LocationDeniedError) Error() string { return e.Reason.Error() } // IsLocationDenied checks if the err is an error which // indicates a location should return HTTP code 503 func IsLocationDenied(e error) bool { - _, ok := e.(LocationDenied) + _, ok := e.(LocationDeniedError) return ok } @@ -96,7 +96,7 @@ func IsMissingAnnotations(e error) bool { // IsInvalidContent checks if the err is an error which // indicates an annotations value is not valid func IsInvalidContent(e error) bool { - _, ok := e.(InvalidContent) + _, ok := e.(InvalidContentError) return ok } diff --git a/internal/ingress/inspector/ingress_test.go b/internal/ingress/inspector/ingress_test.go index bfd9f6b93..52ad8d431 100644 --- a/internal/ingress/inspector/ingress_test.go +++ b/internal/ingress/inspector/ingress_test.go @@ -24,7 +24,6 @@ import ( ) func makeSimpleIngress(hostname string, paths ...string) *networking.Ingress { - newIngress := networking.Ingress{ ObjectMeta: v1.ObjectMeta{ Name: "test1", diff --git a/internal/ingress/inspector/inspector.go b/internal/ingress/inspector/inspector.go index 23b57e538..b41e18d9e 100644 --- a/internal/ingress/inspector/inspector.go +++ b/internal/ingress/inspector/inspector.go @@ -40,9 +40,7 @@ func DeepInspect(obj interface{}) error { } } -var ( - implSpecific = networking.PathTypeImplementationSpecific -) +var implSpecific = networking.PathTypeImplementationSpecific func ValidatePathType(ing *networking.Ingress) error { if ing == nil { diff --git a/internal/ingress/inspector/rules.go b/internal/ingress/inspector/rules.go index c9714e680..8388efdd5 100644 --- a/internal/ingress/inspector/rules.go +++ b/internal/ingress/inspector/rules.go @@ -34,7 +34,7 @@ var ( // the group [[:alnum:]\_\-\/]* says that any amount of characters (A-Za-z0-9), _, - and / // are accepted until the end of the line // Nothing else is accepted. - validPathType = regexp.MustCompile(`(?i)^/[[:alnum:]\_\-\/]*$`) + validPathType = regexp.MustCompile(`(?i)^/[[:alnum:]\_\-/]*$`) invalidRegex = []regexp.Regexp{} ) @@ -52,8 +52,8 @@ func init() { // CheckRegex receives a value/configuration and validates if it matches with one of the // forbidden regexes. func CheckRegex(value string) error { - for _, regex := range invalidRegex { - if regex.MatchString(value) { + for i := range invalidRegex { + if invalidRegex[i].MatchString(value) { return fmt.Errorf("invalid value found: %s", value) } } diff --git a/internal/ingress/inspector/rules_test.go b/internal/ingress/inspector/rules_test.go index 6ed6dbe87..3945a3bd4 100644 --- a/internal/ingress/inspector/rules_test.go +++ b/internal/ingress/inspector/rules_test.go @@ -19,7 +19,6 @@ package inspector import "testing" func TestCheckRegex(t *testing.T) { - tests := []struct { name string value string diff --git a/internal/ingress/inspector/service.go b/internal/ingress/inspector/service.go index 27ed27a8c..8be08490b 100644 --- a/internal/ingress/inspector/service.go +++ b/internal/ingress/inspector/service.go @@ -21,6 +21,6 @@ import ( ) // InspectService will be used to inspect service objects for possible invalid configurations -func InspectService(svc *corev1.Service) error { +func InspectService(_ *corev1.Service) error { return nil } diff --git a/internal/ingress/metric/collectors/admission.go b/internal/ingress/metric/collectors/admission.go index cf42fbaa1..7b84325c0 100644 --- a/internal/ingress/metric/collectors/admission.go +++ b/internal/ingress/metric/collectors/admission.go @@ -104,7 +104,7 @@ func NewAdmissionCollector(pod, namespace, class string) *AdmissionCollector { } // Describe implements prometheus.Collector -func (am AdmissionCollector) Describe(ch chan<- *prometheus.Desc) { +func (am *AdmissionCollector) Describe(ch chan<- *prometheus.Desc) { am.testedIngressLength.Describe(ch) am.testedIngressTime.Describe(ch) am.renderingIngressLength.Describe(ch) @@ -114,7 +114,7 @@ func (am AdmissionCollector) Describe(ch chan<- *prometheus.Desc) { } // Collect implements the prometheus.Collector interface. -func (am AdmissionCollector) Collect(ch chan<- prometheus.Metric) { +func (am *AdmissionCollector) Collect(ch chan<- prometheus.Metric) { am.testedIngressLength.Collect(ch) am.testedIngressTime.Collect(ch) am.renderingIngressLength.Collect(ch) @@ -139,7 +139,7 @@ func ByteFormat(bytes int64) string { } // SetAdmissionMetrics sets the values for AdmissionMetrics that can be called externally -func (am *AdmissionCollector) SetAdmissionMetrics(testedIngressLength float64, testedIngressTime float64, renderingIngressLength float64, renderingIngressTime float64, testedConfigurationSize float64, admissionTime float64) { +func (am *AdmissionCollector) SetAdmissionMetrics(testedIngressLength, testedIngressTime, renderingIngressLength, renderingIngressTime, testedConfigurationSize, admissionTime float64) { am.testedIngressLength.Set(testedIngressLength) am.testedIngressTime.Set(testedIngressTime) am.renderingIngressLength.Set(renderingIngressLength) diff --git a/internal/ingress/metric/collectors/controller.go b/internal/ingress/metric/collectors/controller.go index 3a65a1a99..e1d6789bb 100644 --- a/internal/ingress/metric/collectors/controller.go +++ b/internal/ingress/metric/collectors/controller.go @@ -226,7 +226,7 @@ func (cm *Controller) IncCheckErrorCount(namespace, name string) { } // IncOrphanIngress sets the the orphaned ingress gauge to one -func (cm *Controller) IncOrphanIngress(namespace string, name string, orphanityType string) { +func (cm *Controller) IncOrphanIngress(namespace, name, orphanityType string) { labels := prometheus.Labels{ "namespace": namespace, "ingress": name, @@ -236,7 +236,7 @@ func (cm *Controller) IncOrphanIngress(namespace string, name string, orphanityT } // DecOrphanIngress sets the the orphaned ingress gauge to zero (all services has their endpoints) -func (cm *Controller) DecOrphanIngress(namespace string, name string, orphanityType string) { +func (cm *Controller) DecOrphanIngress(namespace, name, orphanityType string) { labels := prometheus.Labels{ "namespace": namespace, "ingress": name, @@ -261,7 +261,7 @@ func (cm *Controller) ConfigSuccess(hash uint64, success bool) { } // Describe implements prometheus.Collector -func (cm Controller) Describe(ch chan<- *prometheus.Desc) { +func (cm *Controller) Describe(ch chan<- *prometheus.Desc) { cm.configHash.Describe(ch) cm.configSuccess.Describe(ch) cm.configSuccessTime.Describe(ch) @@ -277,7 +277,7 @@ func (cm Controller) Describe(ch chan<- *prometheus.Desc) { } // Collect implements the prometheus.Collector interface. -func (cm Controller) Collect(ch chan<- prometheus.Metric) { +func (cm *Controller) Collect(ch chan<- prometheus.Metric) { cm.configHash.Collect(ch) cm.configSuccess.Collect(ch) cm.configSuccessTime.Collect(ch) @@ -295,41 +295,45 @@ func (cm Controller) Collect(ch chan<- prometheus.Metric) { // SetSSLExpireTime sets the expiration time of SSL Certificates func (cm *Controller) SetSSLExpireTime(servers []*ingress.Server) { for _, s := range servers { - if s.Hostname != "" && s.SSLCert != nil && s.SSLCert.ExpireTime.Unix() > 0 { - labels := make(prometheus.Labels, len(cm.labels)+1) - for k, v := range cm.labels { - labels[k] = v - } - labels["host"] = s.Hostname - labels["secret_name"] = s.SSLCert.Name - - cm.sslExpireTime.With(labels).Set(float64(s.SSLCert.ExpireTime.Unix())) + if !(s.Hostname != "" && s.SSLCert != nil && s.SSLCert.ExpireTime.Unix() > 0) { + continue } + + labels := make(prometheus.Labels, len(cm.labels)+1) + for k, v := range cm.labels { + labels[k] = v + } + labels["host"] = s.Hostname + labels["secret_name"] = s.SSLCert.Name + + cm.sslExpireTime.With(labels).Set(float64(s.SSLCert.ExpireTime.Unix())) } } // SetSSLInfo creates a metric with all certificates informations func (cm *Controller) SetSSLInfo(servers []*ingress.Server) { for _, s := range servers { - if s.SSLCert != nil && s.SSLCert.Certificate != nil && s.SSLCert.Certificate.SerialNumber != nil { - labels := make(prometheus.Labels, len(cm.labels)+1) - for k, v := range cm.labels { - labels[k] = v - } - labels["identifier"] = s.SSLCert.Identifier() - labels["host"] = s.Hostname - labels["secret_name"] = s.SSLCert.Name - labels["namespace"] = s.SSLCert.Namespace - labels["issuer_common_name"] = s.SSLCert.Certificate.Issuer.CommonName - labels["issuer_organization"] = "" - if len(s.SSLCert.Certificate.Issuer.Organization) > 0 { - labels["issuer_organization"] = s.SSLCert.Certificate.Issuer.Organization[0] - } - labels["serial_number"] = s.SSLCert.Certificate.SerialNumber.String() - labels["public_key_algorithm"] = s.SSLCert.Certificate.PublicKeyAlgorithm.String() - - cm.sslInfo.With(labels).Set(1) + if s.SSLCert == nil || s.SSLCert.Certificate == nil || s.SSLCert.Certificate.SerialNumber == nil { + continue } + + labels := make(prometheus.Labels, len(cm.labels)+1) + for k, v := range cm.labels { + labels[k] = v + } + labels["identifier"] = s.SSLCert.Identifier() + labels["host"] = s.Hostname + labels["secret_name"] = s.SSLCert.Name + labels["namespace"] = s.SSLCert.Namespace + labels["issuer_common_name"] = s.SSLCert.Certificate.Issuer.CommonName + labels["issuer_organization"] = "" + if len(s.SSLCert.Certificate.Issuer.Organization) > 0 { + labels["issuer_organization"] = s.SSLCert.Certificate.Issuer.Organization[0] + } + labels["serial_number"] = s.SSLCert.Certificate.SerialNumber.String() + labels["public_key_algorithm"] = s.SSLCert.Certificate.PublicKeyAlgorithm.String() + + cm.sslInfo.With(labels).Set(1) } } diff --git a/internal/ingress/metric/collectors/controller_test.go b/internal/ingress/metric/collectors/controller_test.go index ef80bc96a..15735df42 100644 --- a/internal/ingress/metric/collectors/controller_test.go +++ b/internal/ingress/metric/collectors/controller_test.go @@ -76,9 +76,12 @@ func TestControllerCounters(t *testing.T) { { name: "should set SSL certificates metrics", test: func(cm *Controller) { - t1, _ := time.Parse( + t1, err := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") + if err != nil { + t.Errorf("unexpected error: %v", err) + } servers := []*ingress.Server{ { @@ -106,7 +109,6 @@ func TestControllerCounters(t *testing.T) { { name: "should set SSL certificates infos metrics", test: func(cm *Controller) { - servers := []*ingress.Server{ { Hostname: "demo", @@ -143,7 +145,6 @@ func TestControllerCounters(t *testing.T) { { name: "should ignore certificates without serial number", test: func(cm *Controller) { - servers := []*ingress.Server{ { Hostname: "demo", @@ -168,7 +169,6 @@ func TestControllerCounters(t *testing.T) { { name: "should ignore certificates with nil x509 pointer", test: func(cm *Controller) { - servers := []*ingress.Server{ { Hostname: "demo", @@ -193,7 +193,6 @@ func TestControllerCounters(t *testing.T) { { name: "should ignore servers without certificates", test: func(cm *Controller) { - servers := []*ingress.Server{ { Hostname: "demo", @@ -232,9 +231,12 @@ func TestRemoveMetrics(t *testing.T) { t.Errorf("registering collector failed: %s", err) } - t1, _ := time.Parse( + t1, err := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } servers := []*ingress.Server{ { @@ -279,10 +281,12 @@ func TestRemoveAllSSLMetrics(t *testing.T) { t.Errorf("registering collector failed: %s", err) } - t1, _ := time.Parse( + t1, err := time.Parse( time.RFC3339, "2012-11-01T22:08:41+00:00") - + if err != nil { + t.Errorf("unexpected error: %v", err) + } servers := []*ingress.Server{ { Hostname: "demo", diff --git a/internal/ingress/metric/collectors/nginx_status.go b/internal/ingress/metric/collectors/nginx_status.go index 5aaa787de..f3afdc334 100644 --- a/internal/ingress/metric/collectors/nginx_status.go +++ b/internal/ingress/metric/collectors/nginx_status.go @@ -75,7 +75,6 @@ type NGINXStatusCollector interface { // NewNGINXStatus returns a new prometheus collector the default nginx status module func NewNGINXStatus(podName, namespace, ingressClass string) (NGINXStatusCollector, error) { - p := nginxStatusCollector{ scrapeChan: make(chan scrapeRequest), } diff --git a/internal/ingress/metric/collectors/nginx_status_test.go b/internal/ingress/metric/collectors/nginx_status_test.go index 4dc67c425..ec535745d 100644 --- a/internal/ingress/metric/collectors/nginx_status_test.go +++ b/internal/ingress/metric/collectors/nginx_status_test.go @@ -106,7 +106,7 @@ func TestStatusCollector(t *testing.T) { server := &httptest.Server{ Listener: listener, - Config: &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + Config: &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //nolint:gosec // Ignore the gosec error in testing w.WriteHeader(http.StatusOK) if r.URL.Path == "/nginx_status" { diff --git a/internal/ingress/metric/collectors/process.go b/internal/ingress/metric/collectors/process.go index 23f533876..3803a47ae 100644 --- a/internal/ingress/metric/collectors/process.go +++ b/internal/ingress/metric/collectors/process.go @@ -53,6 +53,8 @@ type BinaryNameMatcher struct { // MatchAndName returns false if the match failed, otherwise // true and the resulting name. +// +//nolint:gocritic // nacl param cannot be a pointer since it's to implement common.MatchNamer interface func (em BinaryNameMatcher) MatchAndName(nacl common.ProcAttributes) (bool, string) { if len(nacl.Cmdline) == 0 { return false, "" @@ -94,8 +96,10 @@ type NGINXProcessCollector interface { Stop() } -var name = "nginx" -var binary = "/usr/bin/nginx" +var ( + name = "nginx" + binary = "/usr/bin/nginx" +) // NewNGINXProcess returns a new prometheus collector for the nginx process func NewNGINXProcess(pod, namespace, ingressClass string) (NGINXProcessCollector, error) { @@ -106,7 +110,7 @@ func NewNGINXProcess(pod, namespace, ingressClass string) (NGINXProcessCollector nm := newBinaryNameMatcher(name, binary) - p := namedProcess{ + p := &namedProcess{ scrapeChan: make(chan scrapeRequest), Grouper: proc.NewGrouper(nm, true, false, false, false), fs: fs, @@ -164,7 +168,7 @@ func NewNGINXProcess(pod, namespace, ingressClass string) (NGINXProcessCollector } // Describe implements prometheus.Collector. -func (p namedProcess) Describe(ch chan<- *prometheus.Desc) { +func (p *namedProcess) Describe(ch chan<- *prometheus.Desc) { ch <- p.data.cpuSecs ch <- p.data.numProcs ch <- p.data.readBytes @@ -175,13 +179,13 @@ func (p namedProcess) Describe(ch chan<- *prometheus.Desc) { } // Collect implements prometheus.Collector. -func (p namedProcess) Collect(ch chan<- prometheus.Metric) { +func (p *namedProcess) Collect(ch chan<- prometheus.Metric) { req := scrapeRequest{results: ch, done: make(chan struct{})} p.scrapeChan <- req <-req.done } -func (p namedProcess) Start() { +func (p *namedProcess) Start() { for req := range p.scrapeChan { ch := req.results p.scrape(ch) @@ -189,18 +193,19 @@ func (p namedProcess) Start() { } } -func (p namedProcess) Stop() { +func (p *namedProcess) Stop() { close(p.scrapeChan) } -func (p namedProcess) scrape(ch chan<- prometheus.Metric) { +func (p *namedProcess) scrape(ch chan<- prometheus.Metric) { _, groups, err := p.Update(p.fs.AllProcs()) if err != nil { klog.Warningf("unexpected error obtaining nginx process info: %v", err) return } - for _, gcounts := range groups { + for i := range groups { + gcounts := groups[i] ch <- prometheus.MustNewConstMetric(p.data.numProcs, prometheus.GaugeValue, float64(gcounts.Procs)) ch <- prometheus.MustNewConstMetric(p.data.memResidentbytes, diff --git a/internal/ingress/metric/collectors/process_test.go b/internal/ingress/metric/collectors/process_test.go index b21d95496..588cbafef 100644 --- a/internal/ingress/metric/collectors/process_test.go +++ b/internal/ingress/metric/collectors/process_test.go @@ -48,8 +48,11 @@ func TestProcessCollector(t *testing.T) { done := make(chan struct{}) go func() { - cmd.Wait() //nolint:errcheck - status := cmd.ProcessState.Sys().(syscall.WaitStatus) + cmd.Wait() //nolint:errcheck // Ignore the error + status, ok := cmd.ProcessState.Sys().(syscall.WaitStatus) + if !ok { + t.Errorf("unexpected type: %T", cmd.ProcessState.Sys()) + } if status.Signaled() { t.Logf("Signal: %v", status.Signal()) } else { @@ -69,7 +72,7 @@ func TestProcessCollector(t *testing.T) { defer func() { cm.Stop() - cmd.Process.Kill() //nolint:errcheck + cmd.Process.Kill() //nolint:errcheck // Ignore the error <-done close(done) }() diff --git a/internal/ingress/metric/collectors/socket.go b/internal/ingress/metric/collectors/socket.go index 508cc6bc8..a70024c57 100644 --- a/internal/ingress/metric/collectors/socket.go +++ b/internal/ingress/metric/collectors/socket.go @@ -44,14 +44,11 @@ type socketData struct { Latency float64 `json:"upstreamLatency"` HeaderTime float64 `json:"upstreamHeaderTime"` ResponseTime float64 `json:"upstreamResponseTime"` - //ResponseLength float64 `json:"upstreamResponseLength"` - //Status string `json:"upstreamStatus"` - - Namespace string `json:"namespace"` - Ingress string `json:"ingress"` - Service string `json:"service"` - Canary string `json:"canary"` - Path string `json:"path"` + Namespace string `json:"namespace"` + Ingress string `json:"ingress"` + Service string `json:"service"` + Canary string `json:"canary"` + Path string `json:"path"` } // HistogramBuckets allow customizing prometheus histogram buckets values @@ -89,19 +86,17 @@ type SocketCollector struct { reportStatusClasses bool } -var ( - requestTags = []string{ - "status", +var requestTags = []string{ + "status", - "method", - "path", + "method", + "path", - "namespace", - "ingress", - "service", - "canary", - } -) + "namespace", + "ingress", + "service", + "canary", +} // DefObjectives was removed in https://github.com/prometheus/client_golang/pull/262 // updating the library to latest version changed the output of the metrics @@ -112,6 +107,7 @@ var defObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001} func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStatusClasses bool, buckets HistogramBuckets, excludeMetrics []string) (*SocketCollector, error) { socket := "/tmp/nginx/prometheus-nginx.socket" // unix sockets must be unlink()ed before being used + //nolint:errcheck // Ignore unlink error _ = syscall.Unlink(socket) listener, err := net.Listen("unix", socket) @@ -119,7 +115,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat return nil, err } - err = os.Chmod(socket, 0777) // #nosec + err = os.Chmod(socket, 0o777) // #nosec if err != nil { return nil, err } @@ -152,7 +148,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat reportStatusClasses: reportStatusClasses, connectTime: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "connect_duration_seconds", Help: "The time spent on establishing a connection with the upstream server", Namespace: PrometheusNamespace, @@ -165,7 +161,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), headerTime: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "header_duration_seconds", Help: "The time spent on receiving first header from the upstream server", Namespace: PrometheusNamespace, @@ -177,7 +173,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat mm, ), responseTime: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "response_duration_seconds", Help: "The time spent on receiving the response from the upstream server", Namespace: PrometheusNamespace, @@ -190,7 +186,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), requestTime: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "request_duration_seconds", Help: "The request processing time in milliseconds", Namespace: PrometheusNamespace, @@ -203,7 +199,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), responseLength: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "response_size", Help: "The response length (including request line, header, and request body)", Namespace: PrometheusNamespace, @@ -216,7 +212,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), requestLength: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "request_size", Help: "The request length (including request line, header, and request body)", Namespace: PrometheusNamespace, @@ -229,7 +225,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), requests: counterMetric( - prometheus.CounterOpts{ + &prometheus.CounterOpts{ Name: "requests", Help: "The total number of client requests", Namespace: PrometheusNamespace, @@ -241,7 +237,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), bytesSent: histogramMetric( - prometheus.HistogramOpts{ + &prometheus.HistogramOpts{ Name: "bytes_sent", Help: "DEPRECATED The number of bytes sent to a client", Namespace: PrometheusNamespace, @@ -254,7 +250,7 @@ func NewSocketCollector(pod, namespace, class string, metricsPerHost, reportStat ), upstreamLatency: summaryMetric( - prometheus.SummaryOpts{ + &prometheus.SummaryOpts{ Name: "ingress_upstream_latency_seconds", Help: "DEPRECATED Upstream service latency per Ingress", Namespace: PrometheusNamespace, @@ -279,36 +275,36 @@ func containsMetric(excludeMetrics map[string]struct{}, name string) bool { return false } -func summaryMetric(opts prometheus.SummaryOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.SummaryVec { +func summaryMetric(opts *prometheus.SummaryOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.SummaryVec { if containsMetric(excludeMetrics, opts.Name) { return nil } m := prometheus.NewSummaryVec( - opts, + *opts, requestTags, ) metricMapping[prometheus.BuildFQName(PrometheusNamespace, "", opts.Name)] = m return m } -func counterMetric(opts prometheus.CounterOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.CounterVec { +func counterMetric(opts *prometheus.CounterOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.CounterVec { if containsMetric(excludeMetrics, opts.Name) { return nil } m := prometheus.NewCounterVec( - opts, + *opts, requestTags, ) metricMapping[prometheus.BuildFQName(PrometheusNamespace, "", opts.Name)] = m return m } -func histogramMetric(opts prometheus.HistogramOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.HistogramVec { +func histogramMetric(opts *prometheus.HistogramOpts, requestTags []string, excludeMetrics map[string]struct{}, metricMapping metricMapping) *prometheus.HistogramVec { if containsMetric(excludeMetrics, opts.Name) { return nil } m := prometheus.NewHistogramVec( - opts, + *opts, requestTags, ) metricMapping[prometheus.BuildFQName(PrometheusNamespace, "", opts.Name)] = m @@ -326,7 +322,8 @@ func (sc *SocketCollector) handleMessage(msg []byte) { return } - for _, stats := range statsBatch { + for i := range statsBatch { + stats := &statsBatch[i] if sc.metricsPerHost && !sc.hosts.Has(stats.Host) { klog.V(3).InfoS("Skipping metric for host not being served", "host", stats.Host) continue @@ -543,14 +540,14 @@ func (sc *SocketCollector) RemoveMetrics(ingresses []string, registry prometheus } // Describe implements prometheus.Collector -func (sc SocketCollector) Describe(ch chan<- *prometheus.Desc) { +func (sc *SocketCollector) Describe(ch chan<- *prometheus.Desc) { for _, metric := range sc.metricMapping { metric.Describe(ch) } } // Collect implements the prometheus.Collector interface. -func (sc SocketCollector) Collect(ch chan<- prometheus.Metric) { +func (sc *SocketCollector) Collect(ch chan<- prometheus.Metric) { for _, metric := range sc.metricMapping { metric.Collect(ch) } diff --git a/internal/ingress/metric/collectors/socket_test.go b/internal/ingress/metric/collectors/socket_test.go index 6000f2685..71e9097c9 100644 --- a/internal/ingress/metric/collectors/socket_test.go +++ b/internal/ingress/metric/collectors/socket_test.go @@ -30,6 +30,7 @@ import ( func TestNewUDPLogListener(t *testing.T) { var count uint64 + //nolint:unparam // Unused `message` param is required by the handleMessages function fn := func(message []byte) { atomic.AddUint64(&count, 1) } @@ -57,7 +58,10 @@ func TestNewUDPLogListener(t *testing.T) { } }() - conn, _ := net.Dial("unix", tmpFile) + conn, err := net.Dial("unix", tmpFile) + if err != nil { + t.Errorf("unexpected error connecting to unix socket: %v", err) + } if _, err := conn.Write([]byte("message")); err != nil { t.Errorf("unexpected error writing to unix socket: %v", err) } @@ -70,7 +74,6 @@ func TestNewUDPLogListener(t *testing.T) { } func TestCollector(t *testing.T) { - buckets := struct { TimeBuckets []float64 LengthBuckets []float64 diff --git a/internal/ingress/metric/collectors/testutils.go b/internal/ingress/metric/collectors/testutils.go index 8c5c27b62..669e89e17 100644 --- a/internal/ingress/metric/collectors/testutils.go +++ b/internal/ingress/metric/collectors/testutils.go @@ -31,7 +31,7 @@ import ( // GatherAndCompare retrieves all metrics exposed by a collector and compares it // to an expected output in the Prometheus text exposition format. // metricNames allows only comparing the given metrics. All are compared if it's nil. -func GatherAndCompare(c prometheus.Collector, expected string, metricNames []string, reg prometheus.Gatherer) error { +func GatherAndCompare(_ prometheus.Collector, expected string, metricNames []string, reg prometheus.Gatherer) error { expected = removeUnusedWhitespace(expected) metrics, err := reg.Gather() @@ -77,9 +77,7 @@ metric output does not match expectation; want: got: -'%s' - -`, buf2.String(), buf1.String()) +'%s'`, buf2.String(), buf1.String()) } return nil } diff --git a/internal/ingress/metric/dummy.go b/internal/ingress/metric/dummy.go index d8ae0155a..a619ccbd8 100644 --- a/internal/ingress/metric/dummy.go +++ b/internal/ingress/metric/dummy.go @@ -29,50 +29,50 @@ func NewDummyCollector() Collector { // DummyCollector dummy implementation for mocks in tests type DummyCollector struct{} -// ConfigSuccess ... +// ConfigSuccess dummy implementation func (dc DummyCollector) ConfigSuccess(uint64, bool) {} -// SetAdmissionMetrics ... +// SetAdmissionMetrics dummy implementation func (dc DummyCollector) SetAdmissionMetrics(float64, float64, float64, float64, float64, float64) {} -// IncReloadCount ... +// IncReloadCount dummy implementation func (dc DummyCollector) IncReloadCount() {} -// IncReloadErrorCount ... +// IncReloadErrorCount dummy implementation func (dc DummyCollector) IncReloadErrorCount() {} -// IncOrphanIngress ... +// IncOrphanIngress dummy implementation func (dc DummyCollector) IncOrphanIngress(string, string, string) {} -// DecOrphanIngress ... +// DecOrphanIngress dummy implementation func (dc DummyCollector) DecOrphanIngress(string, string, string) {} -// IncCheckCount ... +// IncCheckCount dummy implementation func (dc DummyCollector) IncCheckCount(string, string) {} -// IncCheckErrorCount ... +// IncCheckErrorCount dummy implementation func (dc DummyCollector) IncCheckErrorCount(string, string) {} -// RemoveMetrics ... -func (dc DummyCollector) RemoveMetrics(ingresses, endpoints, certificates []string) {} +// RemoveMetrics dummy implementation +func (dc DummyCollector) RemoveMetrics(_, _, _ []string) {} -// Start ... -func (dc DummyCollector) Start(admissionStatus string) {} +// Start dummy implementation +func (dc DummyCollector) Start(_ string) {} -// Stop ... -func (dc DummyCollector) Stop(admissionStatus string) {} +// Stop dummy implementation +func (dc DummyCollector) Stop(_ string) {} -// SetSSLInfo ... +// SetSSLInfo dummy implementation func (dc DummyCollector) SetSSLInfo([]*ingress.Server) {} -// SetSSLExpireTime ... +// SetSSLExpireTime dummy implementation func (dc DummyCollector) SetSSLExpireTime([]*ingress.Server) {} -// SetHosts ... -func (dc DummyCollector) SetHosts(hosts sets.Set[string]) {} +// SetHosts dummy implementation +func (dc DummyCollector) SetHosts(_ sets.Set[string]) {} // OnStartedLeading indicates the pod is not the current leader -func (dc DummyCollector) OnStartedLeading(electionID string) {} +func (dc DummyCollector) OnStartedLeading(_ string) {} // OnStoppedLeading indicates the pod is not the current leader -func (dc DummyCollector) OnStoppedLeading(electionID string) {} +func (dc DummyCollector) OnStoppedLeading(_ string) {} diff --git a/internal/ingress/metric/main.go b/internal/ingress/metric/main.go index b2f721f62..aa35a5c51 100644 --- a/internal/ingress/metric/main.go +++ b/internal/ingress/metric/main.go @@ -115,11 +115,11 @@ func (c *collector) ConfigSuccess(hash uint64, success bool) { c.ingressController.ConfigSuccess(hash, success) } -func (c *collector) IncCheckCount(namespace string, name string) { +func (c *collector) IncCheckCount(namespace, name string) { c.ingressController.IncCheckCount(namespace, name) } -func (c *collector) IncCheckErrorCount(namespace string, name string) { +func (c *collector) IncCheckErrorCount(namespace, name string) { c.ingressController.IncCheckErrorCount(namespace, name) } @@ -183,11 +183,11 @@ func (c *collector) SetSSLInfo(servers []*ingress.Server) { c.ingressController.SetSSLInfo(servers) } -func (c *collector) IncOrphanIngress(namespace string, name string, orphanityType string) { +func (c *collector) IncOrphanIngress(namespace, name, orphanityType string) { c.ingressController.IncOrphanIngress(namespace, name, orphanityType) } -func (c *collector) DecOrphanIngress(namespace string, name string, orphanityType string) { +func (c *collector) DecOrphanIngress(namespace, name, orphanityType string) { c.ingressController.DecOrphanIngress(namespace, name, orphanityType) } @@ -195,7 +195,7 @@ func (c *collector) SetHosts(hosts sets.Set[string]) { c.socket.SetHosts(hosts) } -func (c *collector) SetAdmissionMetrics(testedIngressLength float64, testedIngressTime float64, renderingIngressLength float64, renderingIngressTime float64, testedConfigurationSize float64, admissionTime float64) { +func (c *collector) SetAdmissionMetrics(testedIngressLength, testedIngressTime, renderingIngressLength, renderingIngressTime, testedConfigurationSize, admissionTime float64) { c.admissionController.SetAdmissionMetrics( testedIngressLength, testedIngressTime, @@ -219,9 +219,7 @@ func (c *collector) OnStoppedLeading(electionID string) { c.ingressController.RemoveAllSSLMetrics(c.registry) } -var ( - currentLeader uint32 -) +var currentLeader uint32 func setLeader(leader bool) { var i uint32 diff --git a/internal/ingress/status/status.go b/internal/ingress/status/status.go index 62b88da16..81fb9044a 100644 --- a/internal/ingress/status/status.go +++ b/internal/ingress/status/status.go @@ -44,7 +44,7 @@ import ( // which the status should check if an update is required. var UpdateInterval = 60 -// Syncer ... +// Syncer is an interface that implements syncer type Syncer interface { Run(chan struct{}) @@ -56,7 +56,7 @@ type ingressLister interface { ListIngresses() []*ingress.Ingress } -// Config ... +// Config is a structure that implements Client interfaces type Config struct { Client clientset.Interface @@ -87,7 +87,7 @@ type statusSync struct { } // Start starts the loop to keep the status in sync -func (s statusSync) Run(stopCh chan struct{}) { +func (s *statusSync) Run(stopCh chan struct{}) { go s.syncQueue.Run(time.Second, stopCh) // trigger initial sync @@ -95,6 +95,7 @@ func (s statusSync) Run(stopCh chan struct{}) { // when this instance is the leader we need to enqueue // an item to trigger the update of the Ingress status. + //nolint:staticcheck // TODO: will replace it since wait.PollUntil is deprecated err := wait.PollUntil(time.Duration(UpdateInterval)*time.Second, func() (bool, error) { s.syncQueue.EnqueueTask(task.GetDummyObject("sync status")) return false, nil @@ -106,7 +107,7 @@ func (s statusSync) Run(stopCh chan struct{}) { // Shutdown stops the sync. In case the instance is the leader it will remove the current IP // if there is no other instances running. -func (s statusSync) Shutdown() { +func (s *statusSync) Shutdown() { go s.syncQueue.Shutdown() if !s.UpdateStatusOnShutdown { @@ -135,7 +136,7 @@ func (s statusSync) Shutdown() { s.updateStatus([]v1.IngressLoadBalancerIngress{}) } -func (s *statusSync) sync(key interface{}) error { +func (s *statusSync) sync(_ interface{}) error { if s.syncQueue.IsShuttingDown() { klog.V(2).InfoS("skipping Ingress status update (shutting down in progress)") return nil @@ -150,13 +151,13 @@ func (s *statusSync) sync(key interface{}) error { return nil } -func (s statusSync) keyfunc(input interface{}) (interface{}, error) { +func (s *statusSync) keyfunc(input interface{}) (interface{}, error) { return input, nil } // NewStatusSyncer returns a new Syncer instance func NewStatusSyncer(config Config) Syncer { - st := statusSync{ + st := &statusSync{ Config: config, } st.syncQueue = task.NewCustomTaskQueue(st.sync, st.keyfunc) @@ -229,7 +230,6 @@ func (s *statusSync) runningAddresses() ([]v1.IngressLoadBalancerIngress, error) } func (s *statusSync) isRunningMultiplePods() bool { - // As a standard, app.kubernetes.io are "reserved well-known" labels. // In our case, we add those labels as identifiers of the Ingress // deployment in this namespace, so we can select it as a set of Ingress instances. @@ -288,7 +288,8 @@ func (s *statusSync) updateStatus(newIngressPoint []v1.IngressLoadBalancerIngres } func runUpdate(ing *ingress.Ingress, status []v1.IngressLoadBalancerIngress, - client clientset.Interface) pool.WorkFunc { + client clientset.Interface, +) pool.WorkFunc { return func(wu pool.WorkUnit) (interface{}, error) { if wu.IsCancelled() { return nil, nil @@ -341,7 +342,10 @@ func ingressSliceEqual(lhs, rhs []v1.IngressLoadBalancerIngress) bool { } func statusAddressFromService(service string, kubeClient clientset.Interface) ([]v1.IngressLoadBalancerIngress, error) { - ns, name, _ := k8s.ParseNameNS(service) + ns, name, err := k8s.ParseNameNS(service) + if err != nil { + return nil, err + } svc, err := kubeClient.CoreV1().Services(ns).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return nil, err @@ -362,15 +366,15 @@ func statusAddressFromService(service string, kubeClient clientset.Interface) ([ IP: svc.Spec.ClusterIP, }}, nil } - addrs := make([]v1.IngressLoadBalancerIngress, len(svc.Spec.ExternalIPs)) - for i, ip := range svc.Spec.ExternalIPs { - addrs[i] = v1.IngressLoadBalancerIngress{IP: ip} + addrs := make([]v1.IngressLoadBalancerIngress, 0, len(svc.Spec.ExternalIPs)) + for _, ip := range svc.Spec.ExternalIPs { + addrs = append(addrs, v1.IngressLoadBalancerIngress{IP: ip}) } return addrs, nil case apiv1.ServiceTypeLoadBalancer: - addrs := make([]v1.IngressLoadBalancerIngress, len(svc.Status.LoadBalancer.Ingress)) + addrs := make([]v1.IngressLoadBalancerIngress, 0, len(svc.Status.LoadBalancer.Ingress)) for i, ingress := range svc.Status.LoadBalancer.Ingress { - addrs[i] = v1.IngressLoadBalancerIngress{} + addrs = append(addrs, v1.IngressLoadBalancerIngress{}) if ingress.Hostname != "" { addrs[i].Hostname = ingress.Hostname } diff --git a/internal/ingress/status/status_test.go b/internal/ingress/status/status_test.go index ce6b6a0bf..01419708b 100644 --- a/internal/ingress/status/status_test.go +++ b/internal/ingress/status/status_test.go @@ -18,7 +18,6 @@ package status import ( "context" - "os" "reflect" "testing" "time" @@ -34,6 +33,8 @@ import ( "k8s.io/ingress-nginx/pkg/apis/ingress" ) +const localhost = "127.0.0.1" + func buildLoadBalancerIngressByIP() []networking.IngressLoadBalancerIngress { return []networking.IngressLoadBalancerIngress{ { @@ -126,17 +127,6 @@ func buildSimpleClientSet() *testclient.Clientset { // This is commented out as the ServiceStatus.LoadBalancer field expects a LoadBalancerStatus object // which is incompatible with the current Ingress struct which expects a IngressLoadBalancerStatus object // TODO: update this service when the ServiceStatus struct gets updated - //{ - // ObjectMeta: metav1.ObjectMeta{ - // Name: "foo", - // Namespace: apiv1.NamespaceDefault, - // }, - // Status: apiv1.ServiceStatus{ - // LoadBalancer: apiv1.LoadBalancerStatus{ - // Ingress: buildLoadBalancerIngressByIP(), - // }, - // }, - //}, { ObjectMeta: metav1.ObjectMeta{ Name: "foo_non_exist", @@ -185,7 +175,8 @@ func buildSimpleClientSet() *testclient.Clientset { Name: "ingress-controller-leader", Namespace: apiv1.NamespaceDefault, }, - }}}, + }, + }}, &networking.IngressList{Items: buildExtensionsIngresses()}, ) } @@ -245,30 +236,33 @@ func buildExtensionsIngresses() []networking.Ingress { } } -type testIngressLister struct { -} +type testIngressLister struct{} func (til *testIngressLister) ListIngresses() []*ingress.Ingress { var ingresses []*ingress.Ingress - ingresses = append(ingresses, &ingress.Ingress{ - Ingress: networking.Ingress{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo_ingress_non_01", - Namespace: apiv1.NamespaceDefault, - }}}) - - ingresses = append(ingresses, &ingress.Ingress{ - Ingress: networking.Ingress{ - ObjectMeta: metav1.ObjectMeta{ - Name: "foo_ingress_1", - Namespace: apiv1.NamespaceDefault, - }, - Status: networking.IngressStatus{ - LoadBalancer: networking.IngressLoadBalancerStatus{ - Ingress: buildLoadBalancerIngressByIP(), + ingresses = append(ingresses, + &ingress.Ingress{ + Ingress: networking.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "foo_ingress_non_01", + Namespace: apiv1.NamespaceDefault, }, }, - }}) + }, + &ingress.Ingress{ + Ingress: networking.Ingress{ + ObjectMeta: metav1.ObjectMeta{ + Name: "foo_ingress_1", + Namespace: apiv1.NamespaceDefault, + }, + Status: networking.IngressStatus{ + LoadBalancer: networking.IngressLoadBalancerStatus{ + Ingress: buildLoadBalancerIngressByIP(), + }, + }, + }, + }, + ) return ingresses } @@ -290,8 +284,8 @@ func buildStatusSync() statusSync { func TestStatusActions(t *testing.T) { // make sure election can be created - os.Setenv("POD_NAME", "foo1") - os.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) + t.Setenv("POD_NAME", "foo1") + t.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) c := Config{ Client: buildSimpleClientSet(), PublishService: "", @@ -315,7 +309,10 @@ func TestStatusActions(t *testing.T) { t.Fatalf("expected a valid Sync") } - fk := fkSync.(statusSync) + fk, ok := fkSync.(*statusSync) + if !ok { + t.Errorf("unexpected type: %T", fkSync) + } // start it and wait for the election and syn actions stopCh := make(chan struct{}) @@ -366,7 +363,7 @@ func TestStatusActions(t *testing.T) { } } -func TestCallback(t *testing.T) { +func TestCallback(_ *testing.T) { buildStatusSync() } @@ -375,7 +372,6 @@ func TestKeyfunc(t *testing.T) { i := "foo_base_pod" r, err := fk.keyfunc(i) - if err != nil { t.Fatalf("unexpected error") } @@ -392,34 +388,36 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }{ "service type ClusterIP": { testclient.NewSimpleClientset( - &apiv1.PodList{Items: []apiv1.Pod{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.PodSpec{ - NodeName: "foo_node", - }, - Status: apiv1.PodStatus{ - Phase: apiv1.PodRunning, + &apiv1.PodList{ + Items: []apiv1.Pod{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.PodSpec{ + NodeName: "foo_node", + }, + Status: apiv1.PodStatus{ + Phase: apiv1.PodRunning, + }, }, }, }, - }, - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.ServiceSpec{ - Type: apiv1.ServiceTypeClusterIP, - ClusterIP: "1.1.1.1", + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.ServiceSpec{ + Type: apiv1.ServiceTypeClusterIP, + ClusterIP: "1.1.1.1", + }, }, }, }, - }, ), []networking.IngressLoadBalancerIngress{ {IP: "1.1.1.1"}, @@ -428,19 +426,20 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }, "service type NodePort": { testclient.NewSimpleClientset( - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.ServiceSpec{ - Type: apiv1.ServiceTypeNodePort, - ClusterIP: "1.1.1.1", + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.ServiceSpec{ + Type: apiv1.ServiceTypeNodePort, + ClusterIP: "1.1.1.1", + }, }, }, }, - }, ), []networking.IngressLoadBalancerIngress{ {IP: "1.1.1.1"}, @@ -449,19 +448,20 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }, "service type ExternalName": { testclient.NewSimpleClientset( - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.ServiceSpec{ - Type: apiv1.ServiceTypeExternalName, - ExternalName: "foo.bar", + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.ServiceSpec{ + Type: apiv1.ServiceTypeExternalName, + ExternalName: "foo.bar", + }, }, }, }, - }, ), []networking.IngressLoadBalancerIngress{ {Hostname: "foo.bar"}, @@ -470,35 +470,36 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }, "service type LoadBalancer": { testclient.NewSimpleClientset( - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.ServiceSpec{ - Type: apiv1.ServiceTypeLoadBalancer, - }, - Status: apiv1.ServiceStatus{ - LoadBalancer: apiv1.LoadBalancerStatus{ - Ingress: []apiv1.LoadBalancerIngress{ - { - IP: "10.0.0.1", - }, - { - IP: "", - Hostname: "foo", - }, - { - IP: "10.0.0.2", - Hostname: "10-0-0-2.cloudprovider.example.net", + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.ServiceSpec{ + Type: apiv1.ServiceTypeLoadBalancer, + }, + Status: apiv1.ServiceStatus{ + LoadBalancer: apiv1.LoadBalancerStatus{ + Ingress: []apiv1.LoadBalancerIngress{ + { + IP: "10.0.0.1", + }, + { + IP: "", + Hostname: "foo", + }, + { + IP: "10.0.0.2", + Hostname: "10-0-0-2.cloudprovider.example.net", + }, }, }, }, }, }, }, - }, ), []networking.IngressLoadBalancerIngress{ {IP: "10.0.0.1"}, @@ -512,28 +513,29 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }, "service type LoadBalancer with same externalIP and ingress IP": { testclient.NewSimpleClientset( - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, - }, - Spec: apiv1.ServiceSpec{ - Type: apiv1.ServiceTypeLoadBalancer, - ExternalIPs: []string{"10.0.0.1"}, - }, - Status: apiv1.ServiceStatus{ - LoadBalancer: apiv1.LoadBalancerStatus{ - Ingress: []apiv1.LoadBalancerIngress{ - { - IP: "10.0.0.1", + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, + Spec: apiv1.ServiceSpec{ + Type: apiv1.ServiceTypeLoadBalancer, + ExternalIPs: []string{"10.0.0.1"}, + }, + Status: apiv1.ServiceStatus{ + LoadBalancer: apiv1.LoadBalancerStatus{ + Ingress: []apiv1.LoadBalancerIngress{ + { + IP: "10.0.0.1", + }, }, }, }, }, }, }, - }, ), []networking.IngressLoadBalancerIngress{ {IP: "10.0.0.1"}, @@ -542,15 +544,16 @@ func TestRunningAddressesWithPublishService(t *testing.T) { }, "invalid service type": { testclient.NewSimpleClientset( - &apiv1.ServiceList{Items: []apiv1.Service{ - { - ObjectMeta: metav1.ObjectMeta{ - Name: "foo", - Namespace: apiv1.NamespaceDefault, + &apiv1.ServiceList{ + Items: []apiv1.Service{ + { + ObjectMeta: metav1.ObjectMeta{ + Name: "foo", + Namespace: apiv1.NamespaceDefault, + }, }, }, }, - }, ), nil, true, @@ -559,7 +562,6 @@ func TestRunningAddressesWithPublishService(t *testing.T) { for title, tc := range testCases { t.Run(title, func(t *testing.T) { - fk := buildStatusSync() fk.Config.Client = tc.fakeClient @@ -587,7 +589,11 @@ func TestRunningAddressesWithPods(t *testing.T) { fk := buildStatusSync() fk.PublishService = "" - r, _ := fk.runningAddresses() + r, err := fk.runningAddresses() + if err != nil { + t.Errorf("unexpected error: %v", err) + } + if r == nil { t.Fatalf("returned nil but expected valid []networking.IngressLoadBalancerIngress") } @@ -603,9 +609,12 @@ func TestRunningAddressesWithPods(t *testing.T) { func TestRunningAddressesWithPublishStatusAddress(t *testing.T) { fk := buildStatusSync() - fk.PublishStatusAddress = "127.0.0.1" + fk.PublishStatusAddress = localhost - ra, _ := fk.runningAddresses() + ra, err := fk.runningAddresses() + if err != nil { + t.Errorf("unexpected error: %v", err) + } if ra == nil { t.Fatalf("returned nil but expected valid []networking.IngressLoadBalancerIngress") } @@ -614,8 +623,8 @@ func TestRunningAddressesWithPublishStatusAddress(t *testing.T) { t.Errorf("returned %v but expected %v", rl, 1) } rv := ra[0] - if rv.IP != "127.0.0.1" { - t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: "127.0.0.1"}) + if rv.IP != localhost { + t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: localhost}) } } @@ -623,7 +632,10 @@ func TestRunningAddressesWithPublishStatusAddresses(t *testing.T) { fk := buildStatusSync() fk.PublishStatusAddress = "127.0.0.1,1.1.1.1" - ra, _ := fk.runningAddresses() + ra, err := fk.runningAddresses() + if err != nil { + t.Errorf("unexpected error: %v", err) + } if ra == nil { t.Fatalf("returned nil but expected valid []networking.IngressLoadBalancerIngress") } @@ -633,8 +645,8 @@ func TestRunningAddressesWithPublishStatusAddresses(t *testing.T) { } rv := ra[0] rv2 := ra[1] - if rv.IP != "127.0.0.1" { - t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: "127.0.0.1"}) + if rv.IP != localhost { + t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: localhost}) } if rv2.IP != "1.1.1.1" { t.Errorf("returned %v but expected %v", rv2, networking.IngressLoadBalancerIngress{IP: "1.1.1.1"}) @@ -645,7 +657,10 @@ func TestRunningAddressesWithPublishStatusAddressesAndSpaces(t *testing.T) { fk := buildStatusSync() fk.PublishStatusAddress = "127.0.0.1, 1.1.1.1" - ra, _ := fk.runningAddresses() + ra, err := fk.runningAddresses() + if err != nil { + t.Errorf("unexpected error: %v", err) + } if ra == nil { t.Fatalf("returned nil but expected valid []networking.IngressLoadBalancerIngresst") } @@ -655,8 +670,8 @@ func TestRunningAddressesWithPublishStatusAddressesAndSpaces(t *testing.T) { } rv := ra[0] rv2 := ra[1] - if rv.IP != "127.0.0.1" { - t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: "127.0.0.1"}) + if rv.IP != localhost { + t.Errorf("returned %v but expected %v", rv, networking.IngressLoadBalancerIngress{IP: localhost}) } if rv2.IP != "1.1.1.1" { t.Errorf("returned %v but expected %v", rv2, networking.IngressLoadBalancerIngress{IP: "1.1.1.1"}) diff --git a/internal/k8s/main.go b/internal/k8s/main.go index d61013a9f..5e93e560d 100644 --- a/internal/k8s/main.go +++ b/internal/k8s/main.go @@ -33,7 +33,7 @@ import ( ) // ParseNameNS parses a string searching a namespace and name -func ParseNameNS(input string) (string, string, error) { +func ParseNameNS(input string) (ns, name string, err error) { nsName := strings.Split(input, "/") if len(nsName) != 2 { return "", "", fmt.Errorf("invalid format (namespace/name) found in '%v'", input) @@ -148,7 +148,10 @@ const IngressNGINXController = "k8s.io/ingress-nginx" // NetworkingIngressAvailable checks if the package "k8s.io/api/networking/v1" // is available or not and if Ingress V1 is supported (k8s >= v1.19.0) func NetworkingIngressAvailable(client clientset.Interface) bool { - version119, _ := version.ParseGeneric("v1.19.0") + version119, err := version.ParseGeneric("v1.19.0") + if err != nil { + return false + } serverVersion, err := client.Discovery().ServerVersion() if err != nil { diff --git a/internal/k8s/main_test.go b/internal/k8s/main_test.go index f3f8b652e..1721c1fb2 100644 --- a/internal/k8s/main_test.go +++ b/internal/k8s/main_test.go @@ -17,7 +17,6 @@ limitations under the License. package k8s import ( - "os" "testing" apiv1 "k8s.io/api/core/v1" @@ -203,7 +202,8 @@ func TestGetNodeIP(t *testing.T) { }, }, }}}), - "demo", "10.0.0.2", true}, + "demo", "10.0.0.2", true, + }, } for _, fk := range fKNodes { @@ -216,32 +216,32 @@ func TestGetNodeIP(t *testing.T) { func TestGetIngressPod(t *testing.T) { // POD_NAME & POD_NAMESPACE not exist - os.Setenv("POD_NAME", "") - os.Setenv("POD_NAMESPACE", "") + t.Setenv("POD_NAME", "") + t.Setenv("POD_NAMESPACE", "") err := GetIngressPod(testclient.NewSimpleClientset()) if err == nil { t.Errorf("expected an error but returned nil") } // POD_NAME not exist - os.Setenv("POD_NAME", "") - os.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) + t.Setenv("POD_NAME", "") + t.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) err = GetIngressPod(testclient.NewSimpleClientset()) if err == nil { t.Errorf("expected an error but returned nil") } // POD_NAMESPACE not exist - os.Setenv("POD_NAME", "testpod") - os.Setenv("POD_NAMESPACE", "") + t.Setenv("POD_NAME", "testpod") + t.Setenv("POD_NAMESPACE", "") err = GetIngressPod(testclient.NewSimpleClientset()) if err == nil { t.Errorf("expected an error but returned nil") } // POD not exist - os.Setenv("POD_NAME", "testpod") - os.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) + t.Setenv("POD_NAME", "testpod") + t.Setenv("POD_NAMESPACE", apiv1.NamespaceDefault) err = GetIngressPod(testclient.NewSimpleClientset()) if err == nil { t.Errorf("expected an error but returned nil") diff --git a/internal/net/dns/dns.go b/internal/net/dns/dns.go index 7dfbbd177..6b250e8cb 100644 --- a/internal/net/dns/dns.go +++ b/internal/net/dns/dns.go @@ -38,7 +38,7 @@ func GetSystemNameServers() ([]net.IP, error) { lines := strings.Split(string(file), "\n") for l := range lines { trimmed := strings.TrimSpace(lines[l]) - if len(trimmed) == 0 || trimmed[0] == '#' || trimmed[0] == ';' { + if trimmed == "" || trimmed[0] == '#' || trimmed[0] == ';' { continue } fields := strings.Fields(trimmed) diff --git a/internal/net/ipnet_test.go b/internal/net/ipnet_test.go index 95e6b9c32..8e460aae9 100644 --- a/internal/net/ipnet_test.go +++ b/internal/net/ipnet_test.go @@ -36,13 +36,17 @@ func TestNewIPSet(t *testing.T) { } func TestParseCIDRs(t *testing.T) { - cidr, _ := ParseCIDRs("invalid.com") + cidr, err := ParseCIDRs("invalid.com") + if err == nil { + t.Errorf("expected error but got nil") + } + if cidr != nil { t.Errorf("expected %v but got %v", nil, cidr) } expected := []string{"192.0.0.1", "192.0.1.0/24"} - cidr, err := ParseCIDRs("192.0.0.1, 192.0.1.0/24") + cidr, err = ParseCIDRs("192.0.0.1, 192.0.1.0/24") if err != nil { t.Errorf("unexpected error %v", err) } diff --git a/internal/net/net.go b/internal/net/net.go index 712262f3a..b0952d9cc 100644 --- a/internal/net/net.go +++ b/internal/net/net.go @@ -30,11 +30,12 @@ func IsIPV6(ip _net.IP) bool { // IsPortAvailable checks if a TCP port is available or not func IsPortAvailable(p int) bool { ln, err := _net.Listen("tcp", fmt.Sprintf(":%v", p)) - if err != nil { - return false - } - defer ln.Close() - return true + defer func() { + if ln != nil { + ln.Close() + } + }() + return err == nil } // IsIPv6Enabled checks if IPV6 is enabled or not and we have @@ -51,7 +52,10 @@ func IsIPv6Enabled() bool { } for _, addr := range addrs { - ip, _, _ := _net.ParseCIDR(addr.String()) + ip, _, err := _net.ParseCIDR(addr.String()) + if err != nil { + return false + } if IsIPV6(ip) { return true } diff --git a/internal/net/net_test.go b/internal/net/net_test.go index f2f37a838..f7a4f52e1 100644 --- a/internal/net/net_test.go +++ b/internal/net/net_test.go @@ -47,7 +47,7 @@ func TestIsPortAvailable(t *testing.T) { t.Fatal("expected port 0 to be available (random port) but returned false") } - ln, err := net.Listen("tcp", ":0") + ln, err := net.Listen("tcp", ":0") //nolint:gosec // Ignore the gosec error in testing if err != nil { t.Fatalf("unexpected error: %v", err) } diff --git a/internal/net/ssl/ssl.go b/internal/net/ssl/ssl.go index c74537fe9..516b1ec9c 100644 --- a/internal/net/ssl/ssl.go +++ b/internal/net/ssl/ssl.go @@ -52,17 +52,15 @@ import ( // certificate generated by the ingress controller var FakeSSLCertificateUID = "00000000-0000-0000-0000-000000000000" -var ( - oidExtensionSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17} -) +var oidExtensionSubjectAltName = asn1.ObjectIdentifier{2, 5, 29, 17} const ( fakeCertificateName = "default-fake-certificate" ) // getPemFileName returns absolute file path and file name of pem cert related to given fullSecretName -func getPemFileName(fullSecretName string) (string, string) { - pemName := fmt.Sprintf("%v.pem", fullSecretName) +func getPemFileName(fullSecretName string) (filePath, pemName string) { + pemName = fmt.Sprintf("%v.pem", fullSecretName) return fmt.Sprintf("%v/%v", file.DefaultSSLDirectory, pemName), pemName } @@ -192,7 +190,7 @@ func StoreSSLCertOnDisk(name string, sslCert *ingress.SSLCert) (string, error) { // ConfigureCACertWithCertAndKey appends ca into existing PEM file consisting of cert and key // and sets relevant fields in sslCert object -func ConfigureCACertWithCertAndKey(name string, ca []byte, sslCert *ingress.SSLCert) error { +func ConfigureCACertWithCertAndKey(_ string, ca []byte, sslCert *ingress.SSLCert) error { var buffer bytes.Buffer _, err := buffer.WriteString(sslCert.PemCertKey) @@ -210,12 +208,12 @@ func ConfigureCACertWithCertAndKey(name string, ca []byte, sslCert *ingress.SSLC return fmt.Errorf("could not write ca data to cert file %v: %v", sslCert.CAFileName, err) } - return os.WriteFile(sslCert.CAFileName, buffer.Bytes(), 0644) + //nolint:gosec // Not change permission to avoid possible issues + return os.WriteFile(sslCert.CAFileName, buffer.Bytes(), 0o644) } // ConfigureCRL creates a CRL file and append it into the SSLCert func ConfigureCRL(name string, crl []byte, sslCert *ingress.SSLCert) error { - crlName := fmt.Sprintf("crl-%v.pem", name) crlFileName := fmt.Sprintf("%v/%v", file.DefaultSSLDirectory, crlName) @@ -230,10 +228,11 @@ func ConfigureCRL(name string, crl []byte, sslCert *ingress.SSLCert) error { _, err := x509.ParseRevocationList(pemCRLBlock.Bytes) if err != nil { - return fmt.Errorf(err.Error()) + return err } - err = os.WriteFile(crlFileName, crl, 0644) + //nolint:gosec // Not change permission to avoid possible issues + err = os.WriteFile(crlFileName, crl, 0o644) if err != nil { return fmt.Errorf("could not write CRL file %v: %v", crlFileName, err) } @@ -242,7 +241,6 @@ func ConfigureCRL(name string, crl []byte, sslCert *ingress.SSLCert) error { sslCert.CRLSHA = file.SHA1(crlFileName) return nil - } // ConfigureCACert is similar to ConfigureCACertWithCertAndKey but it creates a separate file @@ -251,7 +249,8 @@ func ConfigureCACert(name string, ca []byte, sslCert *ingress.SSLCert) error { caName := fmt.Sprintf("ca-%v.pem", name) fileName := fmt.Sprintf("%v/%v", file.DefaultSSLDirectory, caName) - err := os.WriteFile(fileName, ca, 0644) + //nolint:gosec // Not change permission to avoid possible issues + err := os.WriteFile(fileName, ca, 0o644) if err != nil { return fmt.Errorf("could not write CA file %v: %v", fileName, err) } @@ -293,14 +292,14 @@ func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddre var seq asn1.RawValue var rest []byte if rest, err = asn1.Unmarshal(value, &seq); err != nil { - return + return dnsNames, emailAddresses, ipAddresses, err } else if len(rest) != 0 { err = errors.New("x509: trailing data after X.509 extension") - return + return dnsNames, emailAddresses, ipAddresses, err } if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { err = asn1.StructuralError{Msg: "bad SAN sequence"} - return + return dnsNames, emailAddresses, ipAddresses, err } rest = seq.Bytes @@ -308,7 +307,7 @@ func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddre var v asn1.RawValue rest, err = asn1.Unmarshal(rest, &v) if err != nil { - return + return dnsNames, emailAddresses, ipAddresses, err } switch v.Tag { case 1: @@ -321,12 +320,12 @@ func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddre ipAddresses = append(ipAddresses, v.Bytes) default: err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes))) - return + return dnsNames, emailAddresses, ipAddresses, err } } } - return + return dnsNames, emailAddresses, ipAddresses, err } // AddOrUpdateDHParam creates a dh parameters file with the specified name @@ -396,7 +395,7 @@ func GetFakeSSLCert() *ingress.SSLCert { return sslCert } -func getFakeHostSSLCert(host string) ([]byte, []byte) { +func getFakeHostSSLCert(host string) (cert, key []byte) { var priv interface{} var err error @@ -412,7 +411,6 @@ func getFakeHostSSLCert(host string) ([]byte, []byte) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { klog.Fatalf("failed to generate fake serial number: %v", err) } @@ -436,9 +434,9 @@ func getFakeHostSSLCert(host string) ([]byte, []byte) { klog.Fatalf("Failed to create fake certificate: %v", err) } - cert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) + cert = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - key := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv.(*rsa.PrivateKey))}) + key = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv.(*rsa.PrivateKey))}) return cert, key } @@ -508,9 +506,14 @@ func NewTLSListener(certificate, key string) *TLSListener { l.load() - _, _ = file.NewFileWatcher(certificate, l.load) - _, _ = file.NewFileWatcher(key, l.load) - + _, err := file.NewFileWatcher(certificate, l.load) + if err != nil { + klog.Errorf("unexpected error: %v", err) + } + _, err = file.NewFileWatcher(key, l.load) + if err != nil { + klog.Errorf("unexpected error: %v", err) + } return &l } diff --git a/internal/net/ssl/ssl_test.go b/internal/net/ssl/ssl_test.go index a86ecb87a..9f8c5eeae 100644 --- a/internal/net/ssl/ssl_test.go +++ b/internal/net/ssl/ssl_test.go @@ -42,7 +42,7 @@ import ( ) // generateRSACerts generates a self signed certificate using a self generated ca -func generateRSACerts(host string) (*keyPair, *keyPair, error) { +func generateRSACerts(host string) (newCert, newCa *keyPair, err error) { ca, err := newCA("self-sign-ca") if err != nil { return nil, nil, err @@ -57,7 +57,7 @@ func generateRSACerts(host string) (*keyPair, *keyPair, error) { CommonName: host, Usages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny}, } - cert, err := newSignedCert(config, key, ca.Cert, ca.Key) + cert, err := newSignedCert(&config, key, ca.Cert, ca.Key) if err != nil { return nil, nil, fmt.Errorf("unable to sign the server certificate: %v", err) } @@ -139,11 +139,11 @@ func TestCACert(t *testing.T) { func TestGetFakeSSLCert(t *testing.T) { sslCert := GetFakeSSLCert() - if len(sslCert.PemCertKey) == 0 { + if sslCert.PemCertKey == "" { t.Fatalf("expected PemCertKey to not be empty") } - if len(sslCert.PemFileName) == 0 { + if sslCert.PemFileName == "" { t.Fatalf("expected PemFileName to not be empty") } @@ -195,7 +195,7 @@ func TestConfigureCRL(t *testing.T) { // Demo CRL from https://csrc.nist.gov/projects/pki-testing/sample-certificates-and-crls // Converted to PEM to be tested // SHA: ef21f9c97ec2ef84ba3b2ab007c858a6f760d813 - var crl = []byte(`-----BEGIN X509 CRL----- + crl := []byte(`-----BEGIN X509 CRL----- MIIBYDCBygIBATANBgkqhkiG9w0BAQUFADBDMRMwEQYKCZImiZPyLGQBGRYDY29t MRcwFQYKCZImiZPyLGQBGRYHZXhhbXBsZTETMBEGA1UEAxMKRXhhbXBsZSBDQRcN MDUwMjA1MTIwMDAwWhcNMDUwMjA2MTIwMDAwWjAiMCACARIXDTA0MTExOTE1NTcw @@ -237,6 +237,7 @@ fUNCdMGmr8FVF6IzTNYGmCuk/C4= t.Fatalf("the expected CRL SHA wasn't found") } } + func TestCreateSSLCert(t *testing.T) { cert, _, err := generateRSACerts("echoheaders") if err != nil { @@ -339,12 +340,12 @@ func newPrivateKey() (*rsa.PrivateKey, error) { } // newSignedCert creates a signed certificate using the given CA certificate and key -func newSignedCert(cfg certutil.Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) { +func newSignedCert(cfg *certutil.Config, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) { serial, err := rand.Int(rand.Reader, new(big.Int).SetInt64(math.MaxInt64)) if err != nil { return nil, err } - if len(cfg.CommonName) == 0 { + if cfg.CommonName == "" { return nil, errors.New("must specify a CommonName") } if len(cfg.Usages) == 0 { @@ -389,7 +390,7 @@ func encodeCertPEM(cert *x509.Certificate) []byte { return pem.EncodeToMemory(&block) } -func newFakeCertificate(t *testing.T) ([]byte, string, string) { +func newFakeCertificate(t *testing.T) (sslCert []byte, certFileName, keyFileName string) { cert, key := getFakeHostSSLCert("localhost") certFile, err := os.CreateTemp("", "crt-") @@ -423,10 +424,9 @@ func dialTestServer(port string, rootCertificates ...[]byte) error { return fmt.Errorf("failed to add root certificate") } } - resp, err := tls.Dial("tcp", "localhost:"+port, &tls.Config{ + resp, err := tls.Dial("tcp", "localhost:"+port, &tls.Config{ //nolint:gosec // Ignore the gosec error in testing RootCAs: roots, }) - if err != nil { return err } @@ -473,15 +473,14 @@ func TestTLSKeyReloader(t *testing.T) { } }) - //TODO: fix - /* - // simulate watch.NewFileWatcher to call the load function - watcher.load() - t.Run("when the certificate is reloaded", func(t *testing.T) { - if err := dialTestServer(port, cert); err != nil { - t.Errorf("TLS dial should succeed, got error: %v", err) - } - }) + /*TODO: fix + // simulate watch.NewFileWatcher to call the load function + watcher.load() + t.Run("when the certificate is reloaded", func(t *testing.T) { + if err := dialTestServer(port, cert); err != nil { + t.Errorf("TLS dial should succeed, got error: %v", err) + } + }) */ }) } diff --git a/internal/nginx/main.go b/internal/nginx/main.go index ae319fe1f..fc586e9e8 100644 --- a/internal/nginx/main.go +++ b/internal/nginx/main.go @@ -62,7 +62,7 @@ var StatusPath = "/nginx_status" var StreamPort = 10247 // NewGetStatusRequest creates a new GET request to the internal NGINX status server -func NewGetStatusRequest(path string) (int, []byte, error) { +func NewGetStatusRequest(path string) (statusCode int, data []byte, err error) { url := fmt.Sprintf("http://127.0.0.1:%v%v", StatusPort, path) client := http.Client{} @@ -72,7 +72,7 @@ func NewGetStatusRequest(path string) (int, []byte, error) { } defer res.Body.Close() - data, err := io.ReadAll(res.Body) + data, err = io.ReadAll(res.Body) if err != nil { return 0, nil, err } @@ -81,7 +81,7 @@ func NewGetStatusRequest(path string) (int, []byte, error) { } // NewPostStatusRequest creates a new POST request to the internal NGINX status server -func NewPostStatusRequest(path, contentType string, data interface{}) (int, []byte, error) { +func NewPostStatusRequest(path, contentType string, data interface{}) (statusCode int, body []byte, err error) { url := fmt.Sprintf("http://127.0.0.1:%v%v", StatusPort, path) buf, err := json.Marshal(data) @@ -96,7 +96,7 @@ func NewPostStatusRequest(path, contentType string, data interface{}) (int, []by } defer res.Body.Close() - body, err := io.ReadAll(res.Body) + body, err = io.ReadAll(res.Body) if err != nil { return 0, nil, err } @@ -105,7 +105,7 @@ func NewPostStatusRequest(path, contentType string, data interface{}) (int, []by } // GetServerBlock takes an nginx.conf file and a host and tries to find the server block for that host -func GetServerBlock(conf string, host string) (string, error) { +func GetServerBlock(conf, host string) (string, error) { startMsg := fmt.Sprintf("## start server %v\n", host) endMsg := fmt.Sprintf("## end server %v", host) @@ -113,7 +113,7 @@ func GetServerBlock(conf string, host string) (string, error) { if blockStart < 0 { return "", fmt.Errorf("host %v was not found in the controller's nginx.conf", host) } - blockStart = blockStart + len(startMsg) + blockStart += len(startMsg) blockEnd := strings.Index(conf, endMsg) if blockEnd < 0 { @@ -163,7 +163,10 @@ func Version() string { // IsRunning returns true if a process with the name 'nginx' is found func IsRunning() bool { - processes, _ := ps.Processes() + processes, err := ps.Processes() + if err != nil { + klog.ErrorS(err, "unexpected error obtaining process list") + } for _, p := range processes { if p.Executable() == "nginx" { return true diff --git a/internal/nginx/maxmind.go b/internal/nginx/maxmind.go index 5aee414cd..bd6bc1048 100644 --- a/internal/nginx/maxmind.go +++ b/internal/nginx/maxmind.go @@ -101,7 +101,7 @@ func DownloadGeoLite2DB(attempts int, period time.Duration) error { var lastErr error retries := 0 - _ = wait.ExponentialBackoff(defaultRetry, func() (bool, error) { + lastErr = wait.ExponentialBackoff(defaultRetry, func() (bool, error) { var dlError error for _, dbName := range strings.Split(MaxmindEditionIDs, ",") { dlError = downloadDatabase(dbName) @@ -139,8 +139,8 @@ func createURL(mirror, licenseKey, dbName string) string { } func downloadDatabase(dbName string) error { - url := createURL(MaxmindMirror, MaxmindLicenseKey, dbName) - req, err := http.NewRequest(http.MethodGet, url, nil) + newURL := createURL(MaxmindMirror, MaxmindLicenseKey, dbName) + req, err := http.NewRequest(http.MethodGet, newURL, http.NoBody) if err != nil { return err } @@ -175,8 +175,7 @@ func downloadDatabase(dbName string) error { return err } - switch header.Typeflag { - case tar.TypeReg: + if header.Typeflag == tar.TypeReg { if !strings.HasSuffix(header.Name, mmdbFile) { continue } @@ -186,6 +185,7 @@ func downloadDatabase(dbName string) error { return err } + //nolint:gocritic // TODO: will fix it on a followup PR defer outFile.Close() if _, err := io.CopyN(outFile, tarReader, header.Size); err != nil { diff --git a/internal/task/queue.go b/internal/task/queue.go index ff6b20f62..f92f2a501 100644 --- a/internal/task/queue.go +++ b/internal/task/queue.go @@ -28,9 +28,7 @@ import ( "k8s.io/client-go/util/workqueue" ) -var ( - keyFunc = cache.DeletionHandlingMetaNamespaceKeyFunc -) +var keyFunc = cache.DeletionHandlingMetaNamespaceKeyFunc // Queue manages a time work queue through an independent worker that invokes the // given sync function for every work item inserted. @@ -117,7 +115,10 @@ func (t *Queue) worker() { } ts := time.Now().UnixNano() - item := key.(Element) + item, ok := key.(Element) + if !ok { + klog.ErrorS(nil, "invalid item type", "key", key) + } if item.Timestamp != 0 && t.lastSync > item.Timestamp { klog.V(3).InfoS("skipping sync", "key", item.Key, "last", t.lastSync, "now", item.Timestamp) t.queue.Forget(key) @@ -168,7 +169,7 @@ func NewTaskQueue(syncFn func(interface{}) error) *Queue { return NewCustomTaskQueue(syncFn, nil) } -// NewCustomTaskQueue ... +// NewCustomTaskQueue creates a new custom task queue with the given sync function. func NewCustomTaskQueue(syncFn func(interface{}) error, fn func(interface{}) (interface{}, error)) *Queue { q := &Queue{ queue: workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter()), diff --git a/pkg/apis/ingress/sslcert.go b/pkg/apis/ingress/sslcert.go index 7dee3880d..b340b2d9a 100644 --- a/pkg/apis/ingress/sslcert.go +++ b/pkg/apis/ingress/sslcert.go @@ -66,12 +66,12 @@ type SSLCert struct { } // GetObjectKind implements the ObjectKind interface as a noop -func (s SSLCert) GetObjectKind() schema.ObjectKind { +func (s *SSLCert) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind } // Identifier returns a the couple issuer / serial number if they both exist, an empty string otherwise -func (s SSLCert) Identifier() string { +func (s *SSLCert) Identifier() string { if s.Certificate != nil { if s.Certificate.SerialNumber != nil { return fmt.Sprintf("%s-%s", s.Certificate.Issuer.SerialNumber, s.Certificate.SerialNumber.String()) @@ -81,7 +81,7 @@ func (s SSLCert) Identifier() string { } // HashInclude defines if a field should be used or not to calculate the hash -func (s SSLCert) HashInclude(field string, v interface{}) (bool, error) { +func (s *SSLCert) HashInclude(field string, _ interface{}) (bool, error) { switch field { case "PemSHA", "CASHA", "ExpireTime": return true, nil diff --git a/pkg/apis/ingress/types.go b/pkg/apis/ingress/types.go index 284e9b427..0742e9f3b 100644 --- a/pkg/apis/ingress/types.go +++ b/pkg/apis/ingress/types.go @@ -73,7 +73,7 @@ type Configuration struct { DefaultSSLCertificate *SSLCert `json:"-"` - StreamSnippets []string + StreamSnippets []string `json:"StreamSnippets"` } // Backend describes one or more remote server/s (endpoints) associated with a service @@ -129,7 +129,7 @@ type TrafficShapingPolicy struct { } // HashInclude defines if a field should be used or not to calculate the hash -func (s Backend) HashInclude(field string, v interface{}) (bool, error) { +func (b *Backend) HashInclude(field string, _ interface{}) (bool, error) { switch field { case "Endpoints": return false, nil @@ -410,5 +410,4 @@ type Ingress struct { } // GeneralConfig holds the definition of lua general configuration data -type GeneralConfig struct { -} +type GeneralConfig struct{} diff --git a/pkg/apis/ingress/types_equals.go b/pkg/apis/ingress/types_equals.go index c87f5ba3e..45f0eedba 100644 --- a/pkg/apis/ingress/types_equals.go +++ b/pkg/apis/ingress/types_equals.go @@ -80,58 +80,58 @@ func (c1 *Configuration) Equal(c2 *Configuration) bool { } // Equal tests for equality between two Backend types -func (b1 *Backend) Equal(b2 *Backend) bool { - if b1 == b2 { +func (b *Backend) Equal(newB *Backend) bool { + if b == newB { return true } - if b1 == nil || b2 == nil { + if b == nil || newB == nil { return false } - if b1.Name != b2.Name { + if b.Name != newB.Name { return false } - if b1.NoServer != b2.NoServer { + if b.NoServer != newB.NoServer { return false } - if b1.Service != b2.Service { - if b1.Service == nil || b2.Service == nil { + if b.Service != newB.Service { + if b.Service == nil || newB.Service == nil { return false } - if b1.Service.GetNamespace() != b2.Service.GetNamespace() { + if b.Service.GetNamespace() != newB.Service.GetNamespace() { return false } - if b1.Service.GetName() != b2.Service.GetName() { + if b.Service.GetName() != newB.Service.GetName() { return false } } - if b1.Port != b2.Port { + if b.Port != newB.Port { return false } - if b1.SSLPassthrough != b2.SSLPassthrough { + if b.SSLPassthrough != newB.SSLPassthrough { return false } - if !(&b1.SessionAffinity).Equal(&b2.SessionAffinity) { + if !(&b.SessionAffinity).Equal(&newB.SessionAffinity) { return false } - if b1.UpstreamHashBy != b2.UpstreamHashBy { + if b.UpstreamHashBy != newB.UpstreamHashBy { return false } - if b1.LoadBalancing != b2.LoadBalancing { + if b.LoadBalancing != newB.LoadBalancing { return false } - match := compareEndpoints(b1.Endpoints, b2.Endpoints) + match := compareEndpoints(b.Endpoints, newB.Endpoints) if !match { return false } - if !b1.TrafficShapingPolicy.Equal(b2.TrafficShapingPolicy) { + if !b.TrafficShapingPolicy.Equal(&newB.TrafficShapingPolicy) { return false } - return sets.StringElementsMatch(b1.AlternativeBackends, b2.AlternativeBackends) + return sets.StringElementsMatch(b.AlternativeBackends, newB.AlternativeBackends) } // Equal tests for equality between two SessionAffinityConfig types @@ -243,7 +243,7 @@ func (e1 *Endpoint) Equal(e2 *Endpoint) bool { } // Equal checks for equality between two TrafficShapingPolicies -func (tsp1 TrafficShapingPolicy) Equal(tsp2 TrafficShapingPolicy) bool { +func (tsp1 *TrafficShapingPolicy) Equal(tsp2 *TrafficShapingPolicy) bool { if tsp1.Weight != tsp2.Weight { return false } @@ -335,6 +335,8 @@ func (s1 *Server) Equal(s2 *Server) bool { } // Equal tests for equality between two Location types +// +//nolint:gocyclo // Ignore function complexity error func (l1 *Location) Equal(l2 *Location) bool { if l1 == l2 { return true @@ -550,39 +552,39 @@ func (l4b1 *L4Backend) Equal(l4b2 *L4Backend) bool { } // Equal tests for equality between two SSLCert types -func (s1 *SSLCert) Equal(s2 *SSLCert) bool { - if s1 == s2 { +func (s *SSLCert) Equal(newS *SSLCert) bool { + if s == newS { return true } - if s1 == nil || s2 == nil { + if s == nil || newS == nil { return false } - if s1.CASHA != s2.CASHA { + if s.CASHA != newS.CASHA { return false } - if s1.CRLSHA != s2.CRLSHA { + if s.CRLSHA != newS.CRLSHA { return false } - if s1.PemSHA != s2.PemSHA { + if s.PemSHA != newS.PemSHA { return false } - if s1.CAFileName != s2.CAFileName { + if s.CAFileName != newS.CAFileName { return false } - if s1.CRLFileName != s2.CRLFileName { + if s.CRLFileName != newS.CRLFileName { return false } - if !s1.ExpireTime.Equal(s2.ExpireTime) { + if !s.ExpireTime.Equal(newS.ExpireTime) { return false } - if s1.PemCertKey != s2.PemCertKey { + if s.PemCertKey != newS.PemCertKey { return false } - if s1.UID != s2.UID { + if s.UID != newS.UID { return false } - return sets.StringElementsMatch(s1.CN, s2.CN) + return sets.StringElementsMatch(s.CN, newS.CN) } var compareEndpointsFunc = func(e1, e2 interface{}) bool { diff --git a/pkg/apis/ingress/types_equals_test.go b/pkg/apis/ingress/types_equals_test.go index 78d29d46c..53643f912 100644 --- a/pkg/apis/ingress/types_equals_test.go +++ b/pkg/apis/ingress/types_equals_test.go @@ -25,19 +25,29 @@ import ( ) func TestEqualConfiguration(t *testing.T) { - ap, _ := filepath.Abs("../../../test/manifests/configuration-a.json") + ap, err := filepath.Abs("../../../test/manifests/configuration-a.json") + if err != nil { + t.Errorf("unexpected error: %v", err) + } a, err := readJSON(ap) if err != nil { t.Errorf("unexpected error reading JSON file: %v", err) } - bp, _ := filepath.Abs("../../../test/manifests/configuration-b.json") + bp, err := filepath.Abs("../../../test/manifests/configuration-b.json") + if err != nil { + t.Errorf("unexpected error: %v", err) + } + b, err := readJSON(bp) if err != nil { t.Errorf("unexpected error reading JSON file: %v", err) } - cp, _ := filepath.Abs("../../../test/manifests/configuration-c.json") + cp, err := filepath.Abs("../../../test/manifests/configuration-c.json") + if err != nil { + t.Errorf("unexpected error: %v", err) + } c, err := readJSON(cp) if err != nil { t.Errorf("unexpected error reading JSON file: %v", err) @@ -84,15 +94,18 @@ func TestL4ServiceElementsMatch(t *testing.T) { {[]L4Service{{Port: 80}}, []L4Service{{Port: 80}}, true}, { []L4Service{ - {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.1"}}}}, + {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.1"}}}, + }, []L4Service{{Port: 80}}, false, }, { []L4Service{ - {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.1"}, {Address: "1.1.1.2"}}}}, + {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.1"}, {Address: "1.1.1.2"}}}, + }, []L4Service{ - {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.2"}, {Address: "1.1.1.1"}}}}, + {Port: 80, Endpoints: []Endpoint{{Address: "1.1.1.2"}, {Address: "1.1.1.1"}}}, + }, true, }, { diff --git a/pkg/flags/flags.go b/pkg/flags/flags.go index 55d24f690..d3bc4ee86 100644 --- a/pkg/flags/flags.go +++ b/pkg/flags/flags.go @@ -298,12 +298,12 @@ https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-g nginx.HealthCheckTimeout = time.Duration(*defHealthCheckTimeout) * time.Second } - if len(*watchNamespace) != 0 && len(*watchNamespaceSelector) != 0 { + if *watchNamespace != "" && *watchNamespaceSelector != "" { return false, nil, fmt.Errorf("flags --watch-namespace and --watch-namespace-selector are mutually exclusive") } var namespaceSelector labels.Selector - if len(*watchNamespaceSelector) != 0 { + if *watchNamespaceSelector != "" { var err error namespaceSelector, err = labels.Parse(*watchNamespaceSelector) if err != nil { @@ -311,7 +311,7 @@ https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-g } } - var histogramBuckets = &collectors.HistogramBuckets{ + histogramBuckets := &collectors.HistogramBuckets{ TimeBuckets: *timeBuckets, LengthBuckets: *lengthBuckets, SizeBuckets: *sizeBuckets, @@ -360,7 +360,7 @@ https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-g HTTPS: *httpsPort, SSLProxy: *sslProxyPort, }, - IngressClassConfiguration: &ingressclass.IngressClassConfiguration{ + IngressClassConfiguration: &ingressclass.Configuration{ Controller: *ingressClassController, AnnotationValue: *ingressClassAnnotation, WatchWithoutClass: *watchWithoutClass, @@ -380,7 +380,7 @@ https://blog.maxmind.com/2019/12/18/significant-changes-to-accessing-and-using-g var err error if nginx.MaxmindEditionIDs != "" { - if err = nginx.ValidateGeoLite2DBEditions(); err != nil { + if err := nginx.ValidateGeoLite2DBEditions(); err != nil { return false, nil, err } if nginx.MaxmindLicenseKey != "" || nginx.MaxmindMirror != "" { diff --git a/pkg/flags/flags_test.go b/pkg/flags/flags_test.go index 2a33d73dd..bffe2b16d 100644 --- a/pkg/flags/flags_test.go +++ b/pkg/flags/flags_test.go @@ -33,7 +33,8 @@ func TestDefaults(t *testing.T) { oldArgs := os.Args defer func() { os.Args = oldArgs }() - os.Args = []string{"cmd", + os.Args = []string{ + "cmd", "--default-backend-service", "namespace/test", "--http-port", "0", "--https-port", "0", @@ -53,8 +54,8 @@ func TestDefaults(t *testing.T) { } } -func TestSetupSSLProxy(t *testing.T) { - // TODO +func TestSetupSSLProxy(_ *testing.T) { + // TODO TestSetupSSLProxy } func TestFlagConflict(t *testing.T) { diff --git a/pkg/metrics/handler.go b/pkg/metrics/handler.go index c37c1760c..73c7d328f 100644 --- a/pkg/metrics/handler.go +++ b/pkg/metrics/handler.go @@ -29,7 +29,6 @@ import ( ) func RegisterHealthz(healthPath string, mux *http.ServeMux, checks ...healthz.HealthChecker) { - healthCheck := []healthz.HealthChecker{healthz.PingHealthz} if len(checks) > 0 { healthCheck = append(healthCheck, checks...) @@ -67,7 +66,7 @@ func RegisterProfiler(host string, port int) { server := &http.Server{ Addr: fmt.Sprintf("%s:%d", host, port), - //G112 (CWE-400): Potential Slowloris Attack + // G112 (CWE-400): Potential Slowloris Attack ReadHeaderTimeout: 10 * time.Second, Handler: mux, } diff --git a/pkg/tcpproxy/tcp.go b/pkg/tcpproxy/tcp.go index 25cc39ee4..eda4a2746 100644 --- a/pkg/tcpproxy/tcp.go +++ b/pkg/tcpproxy/tcp.go @@ -69,7 +69,7 @@ func (p *TCPProxy) Handle(conn net.Conn) { } proxy := p.Default - hostname, err := parser.GetHostname(data[:]) + hostname, err := parser.GetHostname(data) if err == nil { klog.V(4).InfoS("TLS Client Hello", "host", hostname) proxy = p.Get(hostname) @@ -91,8 +91,14 @@ func (p *TCPProxy) Handle(conn net.Conn) { if proxy.ProxyProtocol { // write out the Proxy Protocol header - localAddr := conn.LocalAddr().(*net.TCPAddr) - remoteAddr := conn.RemoteAddr().(*net.TCPAddr) + localAddr, ok := conn.LocalAddr().(*net.TCPAddr) + if !ok { + klog.Errorf("unexpected type: %T", conn.LocalAddr()) + } + remoteAddr, ok := conn.RemoteAddr().(*net.TCPAddr) + if !ok { + klog.Errorf("unexpected type: %T", conn.RemoteAddr()) + } protocol := "UNKNOWN" if remoteAddr.IP.To4() != nil { protocol = "TCP4" diff --git a/pkg/util/file/file_watcher.go b/pkg/util/file/file_watcher.go index daf955e52..3899e41f8 100644 --- a/pkg/util/file/file_watcher.go +++ b/pkg/util/file/file_watcher.go @@ -26,8 +26,8 @@ import ( "github.com/fsnotify/fsnotify" ) -// FileWatcher is an interface we use to watch changes in files -type FileWatcher interface { +// Watcher is an interface we use to watch changes in files +type Watcher interface { Close() error } @@ -40,7 +40,7 @@ type OSFileWatcher struct { } // NewFileWatcher creates a new FileWatcher -func NewFileWatcher(file string, onEvent func()) (FileWatcher, error) { +func NewFileWatcher(file string, onEvent func()) (Watcher, error) { fw := OSFileWatcher{ file: file, onEvent: onEvent, diff --git a/pkg/util/file/filesystem.go b/pkg/util/file/filesystem.go index 7c0db9f12..ccb93ed06 100644 --- a/pkg/util/file/filesystem.go +++ b/pkg/util/file/filesystem.go @@ -17,4 +17,4 @@ limitations under the License. package file // ReadWriteByUser defines linux permission to read and write files for the owner user -const ReadWriteByUser = 0700 +const ReadWriteByUser = 0o700 diff --git a/pkg/util/file/structure.go b/pkg/util/file/structure.go index d109e8c03..7d4f26da9 100644 --- a/pkg/util/file/structure.go +++ b/pkg/util/file/structure.go @@ -33,12 +33,10 @@ const ( DefaultSSLDirectory = "/etc/ingress-controller/ssl" ) -var ( - directories = []string{ - DefaultSSLDirectory, - AuthDirectory, - } -) +var directories = []string{ + DefaultSSLDirectory, + AuthDirectory, +} // CreateRequiredDirectories verifies if the required directories to // start the ingress controller exist and creates the missing ones. diff --git a/pkg/util/ingress/ingress.go b/pkg/util/ingress/ingress.go index e69ca7b29..881d5a001 100644 --- a/pkg/util/ingress/ingress.go +++ b/pkg/util/ingress/ingress.go @@ -114,7 +114,7 @@ func GetRemovedIngresses(rucfg, newcfg *ingress.Configuration) []string { // IsDynamicConfigurationEnough returns whether a Configuration can be // dynamically applied, without reloading the backend. -func IsDynamicConfigurationEnough(newcfg *ingress.Configuration, oldcfg *ingress.Configuration) bool { +func IsDynamicConfigurationEnough(newcfg, oldcfg *ingress.Configuration) bool { copyOfRunningConfig := *oldcfg copyOfPcfg := *newcfg @@ -133,21 +133,21 @@ func IsDynamicConfigurationEnough(newcfg *ingress.Configuration, oldcfg *ingress // clearL4serviceEndpoints is a helper function to clear endpoints from the ingress configuration since they should be ignored when // checking if the new configuration changes can be applied dynamically. func clearL4serviceEndpoints(config *ingress.Configuration) { - var clearedTCPL4Services []ingress.L4Service - var clearedUDPL4Services []ingress.L4Service - for _, service := range config.TCPEndpoints { + clearedTCPL4Services := make([]ingress.L4Service, 0, len(config.TCPEndpoints)) + clearedUDPL4Services := make([]ingress.L4Service, 0, len(config.UDPEndpoints)) + for i := range config.TCPEndpoints { copyofService := ingress.L4Service{ - Port: service.Port, - Backend: service.Backend, + Port: config.TCPEndpoints[i].Port, + Backend: config.TCPEndpoints[i].Backend, Endpoints: []ingress.Endpoint{}, Service: nil, } clearedTCPL4Services = append(clearedTCPL4Services, copyofService) } - for _, service := range config.UDPEndpoints { + for i := range config.UDPEndpoints { copyofService := ingress.L4Service{ - Port: service.Port, - Backend: service.Backend, + Port: config.UDPEndpoints[i].Port, + Backend: config.UDPEndpoints[i].Backend, Endpoints: []ingress.Endpoint{}, Service: nil, } @@ -160,7 +160,7 @@ func clearL4serviceEndpoints(config *ingress.Configuration) { // clearCertificates is a helper function to clear Certificates from the ingress configuration since they should be ignored when // checking if the new configuration changes can be applied dynamically if dynamic certificates is on func clearCertificates(config *ingress.Configuration) { - var clearedServers []*ingress.Server + clearedServers := make([]*ingress.Server, 0, len(config.Servers)) for _, server := range config.Servers { copyOfServer := *server copyOfServer.SSLCert = nil @@ -169,16 +169,16 @@ func clearCertificates(config *ingress.Configuration) { config.Servers = clearedServers } -type redirect struct { +type Redirect struct { From string To string SSLCert *ingress.SSLCert } // BuildRedirects build the redirects of servers based on configurations and certificates -func BuildRedirects(servers []*ingress.Server) []*redirect { +func BuildRedirects(servers []*ingress.Server) []*Redirect { names := sets.Set[string]{} - redirectServers := make([]*redirect, 0) + redirectServers := make([]*Redirect, 0) for _, srv := range servers { if !srv.RedirectFromToWWW { @@ -212,7 +212,7 @@ func BuildRedirects(servers []*ingress.Server) []*redirect { continue } - r := &redirect{ + r := &Redirect{ From: from, To: to, } diff --git a/pkg/util/process/controller.go b/pkg/util/process/controller.go index ae9bc9356..a73e81934 100644 --- a/pkg/util/process/controller.go +++ b/pkg/util/process/controller.go @@ -16,9 +16,9 @@ limitations under the License. package process -// ProcessController defines a common interface for a process to be controlled, +// Controller defines a common interface for a process to be controlled, // like the configurer, the webhook or the proper ingress controller -type ProcessController interface { +type Controller interface { Start() Stop() error } diff --git a/pkg/util/process/sigterm.go b/pkg/util/process/sigterm.go index 77c0ad58c..1c0d729c1 100644 --- a/pkg/util/process/sigterm.go +++ b/pkg/util/process/sigterm.go @@ -29,7 +29,7 @@ type exiter func(code int) // HandleSigterm receives a ProcessController interface and deals with // the graceful shutdown -func HandleSigterm(ngx ProcessController, delay int, exit exiter) { +func HandleSigterm(ngx Controller, delay int, exit exiter) { signalChan := make(chan os.Signal, 1) signal.Notify(signalChan, syscall.SIGTERM) <-signalChan diff --git a/pkg/util/process/sigterm_test.go b/pkg/util/process/sigterm_test.go index b7413bed4..08c8275c3 100644 --- a/pkg/util/process/sigterm_test.go +++ b/pkg/util/process/sigterm_test.go @@ -43,7 +43,7 @@ func (f *FakeProcess) exiterFunc(code int) { } func sendDelayedSignal(delay time.Duration) error { - time.Sleep(delay * time.Second) + time.Sleep(delay) return syscall.Kill(syscall.Getpid(), syscall.SIGTERM) } @@ -67,7 +67,7 @@ func TestHandleSigterm(t *testing.T) { process := &FakeProcess{shouldError: tt.shouldError} t.Run(tt.name, func(t *testing.T) { go func() { - err := sendDelayedSignal(2) // Send a signal after 2 seconds + err := sendDelayedSignal(2 * time.Second) // Send a signal after 2 seconds if err != nil { t.Errorf("error sending delayed signal: %v", err) } diff --git a/pkg/util/runtime/cpu_notlinux.go b/pkg/util/runtime/cpu_notlinux.go index 2a1b48252..97c72cd5a 100644 --- a/pkg/util/runtime/cpu_notlinux.go +++ b/pkg/util/runtime/cpu_notlinux.go @@ -23,7 +23,7 @@ import ( "runtime" ) -// NumCPU ... +// NumCPU returns the number of logical CPUs usable by the current process. func NumCPU() int { return runtime.NumCPU() } diff --git a/pkg/util/sets/match_test.go b/pkg/util/sets/match_test.go index e2366d2c7..a65c5a05f 100644 --- a/pkg/util/sets/match_test.go +++ b/pkg/util/sets/match_test.go @@ -20,23 +20,20 @@ import ( "testing" ) -var ( - testCasesElementMatch = []struct { - listA []string - listB []string - expected bool - }{ - {nil, nil, true}, - {[]string{"1"}, nil, false}, - {[]string{"1"}, []string{"1"}, true}, - {[]string{"1", "2", "1"}, []string{"1", "1", "2"}, true}, - {[]string{"1", "3", "1"}, []string{"1", "1", "2"}, false}, - {[]string{"1", "1"}, []string{"1", "2"}, false}, - } -) +var testCasesElementMatch = []struct { + listA []string + listB []string + expected bool +}{ + {nil, nil, true}, + {[]string{"1"}, nil, false}, + {[]string{"1"}, []string{"1"}, true}, + {[]string{"1", "2", "1"}, []string{"1", "1", "2"}, true}, + {[]string{"1", "3", "1"}, []string{"1", "1", "2"}, false}, + {[]string{"1", "1"}, []string{"1", "2"}, false}, +} func TestElementsMatch(t *testing.T) { - for _, testCase := range testCasesElementMatch { result := StringElementsMatch(testCase.listA, testCase.listB) if result != testCase.expected { diff --git a/rootfs/etc/nginx/template/nginx.tmpl b/rootfs/etc/nginx/template/nginx.tmpl index 3d7235bcc..ccd7b4411 100644 --- a/rootfs/etc/nginx/template/nginx.tmpl +++ b/rootfs/etc/nginx/template/nginx.tmpl @@ -140,7 +140,7 @@ http { {{/* Enable the real_ip module only if we use either X-Forwarded headers or Proxy Protocol. */}} {{/* we use the value of the real IP for the geo_ip module */}} - {{ if or (or $cfg.UseForwardedHeaders $cfg.UseProxyProtocol) $cfg.EnableRealIp }} + {{ if or (or $cfg.UseForwardedHeaders $cfg.UseProxyProtocol) $cfg.EnableRealIP }} {{ if $cfg.UseProxyProtocol }} real_ip_header proxy_protocol; {{ else }} @@ -406,7 +406,7 @@ http { {{ if $cfg.EnableSyslog }} access_log syslog:server={{ $cfg.SyslogHost }}:{{ $cfg.SyslogPort }} upstreaminfo if=$loggable; {{ else }} - access_log {{ or $cfg.HttpAccessLogPath $cfg.AccessLogPath }} upstreaminfo {{ $cfg.AccessLogParams }} if=$loggable; + access_log {{ or $cfg.HTTPAccessLogPath $cfg.AccessLogPath }} upstreaminfo {{ $cfg.AccessLogParams }} if=$loggable; {{ end }} {{ end }} @@ -822,7 +822,7 @@ stream { error_log {{ $cfg.ErrorLogPath }} {{ $cfg.ErrorLogLevel }}; - {{ if $cfg.EnableRealIp }} + {{ if $cfg.EnableRealIP }} {{ range $trusted_ip := $cfg.ProxyRealIPCIDR }} set_real_ip_from {{ $trusted_ip }}; {{ end }} diff --git a/test/e2e/admission/admission.go b/test/e2e/admission/admission.go index 0ee8248b0..726e16f0b 100644 --- a/test/e2e/admission/admission.go +++ b/test/e2e/admission/admission.go @@ -34,6 +34,8 @@ import ( networking "k8s.io/api/networking/v1" ) +const admissionTestHost = "admission-test" + var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", func() { f := framework.NewDefaultFramework("admission") @@ -43,7 +45,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("reject ingress with global-rate-limit annotations when memcached is not configured", func() { - host := "admission-test" + host := admissionTestHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/global-rate-limit": "100", @@ -70,7 +72,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("should not allow overlaps of host and paths without canary annotations", func() { - host := "admission-test" + host := admissionTestHost firstIngress := framework.NewSingleIngress("first-ingress", "/", host, f.Namespace, framework.EchoService, 80, nil) _, err := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Create(context.TODO(), firstIngress, metav1.CreateOptions{}) @@ -87,7 +89,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("should allow overlaps of host and paths with canary annotation", func() { - host := "admission-test" + host := admissionTestHost firstIngress := framework.NewSingleIngress("first-ingress", "/", host, f.Namespace, framework.EchoService, 80, nil) _, err := f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Create(context.TODO(), firstIngress, metav1.CreateOptions{}) @@ -125,7 +127,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("should return an error if there is an error validating the ingress definition", func() { - host := "admission-test" + host := admissionTestHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/configuration-snippet": "something invalid", @@ -136,7 +138,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("should return an error if there is an invalid value in some annotation", func() { - host := "admission-test" + host := admissionTestHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/connection-proxy-header": "a;}", @@ -150,7 +152,7 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", }) ginkgo.It("should return an error if there is a forbidden value in some annotation", func() { - host := "admission-test" + host := admissionTestHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/connection-proxy-header": "set_by_lua", @@ -195,7 +197,6 @@ var _ = framework.IngressNginxDescribeSerial("[Admission] admission controller", validPath := framework.NewSingleIngress("second-ingress", "/bloblo", host, f.Namespace, framework.EchoService, 80, nil) _, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Create(context.TODO(), validPath, metav1.CreateOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "creating an ingress with valid path should not return an error") - }) ginkgo.It("should not return an error if the Ingress V1 definition is valid with Ingress Class", func() { @@ -346,7 +347,7 @@ func createIngress(namespace, ingressDefinition string) (string, error) { execOut bytes.Buffer execErr bytes.Buffer ) - + //nolint:gosec // Ignore G204 error cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%v --warnings-as-errors=false apply --namespace %s -f -", framework.KubectlPath, namespace)) cmd.Stdin = strings.NewReader(ingressDefinition) cmd.Stdout = &execOut diff --git a/test/e2e/annotations/affinity.go b/test/e2e/annotations/affinity.go index 3e1e9e969..b64581ef6 100644 --- a/test/e2e/annotations/affinity.go +++ b/test/e2e/annotations/affinity.go @@ -32,6 +32,14 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const ( + affinityAnnotation = "cookie" + cookieName = "SERVERID" + enableAnnotation = "true" + disableAnnotation = "false" + defaultHost = "foo.com" +) + var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { f := framework.NewDefaultFramework("affinity") @@ -42,8 +50,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should set sticky cookie SERVERID", func() { host := "sticky.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -64,8 +72,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should change cookie name on ingress definition change", func() { host := "change.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -80,7 +88,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { WithHeader("Host", host). Expect(). Status(http.StatusOK). - Header("Set-Cookie").Contains("SERVERID") + Header("Set-Cookie").Contains(cookieName) ing.ObjectMeta.Annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "OTHERCOOKIENAME" @@ -99,8 +107,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should set the path to /something on the generated cookie", func() { host := "path.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName ing := framework.NewSingleIngress(host, "/something", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -122,8 +130,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { pathtype := networking.PathTypePrefix host := "morethanonerule.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName f.EnsureIngress(&networking.Ingress{ ObjectMeta: metav1.ObjectMeta{ @@ -194,7 +202,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should set cookie with expires", func() { host := "cookieexpires.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "ExpiresCookie" annotations["nginx.ingress.kubernetes.io/session-cookie-expires"] = "172800" annotations["nginx.ingress.kubernetes.io/session-cookie-max-age"] = "259200" @@ -211,7 +219,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { assert.Nil(ginkgo.GinkgoT(), err, "loading GMT location") assert.NotNil(ginkgo.GinkgoT(), local, "expected a location but none returned") - duration, _ := time.ParseDuration("48h") + duration, err := time.ParseDuration("48h") + assert.Nil(ginkgo.GinkgoT(), err, "parsing duration") expected := time.Now().In(local).Add(duration).Format("Mon, 02-Jan-06 15:04") f.HTTPTestClient(). @@ -225,7 +234,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should set cookie with domain", func() { host := "cookiedomain.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "DomainCookie" annotations["nginx.ingress.kubernetes.io/session-cookie-domain"] = "foo.bar" @@ -248,7 +257,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should not set cookie without domain annotation", func() { host := "cookienodomain.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "NoDomainCookie" ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) @@ -270,9 +279,9 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should work with use-regex annotation and session-cookie-path", func() { host := "useregex.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" - annotations["nginx.ingress.kubernetes.io/use-regex"] = "true" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName + annotations["nginx.ingress.kubernetes.io/use-regex"] = enableAnnotation annotations["nginx.ingress.kubernetes.io/session-cookie-path"] = "/foo/bar" ing := framework.NewSingleIngress(host, "/foo/.*", host, f.Namespace, framework.EchoService, 80, annotations) @@ -294,9 +303,9 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should warn user when use-regex is true and session-cookie-path is not set", func() { host := "useregexwarn.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" - annotations["nginx.ingress.kubernetes.io/use-regex"] = "true" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName + annotations["nginx.ingress.kubernetes.io/use-regex"] = enableAnnotation ing := framework.NewSingleIngress(host, "/foo/.*", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -321,7 +330,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { host := "separate.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation ing1 := framework.NewSingleIngress("ingress1", "/foo/bar", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing1) @@ -351,8 +360,8 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { ginkgo.It("should set sticky cookie without host", func() { annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName ing := framework.NewSingleIngress("default-no-host", "/", "", f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -370,12 +379,12 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { }) ginkgo.It("should work with server-alias annotation", func() { - host := "foo.com" + host := defaultHost alias1 := "a1.foo.com" alias2 := "a2.foo.com" annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName annotations["nginx.ingress.kubernetes.io/server-alias"] = fmt.Sprintf("%s,%s", alias1, alias2) ing := framework.NewSingleIngress(host, "/bar", host, f.Namespace, framework.EchoService, 80, annotations) @@ -383,7 +392,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { f.WaitForNginxServer(host, func(server string) bool { - //server alias sort by sort.Strings(), see: internal/ingress/annotations/alias/main.go:60 + // server alias sort by sort.Strings(), see: internal/ingress/annotations/alias/main.go:60 return strings.Contains(server, fmt.Sprintf("server_name %s %s %s ;", host, alias1, alias2)) }) @@ -410,11 +419,11 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { }) ginkgo.It("should set secure in cookie with provided true annotation on http", func() { - host := "foo.com" + host := defaultHost annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" - annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = "true" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName + annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = enableAnnotation ing := framework.NewSingleIngress(host, "/bar", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -433,11 +442,11 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { }) ginkgo.It("should not set secure in cookie with provided false annotation on http", func() { - host := "foo.com" + host := defaultHost annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" - annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = "false" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName + annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = disableAnnotation ing := framework.NewSingleIngress(host, "/bar", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -456,11 +465,11 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { }) ginkgo.It("should set secure in cookie with provided false annotation on https", func() { - host := "foo.com" + host := defaultHost annotations := make(map[string]string) - annotations["nginx.ingress.kubernetes.io/affinity"] = "cookie" - annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "SERVERID" - annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = "false" + annotations["nginx.ingress.kubernetes.io/affinity"] = affinityAnnotation + annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = cookieName + annotations["nginx.ingress.kubernetes.io/session-cookie-secure"] = disableAnnotation f.EnsureIngress(framework.NewSingleIngressWithTLS(host, "/", host, []string{host}, f.Namespace, framework.EchoService, 80, annotations)) @@ -470,6 +479,7 @@ var _ = framework.DescribeAnnotation("affinity session-cookie-name", func() { strings.Contains(server, "listen 443") }) + //nolint:gosec // Ignore the gosec error in testing f.HTTPTestClientWithTLSConfig(&tls.Config{ServerName: host, InsecureSkipVerify: true}). GET("/"). WithURL(f.GetURL(framework.HTTPS)). diff --git a/test/e2e/annotations/affinitymode.go b/test/e2e/annotations/affinitymode.go index ad210cfa5..e6253b6ff 100644 --- a/test/e2e/annotations/affinitymode.go +++ b/test/e2e/annotations/affinitymode.go @@ -28,6 +28,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const sslRedirectValue = "false" + var _ = framework.DescribeAnnotation("affinitymode", func() { f := framework.NewDefaultFramework("affinity") @@ -45,7 +47,7 @@ var _ = framework.DescribeAnnotation("affinitymode", func() { annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "hello-cookie" annotations["nginx.ingress.kubernetes.io/session-cookie-expires"] = "172800" annotations["nginx.ingress.kubernetes.io/session-cookie-max-age"] = "172800" - annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false" + annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = sslRedirectValue annotations["nginx.ingress.kubernetes.io/affinity-mode"] = "balanced" annotations["nginx.ingress.kubernetes.io/session-cookie-hash"] = "sha1" @@ -78,7 +80,7 @@ var _ = framework.DescribeAnnotation("affinitymode", func() { annotations["nginx.ingress.kubernetes.io/session-cookie-name"] = "hello-cookie" annotations["nginx.ingress.kubernetes.io/session-cookie-expires"] = "172800" annotations["nginx.ingress.kubernetes.io/session-cookie-max-age"] = "172800" - annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = "false" + annotations["nginx.ingress.kubernetes.io/ssl-redirect"] = sslRedirectValue annotations["nginx.ingress.kubernetes.io/affinity-mode"] = "persistent" annotations["nginx.ingress.kubernetes.io/session-cookie-hash"] = "sha1" @@ -106,7 +108,7 @@ var _ = framework.DescribeAnnotation("affinitymode", func() { // Send new requests and add new backends. Check which backend responded to the sent request cookies := getCookiesFromHeader(response.Header("Set-Cookie").Raw()) for sendRequestNumber := 0; sendRequestNumber < 10; sendRequestNumber++ { - replicas = replicas + 1 + replicas++ err := framework.UpdateDeployment(f.KubeClientSet, f.Namespace, deploymentName, replicas, nil) assert.Nil(ginkgo.GinkgoT(), err) framework.Sleep() diff --git a/test/e2e/annotations/alias.go b/test/e2e/annotations/alias.go index de829507d..ca4fe9c31 100644 --- a/test/e2e/annotations/alias.go +++ b/test/e2e/annotations/alias.go @@ -26,6 +26,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const fooHost = "foo" + var _ = framework.DescribeAnnotation("server-alias", func() { f := framework.NewDefaultFramework("alias") @@ -34,7 +36,7 @@ var _ = framework.DescribeAnnotation("server-alias", func() { }) ginkgo.It("should return status code 200 for host 'foo' and 404 for 'bar'", func() { - host := "foo" + host := fooHost ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -60,7 +62,7 @@ var _ = framework.DescribeAnnotation("server-alias", func() { }) ginkgo.It("should return status code 200 for host 'foo' and 'bar'", func() { - host := "foo" + host := fooHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/server-alias": "bar", } @@ -73,7 +75,7 @@ var _ = framework.DescribeAnnotation("server-alias", func() { return strings.Contains(server, fmt.Sprintf("server_name %v", host)) }) - hosts := []string{"foo", "bar"} + hosts := []string{fooHost, "bar"} for _, host := range hosts { f.HTTPTestClient(). GET("/"). @@ -85,7 +87,7 @@ var _ = framework.DescribeAnnotation("server-alias", func() { }) ginkgo.It("should return status code 200 for hosts defined in two ingresses, different path with one alias", func() { - host := "foo" + host := fooHost ing := framework.NewSingleIngress("app-a", "/app-a", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -101,7 +103,7 @@ var _ = framework.DescribeAnnotation("server-alias", func() { return strings.Contains(server, fmt.Sprintf("server_name %v bar", host)) }) - hosts := []string{"foo", "bar"} + hosts := []string{fooHost, "bar"} for _, host := range hosts { f.HTTPTestClient(). GET("/app-a"). diff --git a/test/e2e/annotations/auth.go b/test/e2e/annotations/auth.go index 56246828a..be915a722 100644 --- a/test/e2e/annotations/auth.go +++ b/test/e2e/annotations/auth.go @@ -36,6 +36,12 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const ( + differentHost = "different" + authHost = "auth" + authURL = "http://foo.bar.baz:5000/path" +) + var _ = framework.DescribeAnnotation("auth-*", func() { f := framework.NewDefaultFramework("auth", framework.WithHTTPBunEnabled()) @@ -44,7 +50,7 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 200 when no authentication is configured", func() { - host := "auth" + host := authHost ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -63,7 +69,7 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 503 when authentication is configured with an invalid secret", func() { - host := "auth" + host := authHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", "nginx.ingress.kubernetes.io/auth-secret": "something", @@ -87,9 +93,9 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 401 when authentication is configured but Authorization header is not configured", func() { - host := "auth" + host := authHost - s := f.EnsureSecret(buildSecret("foo", "bar", "test", f.Namespace)) + s := f.EnsureSecret(buildSecret(fooHost, "bar", "test", f.Namespace)) annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", @@ -114,9 +120,9 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 401 when authentication is configured and Authorization header is sent with invalid credentials", func() { - host := "auth" + host := authHost - s := f.EnsureSecret(buildSecret("foo", "bar", "test", f.Namespace)) + s := f.EnsureSecret(buildSecret(fooHost, "bar", "test", f.Namespace)) annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", @@ -142,9 +148,9 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 401 and cors headers when authentication and cors is configured but Authorization header is not configured", func() { - host := "auth" + host := authHost - s := f.EnsureSecret(buildSecret("foo", "bar", "test", f.Namespace)) + s := f.EnsureSecret(buildSecret(fooHost, "bar", "test", f.Namespace)) annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", @@ -170,9 +176,9 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It("should return status code 200 when authentication is configured and Authorization header is sent", func() { - host := "auth" + host := authHost - s := f.EnsureSecret(buildSecret("foo", "bar", "test", f.Namespace)) + s := f.EnsureSecret(buildSecret(fooHost, "bar", "test", f.Namespace)) annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", @@ -191,15 +197,15 @@ var _ = framework.DescribeAnnotation("auth-*", func() { f.HTTPTestClient(). GET("/"). WithHeader("Host", host). - WithBasicAuth("foo", "bar"). + WithBasicAuth(fooHost, "bar"). Expect(). Status(http.StatusOK) }) ginkgo.It("should return status code 200 when authentication is configured with a map and Authorization header is sent", func() { - host := "auth" + host := authHost - s := f.EnsureSecret(buildMapSecret("foo", "bar", "test", f.Namespace)) + s := f.EnsureSecret(buildMapSecret(fooHost, "bar", "test", f.Namespace)) annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-type": "basic", @@ -219,13 +225,13 @@ var _ = framework.DescribeAnnotation("auth-*", func() { f.HTTPTestClient(). GET("/"). WithHeader("Host", host). - WithBasicAuth("foo", "bar"). + WithBasicAuth(fooHost, "bar"). Expect(). Status(http.StatusOK) }) ginkgo.It("should return status code 401 when authentication is configured with invalid content and Authorization header is sent", func() { - host := "auth" + host := authHost s := f.EnsureSecret( &corev1.Secret{ @@ -258,13 +264,13 @@ var _ = framework.DescribeAnnotation("auth-*", func() { f.HTTPTestClient(). GET("/"). WithHeader("Host", host). - WithBasicAuth("foo", "bar"). + WithBasicAuth(fooHost, "bar"). Expect(). Status(http.StatusUnauthorized) }) ginkgo.It(`should set snippet "proxy_set_header My-Custom-Header 42;" when external auth is configured`, func() { - host := "auth" + host := authHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-url": "http://foo.bar/basic-auth/user/password", @@ -282,7 +288,7 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It(`should not set snippet "proxy_set_header My-Custom-Header 42;" when external auth is not configured`, func() { - host := "auth" + host := authHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-snippet": ` @@ -299,7 +305,7 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It(`should set "proxy_set_header 'My-Custom-Header' '42';" when auth-headers are set`, func() { - host := "auth" + host := authHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-url": "http://foo.bar/basic-auth/user/password", @@ -320,11 +326,11 @@ var _ = framework.DescribeAnnotation("auth-*", func() { }) ginkgo.It(`should set cache_key when external auth cache is configured`, func() { - host := "auth" + host := authHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-url": "http://foo.bar/basic-auth/user/password", - "nginx.ingress.kubernetes.io/auth-cache-key": "foo", + "nginx.ingress.kubernetes.io/auth-cache-key": fooHost, "nginx.ingress.kubernetes.io/auth-cache-duration": "200 202 401 30m", } @@ -337,7 +343,6 @@ var _ = framework.DescribeAnnotation("auth-*", func() { func(server string) bool { return cacheRegex.MatchString(server) && strings.Contains(server, `proxy_cache_valid 200 202 401 30m;`) - }) }) @@ -405,7 +410,6 @@ http { f.WaitForNginxServer(host, func(server string) bool { return strings.Contains(server, "server_name "+host) }) - }) ginkgo.It("user retains cookie by default", func() { @@ -431,7 +435,7 @@ http { }) ginkgo.It("user with annotated ingress retains cookie if upstream returns error status code", func() { - annotations["nginx.ingress.kubernetes.io/auth-always-set-cookie"] = "true" + annotations["nginx.ingress.kubernetes.io/auth-always-set-cookie"] = enableAnnotation f.UpdateIngress(ing1) f.UpdateIngress(ing2) @@ -451,7 +455,7 @@ http { }) ginkgo.Context("when external authentication is configured", func() { - host := "auth" + host := authHost var annotations map[string]string var ing *networking.Ingress @@ -495,7 +499,7 @@ http { annotations["nginx.ingress.kubernetes.io/auth-realm"] = "test auth" f.UpdateIngress(ing) - anotherHost := "different" + anotherHost := differentHost anotherAnnotations := map[string]string{} anotherIng := framework.NewSingleIngress(anotherHost, "/", anotherHost, f.Namespace, framework.EchoService, 80, anotherAnnotations) @@ -544,12 +548,12 @@ http { // Sleep a while just to guarantee that the configmap is applied framework.Sleep() - annotations["nginx.ingress.kubernetes.io/auth-url"] = "http://foo.bar.baz:5000/path" + annotations["nginx.ingress.kubernetes.io/auth-url"] = authURL f.UpdateIngress(ing) f.WaitForNginxServer("", func(server string) bool { - return strings.Contains(server, "http://foo.bar.baz:5000/path") && + return strings.Contains(server, authURL) && !strings.Contains(server, `upstream auth-external-auth`) }) }) @@ -582,19 +586,19 @@ http { // Sleep a while just to guarantee that the configmap is applied framework.Sleep() - annotations["nginx.ingress.kubernetes.io/auth-url"] = "http://foo.bar.baz:5000/path" + annotations["nginx.ingress.kubernetes.io/auth-url"] = authURL annotations["nginx.ingress.kubernetes.io/auth-keepalive"] = "-1" f.UpdateIngress(ing) f.WaitForNginxServer("", func(server string) bool { - return strings.Contains(server, "http://foo.bar.baz:5000/path") && + return strings.Contains(server, authURL) && !strings.Contains(server, `upstream auth-external-auth`) }) }) ginkgo.It(`should not create additional upstream block when auth-keepalive is set with HTTP/2`, func() { - annotations["nginx.ingress.kubernetes.io/auth-url"] = "http://foo.bar.baz:5000/path" + annotations["nginx.ingress.kubernetes.io/auth-url"] = authURL annotations["nginx.ingress.kubernetes.io/auth-keepalive"] = "123" annotations["nginx.ingress.kubernetes.io/auth-keepalive-requests"] = "456" annotations["nginx.ingress.kubernetes.io/auth-keepalive-timeout"] = "789" @@ -602,7 +606,7 @@ http { f.WaitForNginxServer("", func(server string) bool { - return strings.Contains(server, "http://foo.bar.baz:5000/path") && + return strings.Contains(server, authURL) && !strings.Contains(server, `upstream auth-external-auth`) }) }) @@ -657,7 +661,7 @@ http { framework.Sleep() annotations["nginx.ingress.kubernetes.io/auth-keepalive"] = "10" - annotations["nginx.ingress.kubernetes.io/auth-keepalive-share-vars"] = "true" + annotations["nginx.ingress.kubernetes.io/auth-keepalive-share-vars"] = enableAnnotation f.UpdateIngress(ing) f.WaitForNginxServer("", @@ -670,7 +674,7 @@ http { }) ginkgo.Context("when external authentication is configured with a custom redirect param", func() { - host := "auth" + host := authHost var annotations map[string]string var ing *networking.Ingress @@ -715,7 +719,7 @@ http { annotations["nginx.ingress.kubernetes.io/auth-realm"] = "test auth" f.UpdateIngress(ing) - anotherHost := "different" + anotherHost := differentHost anotherAnnotations := map[string]string{} anotherIng := framework.NewSingleIngress(anotherHost, "/", anotherHost, f.Namespace, framework.EchoService, 80, anotherAnnotations) @@ -735,8 +739,8 @@ http { }) ginkgo.Context("when external authentication with caching is configured", func() { - thisHost := "auth" - thatHost := "different" + thisHost := authHost + thatHost := differentHost fooPath := "/foo" barPath := "/bar" @@ -858,7 +862,7 @@ http { }) ginkgo.Context("with invalid auth-url should deny whole location", func() { - host := "auth" + host := authHost var annotations map[string]string var ing *networking.Ingress @@ -898,7 +902,6 @@ http { // Auth error func buildSecret(username, password, name, namespace string) *corev1.Secret { - //out, err := exec.Command("openssl", "passwd", "-crypt", password).CombinedOutput() out, err := bcrypt.GenerateFromPassword([]byte(password), 14) encpass := fmt.Sprintf("%v:%s\n", username, out) assert.Nil(ginkgo.GinkgoT(), err) @@ -917,7 +920,6 @@ func buildSecret(username, password, name, namespace string) *corev1.Secret { } func buildMapSecret(username, password, name, namespace string) *corev1.Secret { - //out, err := exec.Command("openssl", "passwd", "-crypt", password).CombinedOutput() out, err := bcrypt.GenerateFromPassword([]byte(password), 14) assert.Nil(ginkgo.GinkgoT(), err) @@ -928,7 +930,7 @@ func buildMapSecret(username, password, name, namespace string) *corev1.Secret { DeletionGracePeriodSeconds: framework.NewInt64(1), }, Data: map[string][]byte{ - username: []byte(out), + username: out, }, Type: corev1.SecretTypeOpaque, } diff --git a/test/e2e/annotations/authtls.go b/test/e2e/annotations/authtls.go index e96835aa0..c7a05c053 100644 --- a/test/e2e/annotations/authtls.go +++ b/test/e2e/annotations/authtls.go @@ -26,6 +26,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const authTLSFooHost = "authtls.foo.com" + var _ = framework.DescribeAnnotation("auth-tls-*", func() { f := framework.NewDefaultFramework("authtls") @@ -34,7 +36,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should set sslClientCertificate, sslVerifyClient and sslVerifyDepth with auth-tls-secret", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -82,7 +84,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should set valid auth-tls-secret, sslVerify to off, and sslVerifyDepth to 2", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace _, err := framework.CreateIngressMASecret( @@ -112,7 +114,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should 302 redirect to error page instead of 400 when auth-tls-error-page is set", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace errorPath := "/error" @@ -159,7 +161,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should pass URL-encoded certificate to upstream", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -204,7 +206,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should validate auth-tls-verify-client", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -260,11 +262,10 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { WithHeader("Host", host). Expect(). Status(http.StatusOK) - }) ginkgo.It("should return 403 using auth-tls-match-cn with no matching CN from client", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -293,7 +294,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should return 200 using auth-tls-match-cn with matching CN from client", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -322,7 +323,7 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) ginkgo.It("should return 200 using auth-tls-match-cn where atleast one of the regex options matches CN from client", func() { - host := "authtls.foo.com" + host := authTLSFooHost nameSpace := f.Namespace clientConfig, err := framework.CreateIngressMASecret( @@ -351,7 +352,8 @@ var _ = framework.DescribeAnnotation("auth-tls-*", func() { }) }) -func assertSslClientCertificateConfig(f *framework.Framework, host string, verifyClient string, verifyDepth string) { +//nolint:unparam // Ignore the invariant param: host +func assertSslClientCertificateConfig(f *framework.Framework, host, verifyClient, verifyDepth string) { sslClientCertDirective := fmt.Sprintf("ssl_client_certificate /etc/ingress-controller/ssl/%s-%s.pem;", f.Namespace, host) sslVerify := fmt.Sprintf("ssl_verify_client %s;", verifyClient) sslVerifyDepth := fmt.Sprintf("ssl_verify_depth %s;", verifyDepth) diff --git a/test/e2e/annotations/backendprotocol.go b/test/e2e/annotations/backendprotocol.go index 566a6921e..d0a08c767 100644 --- a/test/e2e/annotations/backendprotocol.go +++ b/test/e2e/annotations/backendprotocol.go @@ -24,6 +24,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const backendProtocolHost = "backendprotocol.foo.com" + var _ = framework.DescribeAnnotation("backend-protocol", func() { f := framework.NewDefaultFramework("backendprotocol") @@ -32,7 +34,7 @@ var _ = framework.DescribeAnnotation("backend-protocol", func() { }) ginkgo.It("should set backend protocol to https:// and use proxy_pass", func() { - host := "backendprotocol.foo.com" + host := backendProtocolHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/backend-protocol": "HTTPS", } @@ -47,7 +49,7 @@ var _ = framework.DescribeAnnotation("backend-protocol", func() { }) ginkgo.It("should set backend protocol to $scheme:// and use proxy_pass", func() { - host := "backendprotocol.foo.com" + host := backendProtocolHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/backend-protocol": "AUTO_HTTP", } @@ -62,7 +64,7 @@ var _ = framework.DescribeAnnotation("backend-protocol", func() { }) ginkgo.It("should set backend protocol to grpc:// and use grpc_pass", func() { - host := "backendprotocol.foo.com" + host := backendProtocolHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/backend-protocol": "GRPC", } @@ -77,7 +79,7 @@ var _ = framework.DescribeAnnotation("backend-protocol", func() { }) ginkgo.It("should set backend protocol to grpcs:// and use grpc_pass", func() { - host := "backendprotocol.foo.com" + host := backendProtocolHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/backend-protocol": "GRPCS", } @@ -92,7 +94,7 @@ var _ = framework.DescribeAnnotation("backend-protocol", func() { }) ginkgo.It("should set backend protocol to '' and use fastcgi_pass", func() { - host := "backendprotocol.foo.com" + host := backendProtocolHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/backend-protocol": "FCGI", } diff --git a/test/e2e/annotations/canary.go b/test/e2e/annotations/canary.go index 15cbeffa7..ea733dbf4 100644 --- a/test/e2e/annotations/canary.go +++ b/test/e2e/annotations/canary.go @@ -43,7 +43,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canary is created", func() { ginkgo.It("should response with a 200 status from the mainline upstream when requests are made to the mainline ingress", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -87,7 +87,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should return 404 status for requests to the canary if no matching ingress is found", func() { - host := "foo" + host := fooHost canaryAnnotations := map[string]string{ "nginx.ingress.kubernetes.io/canary": "true", @@ -118,7 +118,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { TODO: This test needs improvements made to the e2e framework so that deployment updates work in order to successfully run It("should return the correct status codes when endpoints are unavailable", func() { - host := "foo" + host := fooHost annotations := map[string]string{} ing := framework.NewSingleIngress(host, "/info", host, f.Namespace, framework.HTTPBunService, 80, annotations) @@ -172,7 +172,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { */ ginkgo.It("should route requests to the correct upstream if mainline ingress is created before the canary ingress", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -230,7 +230,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests to the correct upstream if mainline ingress is created after the canary ingress", func() { - host := "foo" + host := fooHost canaryAnnotations := map[string]string{ "nginx.ingress.kubernetes.io/canary": "true", @@ -287,7 +287,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests to the correct upstream if the mainline ingress is modified", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -321,7 +321,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { canaryAnnotations)) modAnnotations := map[string]string{ - "foo": "bar", + fooHost: "bar", } f.UpdateIngress(framework.NewSingleIngress( @@ -361,7 +361,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests to the correct upstream if the canary ingress is modified", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -443,7 +443,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by header with no value", func() { ginkgo.It("should route requests to the correct upstream", func() { - host := "foo" + host := fooHost f.EnsureIngress(framework.NewSingleIngress( host, @@ -511,7 +511,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by header with value", func() { ginkgo.It("should route requests to the correct upstream", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -592,7 +592,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by header with value and pattern", func() { ginkgo.It("should route requests to the correct upstream", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -645,7 +645,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { Body().Contains(framework.HTTPBunService).NotContains(canaryService) }) ginkgo.It("should route requests to the correct upstream", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -690,7 +690,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { Body().Contains(framework.HTTPBunService).NotContains(canaryService) }) ginkgo.It("should routes to mainline upstream when the given Regex causes error", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -739,7 +739,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by header with value and cookie", func() { ginkgo.It("should route requests to the correct upstream", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -788,7 +788,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by cookie", func() { ginkgo.It("respects always and never values", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -860,7 +860,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("when canaried by weight", func() { ginkgo.It("should route requests only to mainline if canary weight is 0", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -908,7 +908,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests only to canary if canary weight is 100", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -950,7 +950,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests only to canary if canary weight is equal to canary weight total", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -993,7 +993,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests split between mainline and canary if canary weight is 50", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -1029,7 +1029,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should route requests split between mainline and canary if canary weight is 100 and weight total is 200", func() { - host := "foo" + host := fooHost annotations := map[string]string{} f.EnsureIngress(framework.NewSingleIngress( @@ -1068,7 +1068,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { ginkgo.Context("Single canary Ingress", func() { ginkgo.It("should not use canary as a catch-all server", func() { - host := "foo" + host := fooHost canaryIngName := fmt.Sprintf("%v-canary", host) annotations := map[string]string{ "nginx.ingress.kubernetes.io/canary": "true", @@ -1102,7 +1102,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("should not use canary with domain as a server", func() { - host := "foo" + host := fooHost canaryIngName := fmt.Sprintf("%v-canary", host) annotations := map[string]string{ "nginx.ingress.kubernetes.io/canary": "true", @@ -1136,7 +1136,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.It("does not crash when canary ingress has multiple paths to the same non-matching backend", func() { - host := "foo" + host := fooHost canaryIngName := fmt.Sprintf("%v-canary", host) annotations := map[string]string{ "nginx.ingress.kubernetes.io/canary": "true", @@ -1168,7 +1168,7 @@ var _ = framework.DescribeAnnotation("canary-*", func() { }) ginkgo.Context("canary affinity behavior", func() { - host := "foo" + host := fooHost affinityCookieName := "aff" canaryIngName := fmt.Sprintf("%v-canary", host) @@ -1370,7 +1370,6 @@ var _ = framework.DescribeAnnotation("canary-*", func() { TestMainlineCanaryDistribution(f, host) }) }) - }) // This method assumes canary weight being configured at 50%. @@ -1407,12 +1406,12 @@ func TestMainlineCanaryDistribution(f *framework.Framework, host string) { assert.GreaterOrEqual( ginkgo.GinkgoT(), - int(replicaRequestCount[keys[0].String()]), + replicaRequestCount[keys[0].String()], requestsNumberToTest, ) assert.GreaterOrEqual( ginkgo.GinkgoT(), - int(replicaRequestCount[keys[1].String()]), + replicaRequestCount[keys[1].String()], requestsNumberToTest, ) } diff --git a/test/e2e/annotations/clientbodybuffersize.go b/test/e2e/annotations/clientbodybuffersize.go index 4ea1943bd..15a3530f3 100644 --- a/test/e2e/annotations/clientbodybuffersize.go +++ b/test/e2e/annotations/clientbodybuffersize.go @@ -25,6 +25,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const clientBodyBufferSizeHost = "client-body-buffer-size.com" + var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { f := framework.NewDefaultFramework("clientbodybuffersize") @@ -33,7 +35,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should set client_body_buffer_size to 1000", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1000" annotations := make(map[string]string) @@ -55,7 +57,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should set client_body_buffer_size to 1K", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1K" annotations := make(map[string]string) @@ -77,7 +79,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should set client_body_buffer_size to 1k", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1k" annotations := make(map[string]string) @@ -99,7 +101,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should set client_body_buffer_size to 1m", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1m" annotations := make(map[string]string) @@ -121,7 +123,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should set client_body_buffer_size to 1M", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1M" annotations := make(map[string]string) @@ -143,7 +145,7 @@ var _ = framework.DescribeAnnotation("client-body-buffer-size", func() { }) ginkgo.It("should not set client_body_buffer_size to invalid 1b", func() { - host := "client-body-buffer-size.com" + host := clientBodyBufferSizeHost clientBodyBufferSize := "1b" annotations := make(map[string]string) diff --git a/test/e2e/annotations/cors.go b/test/e2e/annotations/cors.go index f53bd8e9e..dd28f5dd4 100644 --- a/test/e2e/annotations/cors.go +++ b/test/e2e/annotations/cors.go @@ -25,6 +25,11 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const ( + originHost = "http://origin.com:8080" + corsHost = "cors.foo.com" +) + var _ = framework.DescribeAnnotation("cors-*", func() { f := framework.NewDefaultFramework("cors") @@ -33,7 +38,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should enable cors", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", } @@ -60,7 +65,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should set cors methods to only allow POST, GET", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-methods": "POST, GET", @@ -76,7 +81,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should set cors max-age", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-max-age": "200", @@ -92,7 +97,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should disable cors allow credentials", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-credentials": "false", @@ -108,7 +113,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow origin for cors", func() { - host := "cors.foo.com" + host := corsHost origin := "https://origin.cors.com:8080" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -135,7 +140,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow headers for cors", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-headers": "DNT, User-Agent", @@ -151,7 +156,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should expose headers for cors", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-expose-headers": "X-CustomResponseHeader, X-CustomSecondHeader", @@ -167,7 +172,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow - single origin for multiple cors values", func() { - host := "cors.foo.com" + host := corsHost origin := "https://origin.cors.com:8080" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -194,7 +199,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not allow - single origin for multiple cors values", func() { - host := "cors.foo.com" + host := corsHost origin := "http://no.origin.com" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -214,7 +219,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow correct origins - single origin for multiple cors values", func() { - host := "cors.foo.com" + host := corsHost badOrigin := "origin.cors.com:8080" origin1 := "https://origin2.cors.com" origin2 := "https://origin.com" @@ -265,7 +270,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not break functionality", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-origin": "*", @@ -289,7 +294,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not break functionality - without `*`", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", } @@ -312,7 +317,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not break functionality with extra domain", func() { - host := "cors.foo.com" + host := corsHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-origin": "*, foo.bar.com", @@ -336,7 +341,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not match", func() { - host := "cors.foo.com" + host := corsHost origin := "https://fooxbar.com" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -356,8 +361,8 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow - single origin with required port", func() { - host := "cors.foo.com" - origin := "http://origin.com:8080" + host := corsHost + origin := originHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-origin": "http://origin.cors.com:8080, http://origin.com:8080", @@ -384,8 +389,8 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not allow - single origin with port and origin without port", func() { - host := "cors.foo.com" - origin := "http://origin.com:8080" + host := corsHost + origin := originHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", "nginx.ingress.kubernetes.io/cors-allow-origin": "https://origin2.cors.com, http://origin.com", @@ -403,7 +408,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not allow - single origin without port and origin with required port", func() { - host := "cors.foo.com" + host := corsHost origin := "http://origin.com" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -423,7 +428,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow - matching origin with wildcard origin (2 subdomains)", func() { - host := "cors.foo.com" + host := corsHost origin := "http://foo.origin.cors.com" origin2 := "http://bar-foo.origin.cors.com" annotations := map[string]string{ @@ -466,7 +471,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not allow - unmatching origin with wildcard origin (2 subdomains)", func() { - host := "cors.foo.com" + host := corsHost origin := "http://bar.foo.origin.cors.com" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -486,7 +491,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow - matching origin+port with wildcard origin", func() { - host := "cors.foo.com" + host := corsHost origin := "http://abc.origin.com:8080" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -513,7 +518,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should not allow - portless origin with wildcard origin", func() { - host := "cors.foo.com" + host := corsHost origin := "http://abc.origin.com" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -533,8 +538,8 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow correct origins - missing subdomain + origin with wildcard origin and correct origin", func() { - host := "cors.foo.com" - badOrigin := "http://origin.com:8080" + host := corsHost + badOrigin := originHost origin := "http://bar.origin.com:8080" annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-cors": "true", @@ -569,7 +574,7 @@ var _ = framework.DescribeAnnotation("cors-*", func() { }) ginkgo.It("should allow - missing origins (should allow all origins)", func() { - host := "cors.foo.com" + host := corsHost origin := "http://origin.com" origin2 := "http://book.origin.com" origin3 := "test.origin.com" diff --git a/test/e2e/annotations/customhttperrors.go b/test/e2e/annotations/customhttperrors.go index 3862f817b..37a3e9695 100644 --- a/test/e2e/annotations/customhttperrors.go +++ b/test/e2e/annotations/customhttperrors.go @@ -27,7 +27,7 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) -func errorBlockName(upstreamName string, errorCode string) string { +func errorBlockName(upstreamName, errorCode string) string { return fmt.Sprintf("@custom_%s_%s", upstreamName, errorCode) } diff --git a/test/e2e/annotations/default_backend.go b/test/e2e/annotations/default_backend.go index 53c98a307..72ca303b5 100644 --- a/test/e2e/annotations/default_backend.go +++ b/test/e2e/annotations/default_backend.go @@ -48,18 +48,18 @@ var _ = framework.DescribeAnnotation("default-backend", func() { return strings.Contains(server, fmt.Sprintf("server_name %v", host)) }) - requestId := "something-unique" + requestID := "something-unique" f.HTTPTestClient(). GET("/alma/armud"). WithHeader("Host", host). - WithHeader("x-request-id", requestId). + WithHeader("x-request-id", requestID). Expect(). Status(http.StatusOK). Body().Contains("x-code=503"). Contains(fmt.Sprintf("x-ingress-name=%s", host)). Contains("x-service-name=invalid"). - Contains(fmt.Sprintf("x-request-id=%s", requestId)) + Contains(fmt.Sprintf("x-request-id=%s", requestID)) }) }) }) diff --git a/test/e2e/annotations/fromtowwwredirect.go b/test/e2e/annotations/fromtowwwredirect.go index 9201bedb7..4ee3d313c 100644 --- a/test/e2e/annotations/fromtowwwredirect.go +++ b/test/e2e/annotations/fromtowwwredirect.go @@ -90,7 +90,7 @@ var _ = framework.DescribeAnnotation("from-to-www-redirect", func() { ginkgo.By("sending request to www should redirect to domain") f.HTTPTestClientWithTLSConfig(&tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing ServerName: toHost, }). GET("/"). @@ -102,7 +102,7 @@ var _ = framework.DescribeAnnotation("from-to-www-redirect", func() { ginkgo.By("sending request to domain should not redirect to www") f.HTTPTestClientWithTLSConfig(&tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing ServerName: fromHost, }). GET("/"). diff --git a/test/e2e/annotations/globalratelimit.go b/test/e2e/annotations/globalratelimit.go index 2efcc3558..96be467fe 100644 --- a/test/e2e/annotations/globalratelimit.go +++ b/test/e2e/annotations/globalratelimit.go @@ -47,7 +47,7 @@ var _ = framework.DescribeAnnotation("annotation-global-rate-limit", func() { ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) ing = f.EnsureIngress(ing) - namespace := strings.Replace(string(ing.UID), "-", "", -1) + namespace := strings.ReplaceAll(string(ing.UID), "-", "") serverConfig := "" f.WaitForNginxServer(host, func(server string) bool { diff --git a/test/e2e/annotations/grpc.go b/test/e2e/annotations/grpc.go index 243307df4..4c121df49 100644 --- a/test/e2e/annotations/grpc.go +++ b/test/e2e/annotations/grpc.go @@ -17,12 +17,11 @@ limitations under the License. package annotations import ( + "context" "crypto/tls" "fmt" "strings" - "context" - pb "github.com/moul/pb/grpcbin/go-grpc" "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/assert" @@ -36,6 +35,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const echoHost = "echo" + var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { f := framework.NewDefaultFramework("grpc", framework.WithHTTPBunEnabled()) @@ -67,7 +68,7 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { ginkgo.It("should return OK for service with backend protocol GRPC", func() { f.NewGRPCBinDeployment() - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -102,14 +103,15 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { return strings.Contains(server, "grpc_pass grpc://upstream_balancer;") }) - conn, _ := grpc.Dial(f.GetNginxIP()+":443", + conn, err := grpc.Dial(f.GetNginxIP()+":443", grpc.WithTransportCredentials( credentials.NewTLS(&tls.Config{ - ServerName: "echo", - InsecureSkipVerify: true, + ServerName: echoHost, + InsecureSkipVerify: true, //nolint:gosec // Ignore certificate validation in testing }), ), ) + assert.Nil(ginkgo.GinkgoT(), err, "error creating a connection") defer conn.Close() client := pb.NewGRPCBinClient(conn) @@ -125,7 +127,7 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { ginkgo.It("authorization metadata should be overwritten by external auth response headers", func() { f.NewGRPCBinDeployment() - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -162,14 +164,15 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { return strings.Contains(server, "grpc_pass grpc://upstream_balancer;") }) - conn, _ := grpc.Dial(f.GetNginxIP()+":443", + conn, err := grpc.Dial(f.GetNginxIP()+":443", grpc.WithTransportCredentials( credentials.NewTLS(&tls.Config{ - ServerName: "echo", - InsecureSkipVerify: true, + ServerName: echoHost, + InsecureSkipVerify: true, //nolint:gosec // Ignore certificate validation in testing }), ), ) + assert.Nil(ginkgo.GinkgoT(), err) defer conn.Close() client := pb.NewGRPCBinClient(conn) @@ -180,13 +183,13 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { assert.Nil(ginkgo.GinkgoT(), err) metadata := res.GetMetadata() - assert.Equal(ginkgo.GinkgoT(), "foo", metadata["authorization"].Values[0]) + assert.Equal(ginkgo.GinkgoT(), fooHost, metadata["authorization"].Values[0]) }) ginkgo.It("should return OK for service with backend protocol GRPCS", func() { f.NewGRPCBinDeployment() - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -226,14 +229,15 @@ var _ = framework.DescribeAnnotation("backend-protocol - GRPC", func() { return strings.Contains(server, "grpc_pass grpcs://upstream_balancer;") }) - conn, _ := grpc.Dial(f.GetNginxIP()+":443", + conn, err := grpc.Dial(f.GetNginxIP()+":443", grpc.WithTransportCredentials( credentials.NewTLS(&tls.Config{ - ServerName: "echo", - InsecureSkipVerify: true, + ServerName: echoHost, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing }), ), ) + assert.Nil(ginkgo.GinkgoT(), err) defer conn.Close() client := pb.NewGRPCBinClient(conn) diff --git a/test/e2e/annotations/modsecurity/modsecurity.go b/test/e2e/annotations/modsecurity/modsecurity.go index 62c9bc843..71e8963e3 100644 --- a/test/e2e/annotations/modsecurity/modsecurity.go +++ b/test/e2e/annotations/modsecurity/modsecurity.go @@ -25,6 +25,17 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const ( + modSecurityFooHost = "modsecurity.foo.com" + defaultSnippet = `SecRuleEngine On + SecRequestBodyAccess On + SecAuditEngine RelevantOnly + SecAuditLogParts ABIJDEFHZ + SecAuditLog /dev/stdout + SecAuditLogType Serial + SecRule REQUEST_HEADERS:User-Agent \"block-ua\" \"log,deny,id:107,status:403,msg:\'UA blocked\'\"` +) + var _ = framework.DescribeAnnotation("modsecurity owasp", func() { f := framework.NewDefaultFramework("modsecuritylocation") @@ -33,7 +44,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -51,7 +62,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity with transaction ID and OWASP rules", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -72,7 +83,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should disable modsecurity", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -89,7 +100,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity with snippet", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -109,10 +120,11 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { ginkgo.It("should enable modsecurity without using 'modsecurity on;'", func() { f.SetNginxConfigMapData(map[string]string{ - "enable-modsecurity": "true"}, + "enable-modsecurity": "true", + }, ) - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -131,10 +143,11 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { ginkgo.It("should disable modsecurity using 'modsecurity off;'", func() { f.SetNginxConfigMapData(map[string]string{ - "enable-modsecurity": "true"}, + "enable-modsecurity": "true", + }, ) - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace annotations := map[string]string{ @@ -151,16 +164,10 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity with snippet and block requests", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace - snippet := `SecRuleEngine On - SecRequestBodyAccess On - SecAuditEngine RelevantOnly - SecAuditLogParts ABIJDEFHZ - SecAuditLog /dev/stdout - SecAuditLogType Serial - SecRule REQUEST_HEADERS:User-Agent \"block-ua\" \"log,deny,id:107,status:403,msg:\'UA blocked\'\"` + snippet := defaultSnippet annotations := map[string]string{ "nginx.ingress.kubernetes.io/enable-modsecurity": "true", @@ -187,16 +194,10 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity globally and with modsecurity-snippet block requests", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace - snippet := `SecRuleEngine On - SecRequestBodyAccess On - SecAuditEngine RelevantOnly - SecAuditLogParts ABIJDEFHZ - SecAuditLog /dev/stdout - SecAuditLogType Serial - SecRule REQUEST_HEADERS:User-Agent \"block-ua\" \"log,deny,id:107,status:403,msg:\'UA blocked\'\"` + snippet := defaultSnippet annotations := map[string]string{ "nginx.ingress.kubernetes.io/modsecurity-snippet": snippet, @@ -223,16 +224,10 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity when enable-owasp-modsecurity-crs is set to true", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace - snippet := `SecRuleEngine On - SecRequestBodyAccess On - SecAuditEngine RelevantOnly - SecAuditLogParts ABIJDEFHZ - SecAuditLog /dev/stdout - SecAuditLogType Serial - SecRule REQUEST_HEADERS:User-Agent \"block-ua\" \"log,deny,id:107,status:403,msg:\'UA blocked\'\"` + snippet := defaultSnippet annotations := map[string]string{ "nginx.ingress.kubernetes.io/modsecurity-snippet": snippet, @@ -262,7 +257,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity through the config map", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace snippet := `SecRequestBodyAccess On @@ -303,7 +298,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should enable modsecurity through the config map but ignore snippet as disabled by admin", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace snippet := `SecRequestBodyAccess On @@ -345,7 +340,7 @@ var _ = framework.DescribeAnnotation("modsecurity owasp", func() { }) ginkgo.It("should disable default modsecurity conf setting when modsecurity-snippet is specified", func() { - host := "modsecurity.foo.com" + host := modSecurityFooHost nameSpace := f.Namespace snippet := `SecRuleEngine On diff --git a/test/e2e/annotations/proxy.go b/test/e2e/annotations/proxy.go index c0c89eb43..235b828e7 100644 --- a/test/e2e/annotations/proxy.go +++ b/test/e2e/annotations/proxy.go @@ -25,6 +25,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const proxyRedirectToHost = "goodbye.com" + var _ = framework.DescribeAnnotation("proxy-*", func() { f := framework.NewDefaultFramework("proxy") host := "proxy.foo.com" @@ -38,7 +40,7 @@ var _ = framework.DescribeAnnotation("proxy-*", func() { annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-redirect-from"] = proxyRedirectFrom - annotations["nginx.ingress.kubernetes.io/proxy-redirect-to"] = "goodbye.com" + annotations["nginx.ingress.kubernetes.io/proxy-redirect-to"] = proxyRedirectToHost ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -54,7 +56,7 @@ var _ = framework.DescribeAnnotation("proxy-*", func() { annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-redirect-from"] = proxyRedirectFrom - annotations["nginx.ingress.kubernetes.io/proxy-redirect-to"] = "goodbye.com" + annotations["nginx.ingress.kubernetes.io/proxy-redirect-to"] = proxyRedirectToHost ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -67,7 +69,7 @@ var _ = framework.DescribeAnnotation("proxy-*", func() { ginkgo.It("should set proxy_redirect to hello.com goodbye.com", func() { proxyRedirectFrom := "hello.com" - proxyRedirectTo := "goodbye.com" + proxyRedirectTo := proxyRedirectToHost annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-redirect-from"] = proxyRedirectFrom @@ -244,5 +246,4 @@ var _ = framework.DescribeAnnotation("proxy-*", func() { return strings.Contains(server, fmt.Sprintf("proxy_http_version %s;", proxyHTTPVersion)) }) }) - }) diff --git a/test/e2e/annotations/proxyssl.go b/test/e2e/annotations/proxyssl.go index 7f14c3393..989d681c1 100644 --- a/test/e2e/annotations/proxyssl.go +++ b/test/e2e/annotations/proxyssl.go @@ -27,6 +27,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const proxySSLHost = "proxyssl.foo.com" + var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { f := framework.NewDefaultFramework("proxyssl") @@ -35,7 +37,7 @@ var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { }) ginkgo.It("should set valid proxy-ssl-secret", func() { - host := "proxyssl.foo.com" + host := proxySSLHost annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-ssl-secret"] = f.Namespace + "/" + host @@ -62,7 +64,7 @@ var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { }) ginkgo.It("should set valid proxy-ssl-secret, proxy-ssl-verify to on, proxy-ssl-verify-depth to 2, and proxy-ssl-server-name to on", func() { - host := "proxyssl.foo.com" + host := proxySSLHost annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-ssl-secret"] = f.Namespace + "/" + host annotations["nginx.ingress.kubernetes.io/proxy-ssl-verify"] = "on" @@ -90,9 +92,9 @@ var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { Expect(). Status(http.StatusOK) }) - + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should set valid proxy-ssl-secret, proxy-ssl-ciphers to HIGH:!AES", func() { - host := "proxyssl.foo.com" + host := proxySSLHost annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-ssl-secret"] = f.Namespace + "/" + host annotations["nginx.ingress.kubernetes.io/proxy-ssl-ciphers"] = "HIGH:!AES" @@ -118,9 +120,9 @@ var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { Expect(). Status(http.StatusOK) }) - + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should set valid proxy-ssl-secret, proxy-ssl-protocols", func() { - host := "proxyssl.foo.com" + host := proxySSLHost annotations := make(map[string]string) annotations["nginx.ingress.kubernetes.io/proxy-ssl-secret"] = f.Namespace + "/" + host annotations["nginx.ingress.kubernetes.io/proxy-ssl-protocols"] = "TLSv1.2 TLSv1.3" @@ -195,7 +197,6 @@ var _ = framework.DescribeAnnotation("proxy-ssl-*", func() { strings.Contains(server, "proxy_ssl_certificate_key")) }) }) - }) func assertProxySSL(f *framework.Framework, host, sslName, ciphers, protocols, verify string, depth int, proxySSLServerName string) { diff --git a/test/e2e/annotations/rewrite.go b/test/e2e/annotations/rewrite.go index 79738b984..173df29f0 100644 --- a/test/e2e/annotations/rewrite.go +++ b/test/e2e/annotations/rewrite.go @@ -27,6 +27,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const rewriteHost = "rewrite.bar.com" + var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-log", func() { f := framework.NewDefaultFramework("rewrite") @@ -37,7 +39,7 @@ var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-lo ginkgo.It("should write rewrite logs", func() { ginkgo.By("setting enable-rewrite-log annotation") - host := "rewrite.bar.com" + host := rewriteHost annotations := map[string]string{ "nginx.ingress.kubernetes.io/rewrite-target": "/", "nginx.ingress.kubernetes.io/enable-rewrite-log": "true", @@ -64,7 +66,7 @@ var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-lo }) ginkgo.It("should use correct longest path match", func() { - host := "rewrite.bar.com" + host := rewriteHost ginkgo.By("creating a regular ingress definition") ing := framework.NewSingleIngress("kube-lego", "/.well-known/acme/challenge", host, f.Namespace, framework.EchoService, 80, nil) @@ -109,10 +111,10 @@ var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-lo }) ginkgo.It("should use ~* location modifier if regex annotation is present", func() { - host := "rewrite.bar.com" + host := rewriteHost ginkgo.By("creating a regular ingress definition") - ing := framework.NewSingleIngress("foo", "/foo", host, f.Namespace, framework.EchoService, 80, nil) + ing := framework.NewSingleIngress(fooHost, "/foo", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) f.WaitForNginxServer(host, @@ -156,10 +158,10 @@ var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-lo }) ginkgo.It("should fail to use longest match for documented warning", func() { - host := "rewrite.bar.com" + host := rewriteHost ginkgo.By("creating a regular ingress definition") - ing := framework.NewSingleIngress("foo", "/foo/bar/bar", host, f.Namespace, framework.EchoService, 80, nil) + ing := framework.NewSingleIngress(fooHost, "/foo/bar/bar", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) ginkgo.By(`creating an ingress definition with the use-regex annotation`) @@ -188,7 +190,7 @@ var _ = framework.DescribeAnnotation("rewrite-target use-regex enable-rewrite-lo }) ginkgo.It("should allow for custom rewrite parameters", func() { - host := "rewrite.bar.com" + host := rewriteHost ginkgo.By(`creating an ingress definition with the use-regex annotation`) annotations := map[string]string{ diff --git a/test/e2e/annotations/serversnippet.go b/test/e2e/annotations/serversnippet.go index df1383bdb..e74fa37f5 100644 --- a/test/e2e/annotations/serversnippet.go +++ b/test/e2e/annotations/serversnippet.go @@ -89,6 +89,5 @@ var _ = framework.DescribeAnnotation("server-snippet", func() { Status(http.StatusOK).Headers(). NotContainsKey("Foo"). NotContainsKey("Xpto") - }) }) diff --git a/test/e2e/annotations/serviceupstream.go b/test/e2e/annotations/serviceupstream.go index 0606a2d61..1d80f304a 100644 --- a/test/e2e/annotations/serviceupstream.go +++ b/test/e2e/annotations/serviceupstream.go @@ -27,6 +27,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const dbgCmd = "/dbg backends all" + var _ = framework.DescribeAnnotation("service-upstream", func() { f := framework.NewDefaultFramework("serviceupstream") host := "serviceupstream" @@ -57,10 +59,9 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are used") s := f.GetService(f.Namespace, framework.EchoService) - dbgCmd := "/dbg backends all" output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) + assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": %q`, s.Spec.ClusterIP)) }) }) @@ -86,10 +87,9 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are used") s := f.GetService(f.Namespace, framework.EchoService) - dbgCmd := "/dbg backends all" output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) + assert.Contains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": %q`, s.Spec.ClusterIP)) }) }) @@ -117,10 +117,9 @@ var _ = framework.DescribeAnnotation("service-upstream", func() { ginkgo.By("checking if the Service Cluster IP and Port are not used") s := f.GetService(f.Namespace, framework.EchoService) - dbgCmd := "/dbg backends all" output, err := f.ExecIngressPod(dbgCmd) assert.Nil(ginkgo.GinkgoT(), err) - assert.NotContains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": "%s"`, s.Spec.ClusterIP)) + assert.NotContains(ginkgo.GinkgoT(), output, fmt.Sprintf(`"address": %q`, s.Spec.ClusterIP)) }) }) }) diff --git a/test/e2e/annotations/upstreamhashby.go b/test/e2e/annotations/upstreamhashby.go index 023a094aa..1b8106662 100644 --- a/test/e2e/annotations/upstreamhashby.go +++ b/test/e2e/annotations/upstreamhashby.go @@ -39,12 +39,13 @@ func startIngress(f *framework.Framework, annotations map[string]string) map[str return strings.Contains(server, fmt.Sprintf("server_name %s ;", host)) }) + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(framework.Poll, framework.DefaultTimeout, func() (bool, error) { - resp := f.HTTPTestClient(). GET("/"). WithHeader("Host", host). Expect().Raw() + defer resp.Body.Close() if resp.StatusCode == http.StatusOK { return true, nil @@ -55,7 +56,9 @@ func startIngress(f *framework.Framework, annotations map[string]string) map[str assert.Nil(ginkgo.GinkgoT(), err) - re, _ := regexp.Compile(fmt.Sprintf(`Hostname: %v.*`, framework.EchoService)) + re, err := regexp.Compile(fmt.Sprintf(`Hostname: %v.*`, framework.EchoService)) + assert.Nil(ginkgo.GinkgoT(), err, "error compiling regex") + podMap := map[string]bool{} for i := 0; i < 100; i++ { diff --git a/test/e2e/dbg/main.go b/test/e2e/dbg/main.go index 2df57469d..6c0a22f69 100644 --- a/test/e2e/dbg/main.go +++ b/test/e2e/dbg/main.go @@ -49,7 +49,7 @@ var _ = framework.IngressNginxDescribe("Debug CLI", func() { assert.Nil(ginkgo.GinkgoT(), err) // Should be 2: the default and the echo deployment - numUpstreams := len(strings.Split(strings.Trim(string(output), "\n"), "\n")) + numUpstreams := len(strings.Split(strings.Trim(output, "\n"), "\n")) assert.Equal(ginkgo.GinkgoT(), numUpstreams, 2) }) @@ -67,7 +67,7 @@ var _ = framework.IngressNginxDescribe("Debug CLI", func() { output, err := f.ExecIngressPod(cmd) assert.Nil(ginkgo.GinkgoT(), err) - backends := strings.Split(string(output), "\n") + backends := strings.Split(output, "\n") assert.Greater(ginkgo.GinkgoT(), len(backends), 0) getCmd := "/dbg backends get " + backends[0] diff --git a/test/e2e/e2e.go b/test/e2e/e2e.go index 28adf297d..25d714f88 100644 --- a/test/e2e/e2e.go +++ b/test/e2e/e2e.go @@ -48,7 +48,6 @@ import ( _ "k8s.io/ingress-nginx/test/e2e/settings/modsecurity" _ "k8s.io/ingress-nginx/test/e2e/settings/ocsp" _ "k8s.io/ingress-nginx/test/e2e/settings/validations" - _ "k8s.io/ingress-nginx/test/e2e/ssl" _ "k8s.io/ingress-nginx/test/e2e/status" _ "k8s.io/ingress-nginx/test/e2e/tcpudp" diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 4a7a48d92..2e556cf6d 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -26,6 +26,7 @@ func init() { testing.Init() framework.RegisterParseFlags() } + func TestE2E(t *testing.T) { RunE2ETests(t) } diff --git a/test/e2e/endpointslices/longname.go b/test/e2e/endpointslices/longname.go index 0adb66767..b2242daac 100644 --- a/test/e2e/endpointslices/longname.go +++ b/test/e2e/endpointslices/longname.go @@ -36,7 +36,6 @@ var _ = framework.IngressNginxDescribe("[Endpointslices] long service name", fun }) ginkgo.It("should return 200 when service name has max allowed number of characters 63", func() { - annotations := make(map[string]string) ing := framework.NewSingleIngress(host, "/", host, f.Namespace, name, 80, annotations) f.EnsureIngress(ing) diff --git a/test/e2e/endpointslices/topology.go b/test/e2e/endpointslices/topology.go index 2197bcb53..38c5f8b76 100644 --- a/test/e2e/endpointslices/topology.go +++ b/test/e2e/endpointslices/topology.go @@ -40,7 +40,6 @@ var _ = framework.IngressNginxDescribeSerial("[TopologyHints] topology aware rou }) ginkgo.It("should return 200 when service has topology hints", func() { - annotations := make(map[string]string) ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) f.EnsureIngress(ing) @@ -85,7 +84,7 @@ var _ = framework.IngressNginxDescribeSerial("[TopologyHints] topology aware rou } if gotHints { - //we have 2 replics, if there is just one backend it means that we are routing according slices hints to same zone as controller is + // we have 2 replics, if there is just one backend it means that we are routing according slices hints to same zone as controller is assert.Equal(ginkgo.GinkgoT(), 1, gotBackends) } else { // two replicas should have two endpoints without topology hints diff --git a/test/e2e/framework/deployment.go b/test/e2e/framework/deployment.go index 93e1811ec..7ac150dcf 100644 --- a/test/e2e/framework/deployment.go +++ b/test/e2e/framework/deployment.go @@ -50,7 +50,7 @@ var HTTPBunImage = os.Getenv("HTTPBUN_IMAGE") const EchoImage = "registry.k8s.io/ingress-nginx/e2e-test-echo@sha256:4938d1d91a2b7d19454460a8c1b010b89f6ff92d2987fd889ac3e8fc3b70d91a" // TODO: change all Deployment functions to use these options -// in order to reduce complexity and have a unified API accross the +// in order to reduce complexity and have a unified API across the // framework type deploymentOptions struct { name string @@ -317,7 +317,7 @@ func (f *Framework) GetNginxBaseImage() string { // NGINXDeployment creates a new simple NGINX Deployment using NGINX base image // and passing the desired configuration -func (f *Framework) NGINXDeployment(name string, cfg string, waitendpoint bool) { +func (f *Framework) NGINXDeployment(name, cfg string, waitendpoint bool) { cfgMap := map[string]string{ "nginx.conf": cfg, } @@ -389,7 +389,7 @@ func (f *Framework) NGINXDeployment(name string, cfg string, waitendpoint bool) } // NGINXWithConfigDeployment creates an NGINX deployment using a configmap containing the nginx.conf configuration -func (f *Framework) NGINXWithConfigDeployment(name string, cfg string) { +func (f *Framework) NGINXWithConfigDeployment(name, cfg string) { f.NGINXDeployment(name, cfg, true) } @@ -487,7 +487,8 @@ func (f *Framework) NewGRPCBinDeployment() { } func newDeployment(name, namespace, image string, port int32, replicas int32, command []string, args []string, env []corev1.EnvVar, - volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) *appsv1.Deployment { + volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool, +) *appsv1.Deployment { probe := &corev1.Probe{ InitialDelaySeconds: 2, PeriodSeconds: 1, @@ -559,12 +560,12 @@ func newDeployment(name, namespace, image string, port int32, replicas int32, co return d } -func (f *Framework) NewDeployment(name, image string, port int32, replicas int32) { +func (f *Framework) NewDeployment(name, image string, port, replicas int32) { f.NewDeploymentWithOpts(name, image, port, replicas, nil, nil, nil, nil, nil, true) } // NewDeployment creates a new deployment in a particular namespace. -func (f *Framework) NewDeploymentWithOpts(name, image string, port int32, replicas int32, command []string, args []string, env []corev1.EnvVar, volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) { +func (f *Framework) NewDeploymentWithOpts(name, image string, port, replicas int32, command, args []string, env []corev1.EnvVar, volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) { deployment := newDeployment(name, f.Namespace, image, port, replicas, command, args, env, volumeMounts, volumes, setProbe) f.EnsureDeployment(deployment) @@ -606,7 +607,7 @@ func (f *Framework) DeleteDeployment(name string) error { }) assert.Nil(ginkgo.GinkgoT(), err, "deleting deployment") - return waitForPodsDeleted(f.KubeClientSet, 2*time.Minute, f.Namespace, metav1.ListOptions{ + return waitForPodsDeleted(f.KubeClientSet, 2*time.Minute, f.Namespace, &metav1.ListOptions{ LabelSelector: labelSelectorToString(d.Spec.Selector.MatchLabels), }) } diff --git a/test/e2e/framework/exec.go b/test/e2e/framework/exec.go index 07bf09be8..9e4b55122 100644 --- a/test/e2e/framework/exec.go +++ b/test/e2e/framework/exec.go @@ -66,6 +66,7 @@ func (f *Framework) ExecCommand(pod *corev1.Pod, command string) (string, error) execErr bytes.Buffer ) + //nolint:gosec // Ignore G204 error cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%v exec --namespace %s %s --container controller -- %s", KubectlPath, pod.Namespace, pod.Name, command)) cmd.Stdout = &execOut cmd.Stderr = &execErr @@ -73,7 +74,6 @@ func (f *Framework) ExecCommand(pod *corev1.Pod, command string) (string, error) err := cmd.Run() if err != nil { return "", fmt.Errorf("could not execute '%s %s': %v", cmd.Path, cmd.Args, err) - } if execErr.Len() > 0 { @@ -91,6 +91,7 @@ func (f *Framework) NamespaceContent() (string, error) { execErr bytes.Buffer ) + //nolint:gosec // Ignore G204 error cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%v get pods,services,endpoints,deployments --namespace %s", KubectlPath, f.Namespace)) cmd.Stdout = &execOut cmd.Stderr = &execErr @@ -98,7 +99,6 @@ func (f *Framework) NamespaceContent() (string, error) { err := cmd.Run() if err != nil { return "", fmt.Errorf("could not execute '%s %s': %v", cmd.Path, cmd.Args, err) - } eout := strings.TrimSpace(execErr.String()) @@ -110,7 +110,7 @@ func (f *Framework) NamespaceContent() (string, error) { } // newIngressController deploys a new NGINX Ingress controller in a namespace -func (f *Framework) newIngressController(namespace string, namespaceOverlay string) error { +func (f *Framework) newIngressController(namespace, namespaceOverlay string) error { // Creates an nginx deployment isChroot, ok := os.LookupEnv("IS_CHROOT") if !ok { @@ -130,12 +130,11 @@ func (f *Framework) newIngressController(namespace string, namespaceOverlay stri return nil } -var ( - proxyRegexp = regexp.MustCompile("Starting to serve on .*:([0-9]+)") -) +var proxyRegexp = regexp.MustCompile(`Starting to serve on .*:(\d+)`) // KubectlProxy creates a proxy to kubernetes apiserver func (f *Framework) KubectlProxy(port int) (int, *exec.Cmd, error) { + //nolint:gosec // Ignore G204 error cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%s proxy --accept-hosts=.* --address=0.0.0.0 --port=%d", KubectlPath, port)) stdout, stderr, err := startCmdAndStreamOutput(cmd) if err != nil { @@ -163,6 +162,7 @@ func (f *Framework) KubectlProxy(port int) (int, *exec.Cmd, error) { } func (f *Framework) UninstallChart() error { + //nolint:gosec //Ignore G204 error cmd := exec.Command("helm", "uninstall", "--namespace", f.Namespace, "nginx-ingress") _, err := cmd.CombinedOutput() if err != nil { diff --git a/test/e2e/framework/fastcgi_helloserver.go b/test/e2e/framework/fastcgi_helloserver.go index 719048c06..73f9ef340 100644 --- a/test/e2e/framework/fastcgi_helloserver.go +++ b/test/e2e/framework/fastcgi_helloserver.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:dupl // Ignore dupl errors for similar test case package framework import ( @@ -75,7 +76,7 @@ func (f *Framework) NewNewFastCGIHelloServerDeploymentWithReplicas(replicas int3 d := f.EnsureDeployment(deployment) - err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, metav1.ListOptions{ + err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, &metav1.ListOptions{ LabelSelector: fields.SelectorFromSet(fields.Set(d.Spec.Template.ObjectMeta.Labels)).String(), }) assert.Nil(ginkgo.GinkgoT(), err, "failed to wait for to become ready") diff --git a/test/e2e/framework/framework.go b/test/e2e/framework/framework.go index 69f6dae78..b62ad691c 100644 --- a/test/e2e/framework/framework.go +++ b/test/e2e/framework/framework.go @@ -49,10 +49,8 @@ const ( HTTPS RequestScheme = "https" ) -var ( - // KubectlPath defines the full path of the kubectl binary - KubectlPath = "/usr/local/bin/kubectl" -) +// KubectlPath defines the full path of the kubectl binary +var KubectlPath = "/usr/local/bin/kubectl" // Framework supports common operations used by e2e tests; it will keep a client & a namespace for you. type Framework struct { @@ -131,7 +129,6 @@ func (f *Framework) CreateEnvironment() { f.KubeClientSet, err = kubernetes.NewForConfig(f.KubeConfig) assert.Nil(ginkgo.GinkgoT(), err, "creating a kubernetes client") - } f.Namespace, err = CreateKubeNamespace(f.BaseName, f.KubeClientSet) @@ -250,9 +247,9 @@ func (f *Framework) GetNginxPodIP() string { } // GetURL returns the URL should be used to make a request to NGINX -func (f *Framework) GetURL(scheme RequestScheme) string { +func (f *Framework) GetURL(requestScheme RequestScheme) string { ip := f.GetNginxIP() - return fmt.Sprintf("%v://%v", scheme, ip) + return fmt.Sprintf("%v://%v", requestScheme, ip) } // GetIngressNGINXPod returns the ingress controller running pod @@ -270,6 +267,7 @@ func (f *Framework) updateIngressNGINXPod() error { // WaitForNginxServer waits until the nginx configuration contains a particular server section. // `cfg` passed to matcher is normalized by replacing all tabs and spaces with single space. func (f *Framework) WaitForNginxServer(name string, matcher func(cfg string) bool) { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(Poll, DefaultTimeout, f.matchNginxConditions(name, matcher)) assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s") Sleep(1 * time.Second) @@ -278,13 +276,15 @@ func (f *Framework) WaitForNginxServer(name string, matcher func(cfg string) boo // WaitForNginxConfiguration waits until the nginx configuration contains a particular configuration // `cfg` passed to matcher is normalized by replacing all tabs and spaces with single space. func (f *Framework) WaitForNginxConfiguration(matcher func(cfg string) bool) { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(Poll, DefaultTimeout, f.matchNginxConditions("", matcher)) assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s") Sleep(1 * time.Second) } // WaitForNginxCustomConfiguration waits until the nginx configuration given part (from, to) contains a particular configuration -func (f *Framework) WaitForNginxCustomConfiguration(from string, to string, matcher func(cfg string) bool) { +func (f *Framework) WaitForNginxCustomConfiguration(from, to string, matcher func(cfg string) bool) { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(Poll, DefaultTimeout, f.matchNginxCustomConditions(from, to, matcher)) assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s") } @@ -325,7 +325,7 @@ func (f *Framework) matchNginxConditions(name string, matcher func(cfg string) b } } -func (f *Framework) matchNginxCustomConditions(from string, to string, matcher func(cfg string) bool) wait.ConditionFunc { +func (f *Framework) matchNginxCustomConditions(from, to string, matcher func(cfg string) bool) wait.ConditionFunc { return func() (bool, error) { cmd := fmt.Sprintf("cat /etc/nginx/nginx.conf| awk '/%v/,/%v/'", from, to) @@ -395,7 +395,7 @@ func (f *Framework) CreateConfigMap(name string, data map[string]string) { } // UpdateNginxConfigMapData updates single field in ingress-nginx's nginx-ingress-controller map data -func (f *Framework) UpdateNginxConfigMapData(key string, value string) { +func (f *Framework) UpdateNginxConfigMapData(key, value string) { config, err := f.getConfigMap("nginx-ingress-controller") assert.Nil(ginkgo.GinkgoT(), err) assert.NotNil(ginkgo.GinkgoT(), config, "expected a configmap but none returned") @@ -421,6 +421,7 @@ func (f *Framework) WaitForReload(fn func()) { fn() count := 0 + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(1*time.Second, DefaultTimeout, func() (bool, error) { reloads := getReloadCount(f.pod, f.Namespace, f.KubeClientSet) // most of the cases reload the ingress controller @@ -441,8 +442,8 @@ func getReloadCount(pod *v1.Pod, namespace string, client kubernetes.Interface) assert.Nil(ginkgo.GinkgoT(), err, "obtaining NGINX Pod") reloadCount := 0 - for _, e := range events.Items { - if e.Reason == "RELOAD" && e.Type == v1.EventTypeNormal { + for i := range events.Items { + if events.Items[i].Reason == "RELOAD" && events.Items[i].Type == v1.EventTypeNormal { reloadCount++ } } @@ -457,7 +458,7 @@ func (f *Framework) DeleteNGINXPod(grace int64) { err := f.KubeClientSet.CoreV1().Pods(ns).Delete(context.TODO(), f.pod.GetName(), *metav1.NewDeleteOptions(grace)) assert.Nil(ginkgo.GinkgoT(), err, "deleting ingress nginx pod") - + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err = wait.Poll(Poll, DefaultTimeout, func() (bool, error) { err := f.updateIngressNGINXPod() if err != nil || f.pod == nil { @@ -487,7 +488,7 @@ func (f *Framework) HTTPTestClientWithTLSConfig(config *tls.Config) *httpexpect. func (f *Framework) newHTTPTestClient(config *tls.Config, setIngressURL bool) *httpexpect.HTTPRequest { if config == nil { config = &tls.Config{ - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing } } var baseURL string @@ -507,12 +508,13 @@ func (f *Framework) newHTTPTestClient(config *tls.Config, setIngressURL bool) *h // WaitForNginxListening waits until NGINX starts accepting connections on a port func (f *Framework) WaitForNginxListening(port int) { - err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, 1, f.Namespace, metav1.ListOptions{ + err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, 1, f.Namespace, &metav1.ListOptions{ LabelSelector: "app.kubernetes.io/name=ingress-nginx", }) assert.Nil(ginkgo.GinkgoT(), err, "waiting for ingress pods to be ready") podIP := f.GetNginxIP() + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err = wait.Poll(500*time.Millisecond, DefaultTimeout, func() (bool, error) { hostPort := net.JoinHostPort(podIP, fmt.Sprintf("%v", port)) conn, err := net.Dial("tcp", hostPort) @@ -529,7 +531,7 @@ func (f *Framework) WaitForNginxListening(port int) { // WaitForPod waits for a specific Pod to be ready, using a label selector func (f *Framework) WaitForPod(selector string, timeout time.Duration, shouldFail bool) { - err := waitForPodsReady(f.KubeClientSet, timeout, 1, f.Namespace, metav1.ListOptions{ + err := waitForPodsReady(f.KubeClientSet, timeout, 1, f.Namespace, &metav1.ListOptions{ LabelSelector: selector, }) @@ -541,7 +543,7 @@ func (f *Framework) WaitForPod(selector string, timeout time.Duration, shouldFai } // UpdateDeployment runs the given updateFunc on the deployment and waits for it to be updated -func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name string, replicas int, updateFunc func(d *appsv1.Deployment) error) error { +func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace, name string, replicas int, updateFunc func(d *appsv1.Deployment) error) error { deployment, err := kubeClientSet.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return err @@ -571,7 +573,7 @@ func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name } } - err = waitForPodsReady(kubeClientSet, DefaultTimeout, replicas, namespace, metav1.ListOptions{ + err = waitForPodsReady(kubeClientSet, DefaultTimeout, replicas, namespace, &metav1.ListOptions{ LabelSelector: fields.SelectorFromSet(fields.Set(deployment.Spec.Template.ObjectMeta.Labels)).String(), }) if err != nil { @@ -582,6 +584,7 @@ func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name } func waitForDeploymentRollout(kubeClientSet kubernetes.Interface, resource *appsv1.Deployment) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, 5*time.Minute, func() (bool, error) { d, err := kubeClientSet.AppsV1().Deployments(resource.Namespace).Get(context.TODO(), resource.Name, metav1.GetOptions{}) if apierrors.IsNotFound(err) { @@ -605,7 +608,7 @@ func waitForDeploymentRollout(kubeClientSet kubernetes.Interface, resource *apps } // UpdateIngress runs the given updateFunc on the ingress -func UpdateIngress(kubeClientSet kubernetes.Interface, namespace string, name string, updateFunc func(d *networking.Ingress) error) error { +func UpdateIngress(kubeClientSet kubernetes.Interface, namespace, name string, updateFunc func(d *networking.Ingress) error) error { ingress, err := kubeClientSet.NetworkingV1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { return err diff --git a/test/e2e/framework/grpc_fortune_teller.go b/test/e2e/framework/grpc_fortune_teller.go index 02ff3aae2..a7be46327 100644 --- a/test/e2e/framework/grpc_fortune_teller.go +++ b/test/e2e/framework/grpc_fortune_teller.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:dupl // Ignore dupl errors for similar test case package framework import ( @@ -75,7 +76,7 @@ func (f *Framework) NewNewGRPCFortuneTellerDeploymentWithReplicas(replicas int32 d := f.EnsureDeployment(deployment) - err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, metav1.ListOptions{ + err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, &metav1.ListOptions{ LabelSelector: fields.SelectorFromSet(fields.Set(d.Spec.Template.ObjectMeta.Labels)).String(), }) assert.Nil(ginkgo.GinkgoT(), err, "failed to wait for to become ready") diff --git a/test/e2e/framework/healthz.go b/test/e2e/framework/healthz.go index b52c3ffde..3ee297b27 100644 --- a/test/e2e/framework/healthz.go +++ b/test/e2e/framework/healthz.go @@ -26,7 +26,7 @@ func (f *Framework) VerifyHealthz(ip string, statusCode int) error { url := fmt.Sprintf("http://%v:10254/healthz", ip) client := &http.Client{} - req, err := http.NewRequest(http.MethodGet, url, nil) + req, err := http.NewRequest(http.MethodGet, url, http.NoBody) if err != nil { return fmt.Errorf("creating GET request for URL %q failed: %v", url, err) } diff --git a/test/e2e/framework/httpexpect/match.go b/test/e2e/framework/httpexpect/match.go index b031510c4..aad10b02e 100644 --- a/test/e2e/framework/httpexpect/match.go +++ b/test/e2e/framework/httpexpect/match.go @@ -23,7 +23,7 @@ type Match struct { names map[string]int } -func makeMatch(chain chain, submatches []string, names []string) *Match { +func makeMatch(chain chain, submatches, names []string) *Match { if submatches == nil { submatches = []string{} } diff --git a/test/e2e/framework/httpexpect/object.go b/test/e2e/framework/httpexpect/object.go index f7c27faaf..49dcf5659 100644 --- a/test/e2e/framework/httpexpect/object.go +++ b/test/e2e/framework/httpexpect/object.go @@ -23,6 +23,8 @@ import ( "github.com/yudai/gojsondiff/formatter" ) +const unavailableMsg = " (unavailable)" + // Object provides methods to inspect attached map[string]interface{} object // (Go representation of JSON object). type Object struct { @@ -81,20 +83,21 @@ func diffValues(expected, actual interface{}) string { var diff gojsondiff.Diff - if ve, ok := expected.(map[string]interface{}); ok { + switch ve := expected.(type) { + case map[string]interface{}: if va, ok := actual.(map[string]interface{}); ok { diff = differ.CompareObjects(ve, va) } else { - return " (unavailable)" + return unavailableMsg } - } else if ve, ok := expected.([]interface{}); ok { + case []interface{}: if va, ok := actual.([]interface{}); ok { diff = differ.CompareArrays(ve, va) } else { - return " (unavailable)" + return unavailableMsg } - } else { - return " (unavailable)" + default: + return unavailableMsg } config := formatter.AsciiFormatterConfig{ @@ -104,7 +107,7 @@ func diffValues(expected, actual interface{}) string { str, err := f.Format(diff) if err != nil { - return " (unavailable)" + return unavailableMsg } return "--- expected\n+++ actual\n" + str diff --git a/test/e2e/framework/httpexpect/request.go b/test/e2e/framework/httpexpect/request.go index d8edb42ce..0ae85dd79 100644 --- a/test/e2e/framework/httpexpect/request.go +++ b/test/e2e/framework/httpexpect/request.go @@ -65,7 +65,7 @@ func (h *HTTPRequest) DoRequest(method, rpath string) *HTTPRequest { var request *http.Request uri.Path = path.Join(uri.Path, rpath) - if request, err = http.NewRequest(method, uri.String(), nil); err != nil { + if request, err = http.NewRequest(method, uri.String(), http.NoBody); err != nil { h.chain.fail(err.Error()) } @@ -110,6 +110,7 @@ func (h *HTTPRequest) Expect() *HTTPResponse { if err != nil { h.chain.fail(err.Error()) } + defer response.Body.Close() h.HTTPResponse.Response = response // set the HTTP response diff --git a/test/e2e/framework/k8s.go b/test/e2e/framework/k8s.go index fc3e59b08..7c067421d 100644 --- a/test/e2e/framework/k8s.go +++ b/test/e2e/framework/k8s.go @@ -47,7 +47,7 @@ func (f *Framework) EnsureSecret(secret *core.Secret) *core.Secret { } // GetConfigMap gets a ConfigMap object from the given namespace, name and returns it, throws error if it does not exist. -func (f *Framework) GetConfigMap(namespace string, name string) *core.ConfigMap { +func (f *Framework) GetConfigMap(namespace, name string) *core.ConfigMap { cm, err := f.KubeClientSet.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "getting configmap") assert.NotNil(ginkgo.GinkgoT(), cm, "expected a configmap but none returned") @@ -73,7 +73,7 @@ func (f *Framework) EnsureConfigMap(configMap *core.ConfigMap) *core.ConfigMap { } // GetIngress gets an Ingress object from the given namespace, name and returns it, throws error if it does not exists. -func (f *Framework) GetIngress(namespace string, name string) *networking.Ingress { +func (f *Framework) GetIngress(namespace, name string) *networking.Ingress { ing, err := f.KubeClientSet.NetworkingV1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "getting ingress") assert.NotNil(ginkgo.GinkgoT(), ing, "expected an ingress but none returned") @@ -114,7 +114,7 @@ func (f *Framework) UpdateIngress(ingress *networking.Ingress) *networking.Ingre } // GetService gets a Service object from the given namespace, name and returns it, throws error if it does not exist. -func (f *Framework) GetService(namespace string, name string) *core.Service { +func (f *Framework) GetService(namespace, name string) *core.Service { s, err := f.KubeClientSet.CoreV1().Services(namespace).Get(context.TODO(), name, metav1.GetOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "getting service") assert.NotNil(ginkgo.GinkgoT(), s, "expected a service but none returned") @@ -143,16 +143,21 @@ func (f *Framework) EnsureDeployment(deployment *appsv1.Deployment) *appsv1.Depl } // waitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace. -func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts metav1.ListOptions) error { +func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts *metav1.ListOptions) error { + //nolint:staticcheck // TODO: will replace it since wait.PollImmediate is deprecated return wait.PollImmediate(1*time.Second, timeout, func() (bool, error) { - pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts) + pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), *opts) if err != nil { return false, nil } r := 0 - for _, p := range pl.Items { - if isRunning, _ := podRunningReady(&p); isRunning { + for i := range pl.Items { + isRunning, err := podRunningReady(&pl.Items[i]) + if err != nil { + Logf("error checking if pod is running : %v", err) + } + if isRunning { r++ } } @@ -166,9 +171,10 @@ func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, } // waitForPodsDeleted waits for a given amount of time until a group of Pods are deleted in the given namespace. -func waitForPodsDeleted(kubeClientSet kubernetes.Interface, timeout time.Duration, namespace string, opts metav1.ListOptions) error { +func waitForPodsDeleted(kubeClientSet kubernetes.Interface, timeout time.Duration, namespace string, opts *metav1.ListOptions) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, timeout, func() (bool, error) { - pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts) + pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), *opts) if err != nil { return false, nil } @@ -186,7 +192,7 @@ func WaitForEndpoints(kubeClientSet kubernetes.Interface, timeout time.Duration, if expectedEndpoints == 0 { return nil } - + //nolint:staticcheck // TODO: will replace it since wait.PollImmediate is deprecated return wait.PollImmediate(Poll, timeout, func() (bool, error) { endpoint, err := kubeClientSet.CoreV1().Endpoints(ns).Get(context.TODO(), name, metav1.GetOptions{}) if k8sErrors.IsNotFound(err) { @@ -248,6 +254,7 @@ func isPodReady(p *core.Pod) bool { // getIngressNGINXPod returns the ingress controller running pod func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Pod, error) { var pod *core.Pod + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(1*time.Second, DefaultTimeout, func() (bool, error) { l, err := kubeClientSet.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{ LabelSelector: "app.kubernetes.io/name=ingress-nginx", @@ -256,15 +263,16 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po return false, nil } - for _, p := range l.Items { + for i := range l.Items { + p := &l.Items[i] if strings.HasPrefix(p.GetName(), "nginx-ingress-controller") { - isRunning, err := podRunningReady(&p) + isRunning, err := podRunningReady(p) if err != nil { continue } if isRunning { - pod = &p + pod = p return true, nil } } @@ -273,6 +281,7 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po return false, nil }) if err != nil { + //nolint:staticcheck // TODO: will replace it since wait.ErrWaitTimeout is deprecated if err == wait.ErrWaitTimeout { return nil, fmt.Errorf("timeout waiting at least one ingress-nginx pod running in namespace %v", ns) } @@ -285,7 +294,7 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj *appsv1.Deployment) error { if obj == nil { - return fmt.Errorf("Object provided to create is empty") + return fmt.Errorf("object provided to create is empty") } createFunc := func() (bool, error) { _, err := c.AppsV1().Deployments(namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) @@ -298,7 +307,7 @@ func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj * if isRetryableAPIError(err) { return false, nil } - return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err) + return false, fmt.Errorf("failed to create object with non-retriable error: %v", err) } return retryWithExponentialBackOff(createFunc) @@ -306,7 +315,7 @@ func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj * func createSecretWithRetries(c kubernetes.Interface, namespace string, obj *core.Secret) error { if obj == nil { - return fmt.Errorf("Object provided to create is empty") + return fmt.Errorf("object provided to create is empty") } createFunc := func() (bool, error) { _, err := c.CoreV1().Secrets(namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) @@ -319,14 +328,14 @@ func createSecretWithRetries(c kubernetes.Interface, namespace string, obj *core if isRetryableAPIError(err) { return false, nil } - return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err) + return false, fmt.Errorf("failed to create object with non-retriable error: %v", err) } return retryWithExponentialBackOff(createFunc) } func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *core.Service) error { if obj == nil { - return fmt.Errorf("Object provided to create is empty") + return fmt.Errorf("object provided to create is empty") } createFunc := func() (bool, error) { _, err := c.CoreV1().Services(namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) @@ -339,7 +348,7 @@ func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *cor if isRetryableAPIError(err) { return false, nil } - return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err) + return false, fmt.Errorf("failed to create object with non-retriable error: %v", err) } return retryWithExponentialBackOff(createFunc) @@ -347,7 +356,7 @@ func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *cor func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *networking.Ingress) error { if obj == nil { - return fmt.Errorf("Object provided to create is empty") + return fmt.Errorf("object provided to create is empty") } createFunc := func() (bool, error) { _, err := c.NetworkingV1().Ingresses(namespace).Create(context.TODO(), obj, metav1.CreateOptions{}) @@ -360,7 +369,7 @@ func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *net if isRetryableAPIError(err) { return false, nil } - return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err) + return false, fmt.Errorf("failed to create object with non-retriable error: %v", err) } return retryWithExponentialBackOff(createFunc) @@ -368,7 +377,7 @@ func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *net func updateIngressWithRetries(c kubernetes.Interface, namespace string, obj *networking.Ingress) error { if obj == nil { - return fmt.Errorf("Object provided to create is empty") + return fmt.Errorf("object provided to create is empty") } updateFunc := func() (bool, error) { _, err := c.NetworkingV1().Ingresses(namespace).Update(context.TODO(), obj, metav1.UpdateOptions{}) @@ -378,7 +387,7 @@ func updateIngressWithRetries(c kubernetes.Interface, namespace string, obj *net if isRetryableAPIError(err) { return false, nil } - return false, fmt.Errorf("Failed to update object with non-retriable error: %v", err) + return false, fmt.Errorf("failed to update object with non-retriable error: %v", err) } return retryWithExponentialBackOff(updateFunc) diff --git a/test/e2e/framework/metrics.go b/test/e2e/framework/metrics.go index 830237540..774f1bd7e 100644 --- a/test/e2e/framework/metrics.go +++ b/test/e2e/framework/metrics.go @@ -29,7 +29,7 @@ func (f *Framework) GetMetric(metricName, ip string) (*dto.MetricFamily, error) url := fmt.Sprintf("http://%v:10254/metrics", ip) client := &http.Client{} - req, err := http.NewRequest(http.MethodGet, url, nil) + req, err := http.NewRequest(http.MethodGet, url, http.NoBody) if err != nil { return nil, fmt.Errorf("creating GET request for URL %q failed: %v", url, err) } @@ -44,7 +44,6 @@ func (f *Framework) GetMetric(metricName, ip string) (*dto.MetricFamily, error) var parser expfmt.TextParser metrics, err := parser.TextToMetricFamilies(resp.Body) - if err != nil { return nil, fmt.Errorf("reading text format failed: %v", err) } diff --git a/test/e2e/framework/ssl.go b/test/e2e/framework/ssl.go index 52ceffc57..d6252fe47 100644 --- a/test/e2e/framework/ssl.go +++ b/test/e2e/framework/ssl.go @@ -93,8 +93,8 @@ func CreateIngressTLSSecret(client kubernetes.Interface, hosts []string, secretN // CreateIngressMASecret creates or updates a Secret containing a Mutual Auth // certificate-chain for the given Ingress and returns a TLS configuration suitable // for HTTP clients to use against that particular Ingress. -func CreateIngressMASecret(client kubernetes.Interface, host string, secretName, namespace string) (*tls.Config, error) { - if len(host) == 0 { +func CreateIngressMASecret(client kubernetes.Interface, host, secretName, namespace string) (*tls.Config, error) { + if host == "" { return nil, fmt.Errorf("requires a non-empty host") } @@ -138,12 +138,13 @@ func CreateIngressMASecret(client kubernetes.Interface, host string, secretName, return &tls.Config{ ServerName: host, Certificates: []tls.Certificate{clientPair}, - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing }, nil } // WaitForTLS waits until the TLS handshake with a given server completes successfully. func WaitForTLS(url string, tlsConfig *tls.Config) { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err := wait.Poll(Poll, DefaultTimeout, matchTLSServerName(url, tlsConfig)) assert.Nil(ginkgo.GinkgoT(), err, "waiting for TLS configuration in URL %s", url) } @@ -160,7 +161,6 @@ func generateRSACert(host string, isCA bool, keyOut, certOut io.Writer) error { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { return fmt.Errorf("failed to generate serial number: %s", err) } @@ -329,7 +329,7 @@ func tlsConfig(serverName string, pemCA []byte) (*tls.Config, error) { if !rootCAPool.AppendCertsFromPEM(pemCA) { return nil, fmt.Errorf("error creating CA certificate pool (%s)", serverName) } - return &tls.Config{ + return &tls.Config{ //nolint:gosec // Ignore the gosec error in testing ServerName: serverName, RootCAs: rootCAPool, }, nil diff --git a/test/e2e/framework/test_context.go b/test/e2e/framework/test_context.go index be4cd6e5e..961357885 100644 --- a/test/e2e/framework/test_context.go +++ b/test/e2e/framework/test_context.go @@ -23,7 +23,7 @@ import ( // TestContextType describes the client context to use in communications with the Kubernetes API. type TestContextType struct { KubeHost string - //KubeConfig string + // KubeConfig string KubeContext string } @@ -33,7 +33,6 @@ var TestContext TestContextType // registerCommonFlags registers flags common to all e2e test suites. func registerCommonFlags() { flag.StringVar(&TestContext.KubeHost, "kubernetes-host", "http://127.0.0.1:8080", "The kubernetes host, or apiserver, to connect to") - //flag.StringVar(&TestContext.KubeConfig, "kubernetes-config", os.Getenv(clientcmd.RecommendedConfigPathEnvVar), "Path to config containing embedded authinfo for kubernetes. Default value is from environment variable "+clientcmd.RecommendedConfigPathEnvVar) flag.StringVar(&TestContext.KubeContext, "kubernetes-context", "", "config context to use for kubernetes. If unset, will use value from 'current-context'") } diff --git a/test/e2e/framework/util.go b/test/e2e/framework/util.go index 90f15eb1b..abdb168e1 100644 --- a/test/e2e/framework/util.go +++ b/test/e2e/framework/util.go @@ -49,24 +49,24 @@ func nowStamp() string { return time.Now().Format(time.StampMilli) } -func log(level string, format string, args ...interface{}) { +func logf(level, format string, args ...interface{}) { fmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...) } // Logf logs to the INFO logs. func Logf(format string, args ...interface{}) { - log("INFO", format, args...) + logf("INFO", format, args...) } // Failf logs to the INFO logs and fails the test. func Failf(format string, args ...interface{}) { msg := fmt.Sprintf(format, args...) - log("INFO", msg) + logf("INFO", msg) ginkgo.Fail(nowStamp()+": "+msg, 1) } // RestclientConfig deserializes the contents of a kubeconfig file into a Config object. -func RestclientConfig(config, context string) (*api.Config, error) { +func RestclientConfig(config, newContext string) (*api.Config, error) { Logf(">>> config: %s\n", config) if config == "" { return nil, fmt.Errorf("config file must be specified to load client config") @@ -75,9 +75,9 @@ func RestclientConfig(config, context string) (*api.Config, error) { if err != nil { return nil, fmt.Errorf("error loading config: %v", err.Error()) } - if context != "" { - Logf(">>> context: %s\n", context) - c.CurrentContext = context + if newContext != "" { + Logf(">>> context: %s\n", newContext) + c.CurrentContext = newContext } return c, nil } @@ -98,6 +98,7 @@ func createNamespace(baseName string, labels map[string]string, c kubernetes.Int var got *corev1.Namespace var err error + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err = wait.Poll(Poll, DefaultTimeout, func() (bool, error) { got, err = c.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{}) if err != nil { @@ -114,13 +115,11 @@ func createNamespace(baseName string, labels map[string]string, c kubernetes.Int // CreateKubeNamespace creates a new namespace in the cluster func CreateKubeNamespace(baseName string, c kubernetes.Interface) (string, error) { - return createNamespace(baseName, nil, c) } // CreateKubeNamespaceWithLabel creates a new namespace with given labels in the cluster func CreateKubeNamespaceWithLabel(baseName string, labels map[string]string, c kubernetes.Interface) (string, error) { - return createNamespace(baseName, labels, c) } @@ -150,7 +149,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error }, }, metav1.CreateOptions{}) if err != nil { - return "", fmt.Errorf("Unexpected error creating IngressClass %s: %v", icname, err) + return "", fmt.Errorf("unexpected error creating IngressClass %s: %v", icname, err) } _, err = c.RbacV1().ClusterRoles().Create(context.TODO(), &rbacv1.ClusterRole{ @@ -162,7 +161,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error }}, }, metav1.CreateOptions{}) if err != nil { - return "", fmt.Errorf("Unexpected error creating IngressClass ClusterRole %s: %v", icname, err) + return "", fmt.Errorf("unexpected error creating IngressClass ClusterRole %s: %v", icname, err) } _, err = c.RbacV1().ClusterRoleBindings().Create(context.TODO(), &rbacv1.ClusterRoleBinding{ @@ -184,7 +183,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error }, }, metav1.CreateOptions{}) if err != nil { - return "", fmt.Errorf("Unexpected error creating IngressClass ClusterRoleBinding %s: %v", icname, err) + return "", fmt.Errorf("unexpected error creating IngressClass ClusterRoleBinding %s: %v", icname, err) } return ic.Name, nil } @@ -200,16 +199,16 @@ func deleteIngressClass(c kubernetes.Interface, ingressclass string) error { } err = c.NetworkingV1().IngressClasses().Delete(context.TODO(), ingressclass, deleteOptions) if err != nil { - return fmt.Errorf("Unexpected error deleting IngressClass %s: %v", ingressclass, err) + return fmt.Errorf("unexpected error deleting IngressClass %s: %v", ingressclass, err) } err = c.RbacV1().ClusterRoleBindings().Delete(context.TODO(), ingressclass, deleteOptions) if err != nil { - return fmt.Errorf("Unexpected error deleting IngressClass ClusterRoleBinding %s: %v", ingressclass, err) + return fmt.Errorf("unexpected error deleting IngressClass ClusterRoleBinding %s: %v", ingressclass, err) } err = c.RbacV1().ClusterRoles().Delete(context.TODO(), ingressclass, deleteOptions) if err != nil { - return fmt.Errorf("Unexpected error deleting IngressClass ClusterRole %s: %v", ingressclass, err) + return fmt.Errorf("unexpected error deleting IngressClass ClusterRole %s: %v", ingressclass, err) } return nil @@ -223,6 +222,7 @@ func GetIngressClassName(namespace string) *string { // WaitForKubeNamespaceNotExist waits until a namespaces is not present in the cluster func WaitForKubeNamespaceNotExist(c kubernetes.Interface, namespace string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, namespaceNotExist(c, namespace)) } @@ -241,6 +241,7 @@ func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionF // WaitForNoPodsInNamespace waits until there are no pods running in a namespace func WaitForNoPodsInNamespace(c kubernetes.Interface, namespace string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, noPodsInNamespace(c, namespace)) } @@ -267,15 +268,17 @@ func WaitForPodRunningInNamespace(c kubernetes.Interface, pod *corev1.Pod) error if pod.Status.Phase == corev1.PodRunning { return nil } - return waitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace, DefaultTimeout) + return waitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace) } -func waitTimeoutForPodRunningInNamespace(c kubernetes.Interface, podName, namespace string, timeout time.Duration) error { +func waitTimeoutForPodRunningInNamespace(c kubernetes.Interface, podName, namespace string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, podRunning(c, podName, namespace)) } // WaitForSecretInNamespace waits a default amount of time for the specified secret is present in a particular namespace func WaitForSecretInNamespace(c kubernetes.Interface, namespace, name string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, secretInNamespace(c, namespace, name)) } @@ -298,6 +301,7 @@ func secretInNamespace(c kubernetes.Interface, namespace, name string) wait.Cond // WaitForFileInFS waits a default amount of time for the specified file is present in the filesystem func WaitForFileInFS(file string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, fileInFS(file)) } @@ -322,6 +326,7 @@ func fileInFS(file string) wait.ConditionFunc { // WaitForNoIngressInNamespace waits until there is no ingress object in a particular namespace func WaitForNoIngressInNamespace(c kubernetes.Interface, namespace, name string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, noIngressInNamespace(c, namespace, name)) } @@ -344,6 +349,7 @@ func noIngressInNamespace(c kubernetes.Interface, namespace, name string) wait.C // WaitForIngressInNamespace waits until a particular ingress object exists namespace func WaitForIngressInNamespace(c kubernetes.Interface, namespace, name string) error { + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated return wait.Poll(Poll, DefaultTimeout, ingressInNamespace(c, namespace, name)) } diff --git a/test/e2e/gracefulshutdown/grace_period.go b/test/e2e/gracefulshutdown/grace_period.go index 12e2f3d67..123892f3a 100644 --- a/test/e2e/gracefulshutdown/grace_period.go +++ b/test/e2e/gracefulshutdown/grace_period.go @@ -33,7 +33,6 @@ var _ = framework.IngressNginxDescribe("[Shutdown] Grace period shutdown", func( f := framework.NewDefaultFramework("shutdown-grace-period") ginkgo.It("/healthz should return status code 500 during shutdown grace period", func() { - f.NewSlowEchoDeployment() err := f.UpdateIngressControllerDeployment(func(deployment *appsv1.Deployment) error { @@ -83,6 +82,5 @@ var _ = framework.IngressNginxDescribe("[Shutdown] Grace period shutdown", func( for _, err := range <-result { assert.Nil(ginkgo.GinkgoT(), err) } - }) }) diff --git a/test/e2e/ingress/pathtype_exact.go b/test/e2e/ingress/pathtype_exact.go index ae2902e9f..ccc76b5bc 100644 --- a/test/e2e/ingress/pathtype_exact.go +++ b/test/e2e/ingress/pathtype_exact.go @@ -35,14 +35,13 @@ var _ = framework.IngressNginxDescribe("[Ingress] [PathType] exact", func() { }) ginkgo.It("should choose exact location for /exact", func() { - host := "exact.path" annotations := map[string]string{ "nginx.ingress.kubernetes.io/configuration-snippet": `more_set_input_headers "pathType: exact";`, } - var exactPathType = networking.PathTypeExact + exactPathType := networking.PathTypeExact ing := framework.NewSingleIngress("exact", "/exact", host, f.Namespace, framework.EchoService, 80, annotations) ing.Spec.Rules[0].IngressRuleValue.HTTP.Paths[0].PathType = &exactPathType f.EnsureIngress(ing) diff --git a/test/e2e/ingress/pathtype_mixed.go b/test/e2e/ingress/pathtype_mixed.go index dd183bbb4..c55a2c32a 100644 --- a/test/e2e/ingress/pathtype_mixed.go +++ b/test/e2e/ingress/pathtype_mixed.go @@ -34,10 +34,9 @@ var _ = framework.IngressNginxDescribe("[Ingress] [PathType] mix Exact and Prefi f.NewEchoDeployment() }) - var exactPathType = networking.PathTypeExact + exactPathType := networking.PathTypeExact ginkgo.It("should choose the correct location", func() { - host := "mixed.path" annotations := map[string]string{ diff --git a/test/e2e/leaks/lua_ssl.go b/test/e2e/leaks/lua_ssl.go index e63a1e353..88285ba4b 100644 --- a/test/e2e/leaks/lua_ssl.go +++ b/test/e2e/leaks/lua_ssl.go @@ -87,14 +87,14 @@ func provisionIngress(hostname string, f *framework.Framework) { func checkIngress(hostname string, f *framework.Framework) { resp := f.HTTPTestClientWithTLSConfig(&tls.Config{ ServerName: hostname, - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing }). GET("/"). WithURL(f.GetURL(framework.HTTPS)). WithHeader("Host", hostname). Expect(). Raw() - + defer resp.Body.Close() assert.Equal(ginkgo.GinkgoT(), resp.StatusCode, http.StatusOK) // check the returned secret is not the fake one diff --git a/test/e2e/loadbalance/configmap.go b/test/e2e/loadbalance/configmap.go index 8cd47286b..737cd06dd 100644 --- a/test/e2e/loadbalance/configmap.go +++ b/test/e2e/loadbalance/configmap.go @@ -25,6 +25,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const loadBalanceHost = "load-balance.com" + var _ = framework.DescribeSetting("[Load Balancer] load-balance", func() { f := framework.NewDefaultFramework("lb-configmap") @@ -33,7 +35,7 @@ var _ = framework.DescribeSetting("[Load Balancer] load-balance", func() { }) ginkgo.It("should apply the configmap load-balance setting", func() { - host := "load-balance.com" + host := loadBalanceHost f.UpdateNginxConfigMapData("load-balance", "ewma") diff --git a/test/e2e/loadbalance/ewma.go b/test/e2e/loadbalance/ewma.go index e2750a09a..f457e6357 100644 --- a/test/e2e/loadbalance/ewma.go +++ b/test/e2e/loadbalance/ewma.go @@ -35,12 +35,13 @@ var _ = framework.DescribeSetting("[Load Balancer] EWMA", func() { f.NewEchoDeployment(framework.WithDeploymentReplicas(3)) f.SetNginxConfigMapData(map[string]string{ "worker-processes": "2", - "load-balance": "ewma"}, + "load-balance": "ewma", + }, ) }) ginkgo.It("does not fail requests", func() { - host := "load-balance.com" + host := loadBalanceHost f.EnsureIngress(framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil)) f.WaitForNginxServer(host, @@ -52,7 +53,9 @@ var _ = framework.DescribeSetting("[Load Balancer] EWMA", func() { assert.Nil(ginkgo.GinkgoT(), err) assert.Equal(ginkgo.GinkgoT(), algorithm, "ewma") - re, _ := regexp.Compile(fmt.Sprintf(`%v.*`, framework.EchoService)) + re, err := regexp.Compile(fmt.Sprintf(`%v.*`, framework.EchoService)) + assert.Nil(ginkgo.GinkgoT(), err, "error compiling regex") + replicaRequestCount := map[string]int{} for i := 0; i < 30; i++ { diff --git a/test/e2e/loadbalance/round_robin.go b/test/e2e/loadbalance/round_robin.go index 2d0582e9a..5f6667143 100644 --- a/test/e2e/loadbalance/round_robin.go +++ b/test/e2e/loadbalance/round_robin.go @@ -37,7 +37,7 @@ var _ = framework.DescribeSetting("[Load Balancer] round-robin", func() { }) ginkgo.It("should evenly distribute requests with round-robin (default algorithm)", func() { - host := "load-balance.com" + host := loadBalanceHost f.EnsureIngress(framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil)) f.WaitForNginxServer(host, @@ -45,7 +45,9 @@ var _ = framework.DescribeSetting("[Load Balancer] round-robin", func() { return strings.Contains(server, "server_name load-balance.com") }) - re, _ := regexp.Compile(fmt.Sprintf(`%v.*`, framework.EchoService)) + re, err := regexp.Compile(fmt.Sprintf(`%v.*`, framework.EchoService)) + assert.Nil(ginkgo.GinkgoT(), err, "error compiling regex") + replicaRequestCount := map[string]int{} for i := 0; i < 600; i++ { diff --git a/test/e2e/lua/dynamic_certificates.go b/test/e2e/lua/dynamic_certificates.go index 0160cc9e7..8c9df5e71 100644 --- a/test/e2e/lua/dynamic_certificates.go +++ b/test/e2e/lua/dynamic_certificates.go @@ -245,7 +245,6 @@ var _ = framework.IngressNginxDescribe("[Lua] dynamic certificates", func() { WithHeader("Host", host). Expect(). Status(http.StatusOK) - }) }) }) @@ -254,7 +253,6 @@ func extractReloadCount(mf *dto.MetricFamily) (float64, error) { vec, err := expfmt.ExtractSamples(&expfmt.DecodeOptions{ Timestamp: model.Now(), }, mf) - if err != nil { return 0, err } diff --git a/test/e2e/lua/dynamic_configuration.go b/test/e2e/lua/dynamic_configuration.go index 8e9804545..8ec1ef839 100644 --- a/test/e2e/lua/dynamic_configuration.go +++ b/test/e2e/lua/dynamic_configuration.go @@ -26,7 +26,6 @@ import ( "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/assert" - networking "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/ingress-nginx/test/e2e/framework" @@ -199,20 +198,18 @@ var _ = framework.IngressNginxDescribe("[Lua] dynamic configuration", func() { }) }) -func ensureIngress(f *framework.Framework, host string, deploymentName string) *networking.Ingress { - ing := createIngress(f, host, deploymentName) +func ensureIngress(f *framework.Framework, host, deploymentName string) { + createIngress(f, host, deploymentName) f.HTTPTestClient(). GET("/"). WithHeader("Host", host). Expect(). Status(http.StatusOK) - - return ing } -func createIngress(f *framework.Framework, host string, deploymentName string) *networking.Ingress { - ing := f.EnsureIngress(framework.NewSingleIngress(host, "/", host, f.Namespace, deploymentName, 80, +func createIngress(f *framework.Framework, host, deploymentName string) { + f.EnsureIngress(framework.NewSingleIngress(host, "/", host, f.Namespace, deploymentName, 80, map[string]string{ "nginx.ingress.kubernetes.io/load-balance": "ewma", }, @@ -223,21 +220,19 @@ func createIngress(f *framework.Framework, host string, deploymentName string) * return strings.Contains(server, fmt.Sprintf("server_name %s ;", host)) && strings.Contains(server, "proxy_pass http://upstream_balancer;") }) - - return ing } -func ensureHTTPSRequest(f *framework.Framework, url string, host string, expectedDNSName string) { +func ensureHTTPSRequest(f *framework.Framework, url, host, expectedDNSName string) { resp := f.HTTPTestClientWithTLSConfig(&tls.Config{ ServerName: host, - InsecureSkipVerify: true, + InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing }). GET("/"). WithURL(url). WithHeader("Host", host). Expect(). Raw() - + defer resp.Body.Close() assert.Equal(ginkgo.GinkgoT(), resp.StatusCode, http.StatusOK) assert.Equal(ginkgo.GinkgoT(), len(resp.TLS.PeerCertificates), 1) assert.Equal(ginkgo.GinkgoT(), resp.TLS.PeerCertificates[0].DNSNames[0], expectedDNSName) diff --git a/test/e2e/nginx/nginx.go b/test/e2e/nginx/nginx.go index cd14a931c..7e572a976 100644 --- a/test/e2e/nginx/nginx.go +++ b/test/e2e/nginx/nginx.go @@ -100,7 +100,6 @@ var _ = framework.DescribeSetting("nginx-configuration", func() { f := framework.NewSimpleFramework("nginxconfiguration") ginkgo.It("start nginx with default configuration", func() { - f.NGINXWithConfigDeployment("default-nginx", cfgOK) f.WaitForPod("app=default-nginx", 60*time.Second, false) framework.Sleep(5 * time.Second) @@ -113,20 +112,16 @@ var _ = framework.DescribeSetting("nginx-configuration", func() { }) ginkgo.It("fails when using alias directive", func() { - f.NGINXDeployment("alias-nginx", cfgAlias, false) // This should fail with a crashloopback because our NGINX does not have // alias directive! f.WaitForPod("app=alias-nginx", 60*time.Second, true) - }) ginkgo.It("fails when using root directive", func() { - f.NGINXDeployment("root-nginx", cfgRoot, false) // This should fail with a crashloopback because our NGINX does not have // root directive! f.WaitForPod("app=root-nginx", 60*time.Second, true) - }) }) diff --git a/test/e2e/security/request_smuggling.go b/test/e2e/security/request_smuggling.go index 58b17c4d8..5ede02d4b 100644 --- a/test/e2e/security/request_smuggling.go +++ b/test/e2e/security/request_smuggling.go @@ -50,9 +50,9 @@ server { f.UpdateNginxConfigMapData("http-snippet", snippet) - //TODO: currently using a self hosted HTTPBun instance results in a 499, we - //should move away from using httpbun.com once we have the httpbun - //deployment as part of the framework + // TODO: currently using a self hosted HTTPBun instance results in a 499, we + // should move away from using httpbun.com once we have the httpbun + // deployment as part of the framework ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, map[string]string{ "nginx.ingress.kubernetes.io/auth-signin": "https://httpbun.com/bearer/d4bcba7a-0def-4a31-91a7-47e420adf44b", "nginx.ingress.kubernetes.io/auth-url": "https://httpbun.com/basic-auth/user/passwd", @@ -91,7 +91,7 @@ func smugglingRequest(host, addr string, port int) (string, error) { // wait for /_hidden/index.html response framework.Sleep() - var buf = make([]byte, 1024) + buf := make([]byte, 1024) r := bufio.NewReader(conn) _, err = r.Read(buf) if err != nil { diff --git a/test/e2e/servicebackend/service_backend.go b/test/e2e/servicebackend/service_backend.go index 44f3d36a5..6ab2f8ad1 100644 --- a/test/e2e/servicebackend/service_backend.go +++ b/test/e2e/servicebackend/service_backend.go @@ -29,48 +29,50 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) -var pathtype = networking.PathTypePrefix -var _ = framework.IngressNginxDescribe("[Service] backend status code 503", func() { - f := framework.NewDefaultFramework("service-backend") +var ( + pathtype = networking.PathTypePrefix + _ = framework.IngressNginxDescribe("[Service] backend status code 503", func() { + f := framework.NewDefaultFramework("service-backend") - ginkgo.It("should return 503 when backend service does not exist", func() { - host := "nonexistent.svc.com" + ginkgo.It("should return 503 when backend service does not exist", func() { + host := "nonexistent.svc.com" - bi := buildIngressWithNonexistentService(host, f.Namespace, "/") - f.EnsureIngress(bi) + bi := buildIngressWithNonexistentService(host, f.Namespace, "/") + f.EnsureIngress(bi) - f.WaitForNginxServer(host, - func(server string) bool { - return strings.Contains(server, "proxy_pass http://upstream_balancer;") - }) + f.WaitForNginxServer(host, + func(server string) bool { + return strings.Contains(server, "proxy_pass http://upstream_balancer;") + }) - f.HTTPTestClient(). - GET("/"). - WithHeader("Host", host). - Expect(). - Status(http.StatusServiceUnavailable) + f.HTTPTestClient(). + GET("/"). + WithHeader("Host", host). + Expect(). + Status(http.StatusServiceUnavailable) + }) + + ginkgo.It("should return 503 when all backend service endpoints are unavailable", func() { + host := "unavailable.svc.com" + + bi, bs := buildIngressWithUnavailableServiceEndpoints(host, f.Namespace, "/") + + f.EnsureService(bs) + f.EnsureIngress(bi) + + f.WaitForNginxServer(host, + func(server string) bool { + return strings.Contains(server, "proxy_pass http://upstream_balancer;") + }) + + f.HTTPTestClient(). + GET("/"). + WithHeader("Host", host). + Expect(). + Status(http.StatusServiceUnavailable) + }) }) - - ginkgo.It("should return 503 when all backend service endpoints are unavailable", func() { - host := "unavailable.svc.com" - - bi, bs := buildIngressWithUnavailableServiceEndpoints(host, f.Namespace, "/") - - f.EnsureService(bs) - f.EnsureIngress(bi) - - f.WaitForNginxServer(host, - func(server string) bool { - return strings.Contains(server, "proxy_pass http://upstream_balancer;") - }) - - f.HTTPTestClient(). - GET("/"). - WithHeader("Host", host). - Expect(). - Status(http.StatusServiceUnavailable) - }) -}) +) func buildIngressWithNonexistentService(host, namespace, path string) *networking.Ingress { backendService := "nonexistent-svc" @@ -146,14 +148,15 @@ func buildIngressWithUnavailableServiceEndpoints(host, namespace, path string) ( Name: backendService, Namespace: namespace, }, - Spec: corev1.ServiceSpec{Ports: []corev1.ServicePort{ - { - Name: "tcp", - Port: 80, - TargetPort: intstr.FromInt(80), - Protocol: "TCP", + Spec: corev1.ServiceSpec{ + Ports: []corev1.ServicePort{ + { + Name: "tcp", + Port: 80, + TargetPort: intstr.FromInt(80), + Protocol: "TCP", + }, }, - }, Selector: map[string]string{ "app": backendService, }, diff --git a/test/e2e/servicebackend/service_externalname.go b/test/e2e/servicebackend/service_externalname.go index 429690ff1..fccd1cd19 100644 --- a/test/e2e/servicebackend/service_externalname.go +++ b/test/e2e/servicebackend/service_externalname.go @@ -33,12 +33,14 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const echoHost = "echo" + var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { f := framework.NewDefaultFramework("type-externalname", framework.WithHTTPBunEnabled()) ginkgo.It("works with external name set to incomplete fqdn", func() { f.NewEchoDeployment() - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -74,7 +76,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should return 200 for service type=ExternalName without a port defined", func() { - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -114,7 +116,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should return 200 for service type=ExternalName with a port defined", func() { - host := "echo" + host := echoHost svc := framework.BuildNIPExternalNameService(f, f.HTTPBunIP, host) f.EnsureService(svc) @@ -144,7 +146,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should return status 502 for service type=ExternalName with an invalid host", func() { - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -180,7 +182,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should return 200 for service type=ExternalName using a port name", func() { - host := "echo" + host := echoHost svc := framework.BuildNIPExternalNameService(f, f.HTTPBunIP, host) f.EnsureService(svc) @@ -221,7 +223,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should return 200 for service type=ExternalName using FQDN with trailing dot", func() { - host := "echo" + host := echoHost svc := &corev1.Service{ ObjectMeta: metav1.ObjectMeta{ @@ -257,7 +259,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { }) ginkgo.It("should update the external name after a service update", func() { - host := "echo" + host := echoHost svc := framework.BuildNIPExternalNameService(f, f.HTTPBunIP, host) f.EnsureService(svc) @@ -306,7 +308,7 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { Get(context.TODO(), framework.NIPService, metav1.GetOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "unexpected error obtaining external service") - //Deploy a new instance to switch routing to + // Deploy a new instance to switch routing to ip := f.NewHttpbunDeployment(framework.WithDeploymentName("eu-server")) svc.Spec.ExternalName = framework.BuildNIPHost(ip) @@ -335,12 +337,12 @@ var _ = framework.IngressNginxDescribe("[Service] Type ExternalName", func() { assert.Contains( ginkgo.GinkgoT(), output, - fmt.Sprintf(`"address": "%s"`, framework.BuildNIPHost(ip)), + fmt.Sprintf(`"address": %q`, framework.BuildNIPHost(ip)), ) }) ginkgo.It("should sync ingress on external name service addition/deletion", func() { - host := "echo" + host := echoHost // Create the Ingress first ing := framework.NewSingleIngress(host, diff --git a/test/e2e/servicebackend/service_nil_backend.go b/test/e2e/servicebackend/service_nil_backend.go index c44601c88..9b5b4c7e6 100644 --- a/test/e2e/servicebackend/service_nil_backend.go +++ b/test/e2e/servicebackend/service_nil_backend.go @@ -64,7 +64,6 @@ var _ = framework.IngressNginxDescribe("[Service] Nil Service Backend", func() { WithHeader("Host", invalidHost). Expect(). Status(http.StatusNotFound) - }) }) diff --git a/test/e2e/settings/access_log.go b/test/e2e/settings/access_log.go index 7c7e2b9e3..65b9dfda4 100644 --- a/test/e2e/settings/access_log.go +++ b/test/e2e/settings/access_log.go @@ -28,7 +28,6 @@ var _ = framework.DescribeSetting("access-log", func() { f := framework.NewDefaultFramework("access-log") ginkgo.Context("access-log-path", func() { - ginkgo.It("use the default configuration", func() { f.WaitForNginxConfiguration( func(cfg string) bool { @@ -50,7 +49,6 @@ var _ = framework.DescribeSetting("access-log", func() { }) ginkgo.Context("http-access-log-path", func() { - ginkgo.It("use the specified configuration", func() { f.UpdateNginxConfigMapData("http-access-log-path", "/tmp/nginx/http-access.log") f.WaitForNginxConfiguration( @@ -63,7 +61,6 @@ var _ = framework.DescribeSetting("access-log", func() { }) ginkgo.Context("stream-access-log-path", func() { - ginkgo.It("use the specified configuration", func() { f.UpdateNginxConfigMapData("stream-access-log-path", "/tmp/nginx/stream-access.log") f.WaitForNginxConfiguration( @@ -76,7 +73,6 @@ var _ = framework.DescribeSetting("access-log", func() { }) ginkgo.Context("http-access-log-path & stream-access-log-path", func() { - ginkgo.It("use the specified configuration", func() { f.SetNginxConfigMapData(map[string]string{ "http-access-log-path": "/tmp/nginx/http-access.log", diff --git a/test/e2e/settings/badannotationvalues.go b/test/e2e/settings/badannotationvalues.go index b4b6def4a..68a122e76 100644 --- a/test/e2e/settings/badannotationvalues.go +++ b/test/e2e/settings/badannotationvalues.go @@ -100,7 +100,6 @@ var _ = framework.DescribeAnnotation("Bad annotation values", func() { }) ginkgo.It("[BAD_ANNOTATIONS] should allow an ingress if there is a default blocklist config in place", func() { - hostValid := "custom-allowed-value-test" annotationsValid := map[string]string{ "nginx.ingress.kubernetes.io/configuration-snippet": ` @@ -159,6 +158,5 @@ var _ = framework.DescribeAnnotation("Bad annotation values", func() { WithHeader("Host", host). Expect(). Status(http.StatusNotFound) - }) }) diff --git a/test/e2e/settings/default_ssl_certificate.go b/test/e2e/settings/default_ssl_certificate.go index ea97d4895..c48a1e87f 100644 --- a/test/e2e/settings/default_ssl_certificate.go +++ b/test/e2e/settings/default_ssl_certificate.go @@ -30,10 +30,12 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const fooHost = "foo" + var _ = framework.IngressNginxDescribe("[SSL] [Flag] default-ssl-certificate", func() { f := framework.NewDefaultFramework("default-ssl-certificate") var tlsConfig *tls.Config - secretName := "my-custom-cert" + secretName := "my-custom-cert" //nolint:gosec // Ignore the gosec error in testing service := framework.EchoService port := 80 @@ -78,7 +80,7 @@ var _ = framework.IngressNginxDescribe("[SSL] [Flag] default-ssl-certificate", f }) ginkgo.It("uses default ssl certificate for host based ingress when configured certificate does not match host", func() { - host := "foo" + host := fooHost ing := f.EnsureIngress(framework.NewSingleIngressWithTLS(host, "/", host, []string{host}, f.Namespace, service, port, nil)) _, err := framework.CreateIngressTLSSecret(f.KubeClientSet, diff --git a/test/e2e/settings/disable_catch_all.go b/test/e2e/settings/disable_catch_all.go index 0d1a14493..4e7a16f4d 100644 --- a/test/e2e/settings/disable_catch_all.go +++ b/test/e2e/settings/disable_catch_all.go @@ -48,7 +48,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-catch-all", func() { }) ginkgo.It("should ignore catch all Ingress with backend", func() { - host := "foo" + host := fooHost ing := framework.NewSingleCatchAllIngress("catch-all", f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -67,7 +67,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-catch-all", func() { }) ginkgo.It("should ignore catch all Ingress with backend and rules", func() { - host := "foo" + host := fooHost ing := framework.NewSingleIngressWithBackendAndRules(host, "/", host, f.Namespace, framework.EchoService, 80, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -79,7 +79,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-catch-all", func() { }) ginkgo.It("should delete Ingress updated to catch-all", func() { - host := "foo" + host := fooHost ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -121,7 +121,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-catch-all", func() { }) ginkgo.It("should allow Ingress with rules", func() { - host := "foo" + host := fooHost ing := framework.NewSingleIngress("not-catch-all", "/", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) diff --git a/test/e2e/settings/disable_service_external_name.go b/test/e2e/settings/disable_service_external_name.go index 4ecf69e81..602828089 100644 --- a/test/e2e/settings/disable_service_external_name.go +++ b/test/e2e/settings/disable_service_external_name.go @@ -95,6 +95,5 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-service-external-name", f WithHeader("Host", externalhost). Expect(). StatusRange(httpexpect.Status5xx) - }) }) diff --git a/test/e2e/settings/disable_sync_events.go b/test/e2e/settings/disable_sync_events.go index 7d1298087..033fd9194 100644 --- a/test/e2e/settings/disable_sync_events.go +++ b/test/e2e/settings/disable_sync_events.go @@ -50,6 +50,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-sync-events", func() { assert.NotEmpty(ginkgo.GinkgoT(), events.Items, "got events") }) + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should create sync events", func() { host := "disable-sync-events-false" f.NewEchoDeployment(framework.WithDeploymentReplicas(1)) @@ -77,6 +78,7 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-sync-events", func() { assert.NotEmpty(ginkgo.GinkgoT(), events.Items, "got events") }) + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should not create sync events", func() { host := "disable-sync-events-true" f.NewEchoDeployment(framework.WithDeploymentReplicas(1)) @@ -103,5 +105,4 @@ var _ = framework.IngressNginxDescribe("[Flag] disable-sync-events", func() { assert.Empty(ginkgo.GinkgoT(), events.Items, "got events") }) - }) diff --git a/test/e2e/settings/forwarded_headers.go b/test/e2e/settings/forwarded_headers.go index d4ffee545..44460aca6 100644 --- a/test/e2e/settings/forwarded_headers.go +++ b/test/e2e/settings/forwarded_headers.go @@ -26,6 +26,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const forwardedHeadersHost = "forwarded-headers" + var _ = framework.DescribeSetting("use-forwarded-headers", func() { f := framework.NewDefaultFramework("forwarded-headers") @@ -37,7 +39,7 @@ var _ = framework.DescribeSetting("use-forwarded-headers", func() { }) ginkgo.It("should trust X-Forwarded headers when setting is true", func() { - host := "forwarded-headers" + host := forwardedHeadersHost f.UpdateNginxConfigMapData(setting, "true") @@ -89,7 +91,7 @@ var _ = framework.DescribeSetting("use-forwarded-headers", func() { }) ginkgo.It("should not trust X-Forwarded headers when setting is false", func() { - host := "forwarded-headers" + host := forwardedHeadersHost f.UpdateNginxConfigMapData(setting, "false") diff --git a/test/e2e/settings/geoip2.go b/test/e2e/settings/geoip2.go index 9b2ca8624..6dd48b2ad 100644 --- a/test/e2e/settings/geoip2.go +++ b/test/e2e/settings/geoip2.go @@ -19,11 +19,10 @@ package settings import ( "context" "fmt" + "net/http" "path/filepath" "strings" - "net/http" - "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/assert" @@ -72,8 +71,7 @@ var _ = framework.DescribeSetting("Geoip2", func() { f.UpdateNginxConfigMapData("use-geoip2", "true") - httpSnippetAllowingOnlyAustralia := - `map $geoip2_city_country_code $blocked_country { + httpSnippetAllowingOnlyAustralia := `map $geoip2_city_country_code $blocked_country { default 1; AU 0; }` @@ -85,8 +83,7 @@ var _ = framework.DescribeSetting("Geoip2", func() { return strings.Contains(cfg, "map $geoip2_city_country_code $blocked_country") }) - configSnippet := - `if ($blocked_country) { + configSnippet := `if ($blocked_country) { return 403; }` diff --git a/test/e2e/settings/global_external_auth.go b/test/e2e/settings/global_external_auth.go index cc98099ae..741e6f955 100644 --- a/test/e2e/settings/global_external_auth.go +++ b/test/e2e/settings/global_external_auth.go @@ -31,6 +31,11 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const ( + disable = "false" + noAuthLocaltionSetting = "no-auth-locations" +) + var _ = framework.DescribeSetting("[Security] global-auth-url", func() { f := framework.NewDefaultFramework( "global-external-auth", @@ -46,7 +51,7 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { fooPath := "/foo" barPath := "/bar" - noAuthSetting := "no-auth-locations" + noAuthSetting := noAuthLocaltionSetting noAuthLocations := barPath enableGlobalExternalAuthAnnotation := "nginx.ingress.kubernetes.io/enable-global-auth" @@ -56,7 +61,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.Context("when global external authentication is configured", func() { - ginkgo.BeforeEach(func() { globalExternalAuthURL := fmt.Sprintf("http://%s.%s.svc.cluster.local:80/status/401", framework.HTTPBunService, f.Namespace) @@ -85,7 +89,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It("should return status code 401 when request any protected service", func() { - ginkgo.By("Sending a request to protected service /foo") f.HTTPTestClient(). GET(fooPath). @@ -102,7 +105,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It("should return status code 200 when request whitelisted (via no-auth-locations) service and 401 when request protected service", func() { - ginkgo.By("Adding a no-auth-locations for /bar to configMap") f.UpdateNginxConfigMapData(noAuthSetting, noAuthLocations) f.WaitForNginxServer(host, @@ -126,10 +128,9 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It("should return status code 200 when request whitelisted (via ingress annotation) service and 401 when request protected service", func() { - ginkgo.By("Adding an ingress rule for /bar with annotation enable-global-auth = false") err := framework.UpdateIngress(f.KubeClientSet, f.Namespace, "bar-ingress", func(ingress *networking.Ingress) error { - ingress.ObjectMeta.Annotations[enableGlobalExternalAuthAnnotation] = "false" + ingress.ObjectMeta.Annotations[enableGlobalExternalAuthAnnotation] = disable return nil }) assert.Nil(ginkgo.GinkgoT(), err) @@ -155,9 +156,8 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It("should still return status code 200 after auth backend is deleted using cache", func() { - globalExternalAuthCacheKeySetting := "global-auth-cache-key" - globalExternalAuthCacheKey := "foo" + globalExternalAuthCacheKey := fooHost globalExternalAuthCacheDurationSetting := "global-auth-cache-duration" globalExternalAuthCacheDuration := "200 201 401 30m" globalExternalAuthURL := fmt.Sprintf("http://%s.%s.svc.cluster.local:80/status/200", framework.HTTPBunService, f.Namespace) @@ -197,7 +197,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It(`should proxy_method method when global-auth-method is configured`, func() { - globalExternalAuthMethodSetting := "global-auth-method" globalExternalAuthMethod := "GET" @@ -210,7 +209,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It(`should add custom error page when global-auth-signin url is configured`, func() { - globalExternalAuthSigninSetting := "global-auth-signin" globalExternalAuthSignin := "http://foo.com/global-error-page" @@ -223,7 +221,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It(`should add auth headers when global-auth-response-headers is configured`, func() { - globalExternalAuthResponseHeadersSetting := "global-auth-response-headers" globalExternalAuthResponseHeaders := "Foo, Bar" @@ -237,7 +234,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { }) ginkgo.It(`should set request-redirect when global-auth-request-redirect is configured`, func() { - globalExternalAuthRequestRedirectSetting := "global-auth-request-redirect" globalExternalAuthRequestRedirect := "Foo-Redirect" @@ -260,7 +256,6 @@ var _ = framework.DescribeSetting("[Security] global-auth-url", func() { return strings.Contains(server, globalExternalAuthSnippet) }) }) - }) ginkgo.Context("cookie set by external authentication server", func() { @@ -322,7 +317,6 @@ http { f.WaitForNginxServer(host, func(server string) bool { return strings.Contains(server, "server_name "+host) }) - }) ginkgo.It("user retains cookie by default", func() { diff --git a/test/e2e/settings/global_options.go b/test/e2e/settings/global_options.go index 117860d59..1f84ef5d7 100644 --- a/test/e2e/settings/global_options.go +++ b/test/e2e/settings/global_options.go @@ -31,7 +31,6 @@ var _ = framework.IngressNginxDescribe("global-options", func() { ginkgo.It("should have worker_rlimit_nofile option", func() { f.WaitForNginxConfiguration(func(server string) bool { return strings.Contains(server, fmt.Sprintf("worker_rlimit_nofile %d;", rlimitMaxNumFiles()-1024)) - }) }) diff --git a/test/e2e/settings/hash-size.go b/test/e2e/settings/hash-size.go index 6e3e0480c..5aa5f7c95 100644 --- a/test/e2e/settings/hash-size.go +++ b/test/e2e/settings/hash-size.go @@ -36,7 +36,6 @@ var _ = framework.DescribeSetting("hash size", func() { }) ginkgo.Context("Check server names hash size", func() { - ginkgo.It("should set server_names_hash_bucket_size", func() { f.UpdateNginxConfigMapData("server-name-hash-bucket-size", "512") @@ -52,11 +51,9 @@ var _ = framework.DescribeSetting("hash size", func() { return strings.Contains(server, "server_names_hash_max_size 4096;") }) }) - }) ginkgo.Context("Check proxy header hash size", func() { - ginkgo.It("should set proxy-headers-hash-bucket-size", func() { f.UpdateNginxConfigMapData("proxy-headers-hash-bucket-size", "512") @@ -72,11 +69,9 @@ var _ = framework.DescribeSetting("hash size", func() { return strings.Contains(server, "proxy_headers_hash_max_size 4096;") }) }) - }) ginkgo.Context("Check the variable hash size", func() { - ginkgo.It("should set variables-hash-bucket-size", func() { f.UpdateNginxConfigMapData("variables-hash-bucket-size", "512") @@ -92,11 +87,9 @@ var _ = framework.DescribeSetting("hash size", func() { return strings.Contains(server, "variables_hash_max_size 512;") }) }) - }) ginkgo.Context("Check the map hash size", func() { - ginkgo.It("should set vmap-hash-bucket-size", func() { f.UpdateNginxConfigMapData("map-hash-bucket-size", "512") @@ -104,7 +97,5 @@ var _ = framework.DescribeSetting("hash size", func() { return strings.Contains(server, "map_hash_bucket_size 512;") }) }) - }) - }) diff --git a/test/e2e/settings/ingress_class.go b/test/e2e/settings/ingress_class.go index 232045f3a..80c09f80c 100644 --- a/test/e2e/settings/ingress_class.go +++ b/test/e2e/settings/ingress_class.go @@ -36,6 +36,8 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const barHost = "bar" + var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { f := framework.NewDefaultFramework("ingress-class") @@ -66,7 +68,7 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { ginkgo.Context("With default ingress class config", func() { ginkgo.It("should ignore Ingress with a different class annotation", func() { - invalidHost := "foo" + invalidHost := fooHost annotations := map[string]string{ ingressclass.IngressKey: "testclass", } @@ -75,7 +77,7 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { ing.Spec.IngressClassName = nil f.EnsureIngress(ing) - validHost := "bar" + validHost := barHost annotationClass := map[string]string{ ingressclass.IngressKey: ingressclass.DefaultAnnotationValue, } @@ -385,7 +387,6 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { Expect(). Status(http.StatusOK) }) - }) ginkgo.Context("With specific ingress-class flags", func() { @@ -411,13 +412,13 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { }) ginkgo.It("should ignore Ingress with no class and accept the correctly configured Ingresses", func() { - invalidHost := "bar" + invalidHost := barHost ing := framework.NewSingleIngress(invalidHost, "/", invalidHost, f.Namespace, framework.EchoService, 80, nil) ing.Spec.IngressClassName = nil f.EnsureIngress(ing) - validHost := "foo" + validHost := fooHost annotations := map[string]string{ ingressclass.IngressKey: "testclass", } @@ -455,7 +456,6 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { Expect(). Status(http.StatusNotFound) }) - }) ginkgo.Context("With watch-ingress-without-class flag", func() { @@ -480,13 +480,13 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { }) ginkgo.It("should watch Ingress with no class and ignore ingress with a different class", func() { - validHost := "bar" + validHost := barHost ing := framework.NewSingleIngress(validHost, "/", validHost, f.Namespace, framework.EchoService, 80, nil) ing.Spec.IngressClassName = nil f.EnsureIngress(ing) - invalidHost := "foo" + invalidHost := fooHost annotations := map[string]string{ ingressclass.IngressKey: "testclass123", } @@ -511,7 +511,6 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { Expect(). Status(http.StatusNotFound) }) - }) ginkgo.Context("With ingress-class-by-name flag", func() { @@ -579,11 +578,9 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { Expect(). Status(http.StatusNotFound) }) - }) ginkgo.Context("Without IngressClass Cluster scoped Permission", func() { - ginkgo.BeforeEach(func() { icname := fmt.Sprintf("ic-%s", f.Namespace) @@ -629,8 +626,7 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { }) ginkgo.It("should watch Ingress with correct annotation", func() { - - validHost := "foo" + validHost := fooHost annotations := map[string]string{ ingressclass.IngressKey: "testclass", } @@ -650,7 +646,6 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { }) ginkgo.It("should ignore Ingress with only IngressClassName", func() { - invalidHost := "noclassforyou" ing := framework.NewSingleIngress(invalidHost, "/", invalidHost, f.Namespace, framework.EchoService, 80, nil) @@ -666,6 +661,5 @@ var _ = framework.IngressNginxDescribe("[Flag] ingress-class", func() { Expect(). Status(http.StatusNotFound) }) - }) }) diff --git a/test/e2e/settings/keep-alive.go b/test/e2e/settings/keep-alive.go index d139f61c0..167f5ac18 100644 --- a/test/e2e/settings/keep-alive.go +++ b/test/e2e/settings/keep-alive.go @@ -21,6 +21,7 @@ import ( "strings" "github.com/onsi/ginkgo/v2" + "github.com/stretchr/testify/assert" "k8s.io/ingress-nginx/test/e2e/framework" ) @@ -50,7 +51,6 @@ var _ = framework.DescribeSetting("keep-alive keep-alive-requests", func() { f.WaitForNginxConfiguration(func(server string) bool { return strings.Contains(server, `keepalive_requests 200;`) }) - }) }) @@ -59,7 +59,8 @@ var _ = framework.DescribeSetting("keep-alive keep-alive-requests", func() { f.UpdateNginxConfigMapData("upstream-keepalive-connections", "128") f.WaitForNginxConfiguration(func(server string) bool { - match, _ := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive 128;`, server) + match, err := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive 128;`, server) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error matching the upstream keepalive time") return match }) }) @@ -68,7 +69,8 @@ var _ = framework.DescribeSetting("keep-alive keep-alive-requests", func() { f.UpdateNginxConfigMapData("upstream-keepalive-timeout", "120") f.WaitForNginxConfiguration(func(server string) bool { - match, _ := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_timeout\s*120s;`, server) + match, err := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_timeout\s*120s;`, server) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error matching the upstream keepalive time") return match }) }) @@ -77,7 +79,8 @@ var _ = framework.DescribeSetting("keep-alive keep-alive-requests", func() { f.UpdateNginxConfigMapData("upstream-keepalive-time", "75s") f.WaitForNginxConfiguration(func(server string) bool { - match, _ := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_time\s*75s;`, server) + match, err := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_time\s*75s;`, server) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error matching the upstream keepalive time") return match }) }) @@ -86,7 +89,8 @@ var _ = framework.DescribeSetting("keep-alive keep-alive-requests", func() { f.UpdateNginxConfigMapData("upstream-keepalive-requests", "200") f.WaitForNginxConfiguration(func(server string) bool { - match, _ := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_requests\s*200;`, server) + match, err := regexp.MatchString(`upstream\supstream_balancer\s\{[\s\S]*keepalive_requests\s*200;`, server) + assert.Nil(ginkgo.GinkgoT(), err, "unexpected error matching the upstream keepalive time") return match }) }) diff --git a/test/e2e/settings/listen_nondefault_ports.go b/test/e2e/settings/listen_nondefault_ports.go index 7e3b11b21..9d3952227 100644 --- a/test/e2e/settings/listen_nondefault_ports.go +++ b/test/e2e/settings/listen_nondefault_ports.go @@ -28,7 +28,6 @@ import ( ) var _ = framework.IngressNginxDescribe("[Flag] custom HTTP and HTTPS ports", func() { - host := "forwarded-headers" f := framework.NewDefaultFramework("forwarded-port-headers", framework.WithHTTPBunEnabled()) @@ -44,7 +43,6 @@ var _ = framework.IngressNginxDescribe("[Flag] custom HTTP and HTTPS ports", fun ginkgo.Context("with a plain HTTP ingress", func() { ginkgo.It("should set X-Forwarded-Port headers accordingly when listening on a non-default HTTP port", func() { - ing := framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -64,9 +62,7 @@ var _ = framework.IngressNginxDescribe("[Flag] custom HTTP and HTTPS ports", fun }) ginkgo.Context("with a TLS enabled ingress", func() { - ginkgo.It("should set X-Forwarded-Port header to 443", func() { - ing := framework.NewSingleIngressWithTLS(host, "/", host, []string{host}, f.Namespace, framework.EchoService, 80, nil) f.EnsureIngress(ing) @@ -94,7 +90,6 @@ var _ = framework.IngressNginxDescribe("[Flag] custom HTTP and HTTPS ports", fun }) ginkgo.Context("when external authentication is configured", func() { - ginkgo.It("should set the X-Forwarded-Port header to 443", func() { annotations := map[string]string{ "nginx.ingress.kubernetes.io/auth-url": fmt.Sprintf("http://%s/basic-auth/user/password", f.HTTPBunIP), diff --git a/test/e2e/settings/log-format.go b/test/e2e/settings/log-format.go index 24877818d..18835cb66 100644 --- a/test/e2e/settings/log-format.go +++ b/test/e2e/settings/log-format.go @@ -36,7 +36,6 @@ var _ = framework.DescribeSetting("log-format-*", func() { }) ginkgo.Context("Check log-format-escape-json and log-format-escape-none", func() { - ginkgo.It("should not configure log-format escape by default", func() { f.WaitForNginxConfiguration( func(cfg string) bool { @@ -78,7 +77,6 @@ var _ = framework.DescribeSetting("log-format-*", func() { }) ginkgo.Context("Check log-format-upstream with log-format-escape-json and log-format-escape-none", func() { - ginkgo.It("log-format-escape-json enabled", func() { f.SetNginxConfigMapData(map[string]string{ "log-format-escape-json": "true", diff --git a/test/e2e/settings/namespace_selector.go b/test/e2e/settings/namespace_selector.go index 3bf856566..1da62ee86 100644 --- a/test/e2e/settings/namespace_selector.go +++ b/test/e2e/settings/namespace_selector.go @@ -29,12 +29,12 @@ import ( var _ = framework.IngressNginxDescribeSerial("[Flag] watch namespace selector", func() { f := framework.NewDefaultFramework("namespace-selector") - notMatchedHost, matchedHost := "bar", "foo" + notMatchedHost, matchedHost := barHost, fooHost var notMatchedNs string var matchedNs string // create a test namespace, under which create an ingress and backend deployment - prepareTestIngress := func(baseName string, host string, labels map[string]string) string { + prepareTestIngress := func(host string, labels map[string]string) string { ns, err := framework.CreateKubeNamespaceWithLabel(f.BaseName, labels, f.KubeClientSet) assert.Nil(ginkgo.GinkgoT(), err, "creating test namespace") f.NewEchoDeployment(framework.WithDeploymentNamespace(ns)) @@ -49,8 +49,8 @@ var _ = framework.IngressNginxDescribeSerial("[Flag] watch namespace selector", } ginkgo.BeforeEach(func() { - notMatchedNs = prepareTestIngress(notMatchedHost, notMatchedHost, nil) // create namespace without label "foo=bar" - matchedNs = prepareTestIngress(matchedHost, matchedHost, map[string]string{"foo": "bar"}) + notMatchedNs = prepareTestIngress(notMatchedHost, nil) // create namespace without label "foo=bar" + matchedNs = prepareTestIngress(matchedHost, map[string]string{fooHost: barHost}) }) ginkgo.AfterEach(func() { @@ -59,9 +59,7 @@ var _ = framework.IngressNginxDescribeSerial("[Flag] watch namespace selector", }) ginkgo.Context("With specific watch-namespace-selector flags", func() { - - ginkgo.It("should ingore Ingress of namespace without label foo=bar and accept those of namespace with label foo=bar", func() { - + ginkgo.It("should ignore Ingress of namespace without label foo=bar and accept those of namespace with label foo=bar", func() { f.WaitForNginxConfiguration(func(cfg string) bool { return !strings.Contains(cfg, "server_name bar") && strings.Contains(cfg, "server_name foo") @@ -86,7 +84,7 @@ var _ = framework.IngressNginxDescribeSerial("[Flag] watch namespace selector", if ns.Labels == nil { ns.Labels = make(map[string]string) } - ns.Labels["foo"] = "bar" + ns.Labels[fooHost] = barHost _, err = f.KubeClientSet.CoreV1().Namespaces().Update(context.TODO(), ns, metav1.UpdateOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "labeling not matched namespace") @@ -97,7 +95,7 @@ var _ = framework.IngressNginxDescribeSerial("[Flag] watch namespace selector", if ing.Labels == nil { ing.Labels = make(map[string]string) } - ing.Labels["foo"] = "bar" + ing.Labels[fooHost] = barHost _, err = f.KubeClientSet.NetworkingV1().Ingresses(notMatchedNs).Update(context.TODO(), ing, metav1.UpdateOptions{}) assert.Nil(ginkgo.GinkgoT(), err, "updating ingress") diff --git a/test/e2e/settings/no_auth_locations.go b/test/e2e/settings/no_auth_locations.go index 2fc4b6455..103c057d7 100644 --- a/test/e2e/settings/no_auth_locations.go +++ b/test/e2e/settings/no_auth_locations.go @@ -18,12 +18,12 @@ package settings import ( "fmt" - "golang.org/x/crypto/bcrypt" "net/http" "strings" "github.com/onsi/ginkgo/v2" "github.com/stretchr/testify/assert" + "golang.org/x/crypto/bcrypt" corev1 "k8s.io/api/core/v1" networking "k8s.io/api/networking/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -34,7 +34,7 @@ var _ = framework.DescribeSetting("[Security] no-auth-locations", func() { f := framework.NewDefaultFramework("no-auth-locations") setting := "no-auth-locations" - username := "foo" + username := fooHost password := "bar" secretName := "test-secret" host := "no-auth-locations" @@ -100,7 +100,8 @@ func buildBasicAuthIngressWithSecondPath(host, namespace, secretName, pathName s ObjectMeta: metav1.ObjectMeta{ Name: host, Namespace: namespace, - Annotations: map[string]string{"nginx.ingress.kubernetes.io/auth-type": "basic", + Annotations: map[string]string{ + "nginx.ingress.kubernetes.io/auth-type": "basic", "nginx.ingress.kubernetes.io/auth-secret": secretName, "nginx.ingress.kubernetes.io/auth-realm": "test auth", }, @@ -147,7 +148,6 @@ func buildBasicAuthIngressWithSecondPath(host, namespace, secretName, pathName s } func buildSecret(username, password, name, namespace string) *corev1.Secret { - //out, err := exec.Command("openssl", "passwd", "-crypt", password).CombinedOutput() out, err := bcrypt.GenerateFromPassword([]byte(password), 14) assert.Nil(ginkgo.GinkgoT(), err, "creating password") diff --git a/test/e2e/settings/no_tls_redirect_locations.go b/test/e2e/settings/no_tls_redirect_locations.go index 332d764d6..8339eb23e 100644 --- a/test/e2e/settings/no_tls_redirect_locations.go +++ b/test/e2e/settings/no_tls_redirect_locations.go @@ -44,6 +44,5 @@ var _ = framework.DescribeSetting("Add no tls redirect locations", func() { f.WaitForNginxConfiguration(func(server string) bool { return strings.Contains(server, "force_no_ssl_redirect = true,") }) - }) }) diff --git a/test/e2e/settings/ocsp/ocsp.go b/test/e2e/settings/ocsp/ocsp.go index 0173f41ac..0ec15db58 100644 --- a/test/e2e/settings/ocsp/ocsp.go +++ b/test/e2e/settings/ocsp/ocsp.go @@ -112,7 +112,7 @@ var _ = framework.DescribeSetting("OCSP", func() { return strings.Contains(server, fmt.Sprintf(`server_name %v`, host)) }) - tlsConfig := &tls.Config{ServerName: host, InsecureSkipVerify: true} + tlsConfig := &tls.Config{ServerName: host, InsecureSkipVerify: true} //nolint:gosec // Ignore the gosec error in testing f.HTTPTestClientWithTLSConfig(tlsConfig). GET("/"). WithURL(f.GetURL(framework.HTTPS)). @@ -195,7 +195,8 @@ const configTemplate = ` func prepareCertificates(namespace string) error { config := fmt.Sprintf(configTemplate, namespace) - err := os.WriteFile("cfssl_config.json", []byte(config), 0644) + //nolint:gosec // Not change permission to avoid possible issues + err := os.WriteFile("cfssl_config.json", []byte(config), 0o644) if err != nil { return fmt.Errorf("creating cfssl_config.json file: %v", err) } diff --git a/test/e2e/settings/opentelemetry.go b/test/e2e/settings/opentelemetry.go index 92d202cb3..15b5d165e 100644 --- a/test/e2e/settings/opentelemetry.go +++ b/test/e2e/settings/opentelemetry.go @@ -32,6 +32,8 @@ const ( opentelemetryLocationOperationName = "opentelemetry-location-operation-name" opentelemetryConfig = "opentelemetry-config" opentelemetryConfigPath = "/etc/nginx/opentelemetry.toml" + + enable = "true" ) var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { @@ -46,7 +48,7 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { ginkgo.It("should not exists opentelemetry directive", func() { config := map[string]string{} - config[enableOpentelemetry] = "false" + config[enableOpentelemetry] = disable f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentelemetry, "/", enableOpentelemetry, f.Namespace, "http-svc", 80, nil)) @@ -59,7 +61,7 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { ginkgo.It("should exists opentelemetry directive when is enabled", func() { config := map[string]string{} - config[enableOpentelemetry] = "true" + config[enableOpentelemetry] = enable config[opentelemetryConfig] = opentelemetryConfigPath f.SetNginxConfigMapData(config) @@ -73,9 +75,9 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { ginkgo.It("should include opentelemetry_trust_incoming_spans on directive when enabled", func() { config := map[string]string{} - config[enableOpentelemetry] = "true" + config[enableOpentelemetry] = enable config[opentelemetryConfig] = opentelemetryConfigPath - config[opentelemetryTrustIncomingSpan] = "true" + config[opentelemetryTrustIncomingSpan] = enable f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentelemetry, "/", enableOpentelemetry, f.Namespace, "http-svc", 80, nil)) @@ -88,7 +90,7 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { ginkgo.It("should not exists opentelemetry_operation_name directive when is empty", func() { config := map[string]string{} - config[enableOpentelemetry] = "true" + config[enableOpentelemetry] = enable config[opentelemetryConfig] = opentelemetryConfigPath config[opentelemetryOperationName] = "" f.SetNginxConfigMapData(config) @@ -103,7 +105,7 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { ginkgo.It("should exists opentelemetry_operation_name directive when is configured", func() { config := map[string]string{} - config[enableOpentelemetry] = "true" + config[enableOpentelemetry] = enable config[opentelemetryConfig] = opentelemetryConfigPath config[opentelemetryOperationName] = "HTTP $request_method $uri" f.SetNginxConfigMapData(config) @@ -115,5 +117,4 @@ var _ = framework.IngressNginxDescribe("Configure Opentelemetry", func() { return strings.Contains(cfg, `opentelemetry_operation_name "HTTP $request_method $uri"`) }) }) - }) diff --git a/test/e2e/settings/opentracing.go b/test/e2e/settings/opentracing.go index aee01ea60..76d96498d 100644 --- a/test/e2e/settings/opentracing.go +++ b/test/e2e/settings/opentracing.go @@ -41,8 +41,12 @@ const ( datadogCollectorHost = "datadog-collector-host" - opentracingOperationName = "opentracing-operation-name" + opentracingOperationName = "opentracing-operation-name" + opentracingOperationValue = "HTTP $request_method $uri" + opentracingLocationOperationName = "opentracing-location-operation-name" + + localhost = "127.0.0.1" ) var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { @@ -57,7 +61,7 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should not exists opentracing directive", func() { config := map[string]string{} - config[enableOpentracing] = "false" + config[enableOpentracing] = disable f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentracing, "/", enableOpentracing, f.Namespace, "http-svc", 80, nil)) @@ -70,8 +74,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should exists opentracing directive when is enabled", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentracing, "/", enableOpentracing, f.Namespace, "http-svc", 80, nil)) @@ -84,9 +88,9 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should include opentracing_trust_incoming_span off directive when disabled", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[opentracingTrustIncomingSpan] = "false" - config[zipkinCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[opentracingTrustIncomingSpan] = disable + config[zipkinCollectorHost] = localhost f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentracing, "/", enableOpentracing, f.Namespace, "http-svc", 80, nil)) @@ -99,8 +103,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should not exists opentracing_operation_name directive when is empty", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost config[opentracingOperationName] = "" f.SetNginxConfigMapData(config) @@ -114,9 +118,9 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should exists opentracing_operation_name directive when is configured", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" - config[opentracingOperationName] = "HTTP $request_method $uri" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost + config[opentracingOperationName] = opentracingOperationValue f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentracing, "/", enableOpentracing, f.Namespace, "http-svc", 80, nil)) @@ -129,8 +133,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should not exists opentracing_location_operation_name directive when is empty", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost config[opentracingLocationOperationName] = "" f.SetNginxConfigMapData(config) @@ -144,9 +148,9 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should exists opentracing_location_operation_name directive when is configured", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" - config[opentracingLocationOperationName] = "HTTP $request_method $uri" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost + config[opentracingLocationOperationName] = opentracingOperationValue f.SetNginxConfigMapData(config) f.EnsureIngress(framework.NewSingleIngress(enableOpentracing, "/", enableOpentracing, f.Namespace, "http-svc", 80, nil)) @@ -159,8 +163,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should enable opentracing using zipkin", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[zipkinCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[zipkinCollectorHost] = localhost f.SetNginxConfigMapData(config) framework.Sleep(10 * time.Second) @@ -171,8 +175,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should enable opentracing using jaeger", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[jaegerCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[jaegerCollectorHost] = localhost f.SetNginxConfigMapData(config) framework.Sleep(10 * time.Second) @@ -183,9 +187,9 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should enable opentracing using jaeger with sampler host", func() { config := map[string]string{} - config[enableOpentracing] = "true" - config[jaegerCollectorHost] = "127.0.0.1" - config[jaegerSamplerHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[jaegerCollectorHost] = localhost + config[jaegerSamplerHost] = localhost f.SetNginxConfigMapData(config) framework.Sleep(10 * time.Second) @@ -197,8 +201,8 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should propagate the w3c header when configured with jaeger", func() { host := "jaeger-w3c" config := map[string]string{} - config[enableOpentracing] = "true" - config[jaegerCollectorHost] = "127.0.0.1" + config[enableOpentracing] = enable + config[jaegerCollectorHost] = localhost config[jaegerPropagationFormat] = "w3c" f.SetNginxConfigMapData(config) @@ -227,7 +231,7 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { /* ginkgo.It("should enable opentracing using jaeger with an HTTP endpoint", func() { config := map[string]string{} - config[enableOpentracing] = "true" + config[enableOpentracing] = TRUE config[jaegerEndpoint] = "http://127.0.0.1/api/traces" f.SetNginxConfigMapData(config) @@ -240,7 +244,7 @@ var _ = framework.IngressNginxDescribe("Configure OpenTracing", func() { ginkgo.It("should enable opentracing using datadog", func() { config := map[string]string{} - config[enableOpentracing] = "true" + config[enableOpentracing] = enable config[datadogCollectorHost] = "http://127.0.0.1" f.SetNginxConfigMapData(config) diff --git a/test/e2e/settings/pod_security_policy_volumes.go b/test/e2e/settings/pod_security_policy_volumes.go index dd4df3bd9..f8fc58300 100644 --- a/test/e2e/settings/pod_security_policy_volumes.go +++ b/test/e2e/settings/pod_security_policy_volumes.go @@ -38,7 +38,6 @@ var _ = framework.IngressNginxDescribe("[Security] Pod Security Policies with vo f := framework.NewDefaultFramework("pod-security-policies-volumes") ginkgo.It("should be running with a Pod Security Policy", func() { - k8sversion, err := f.KubeClientSet.Discovery().ServerVersion() if err != nil { assert.Nil(ginkgo.GinkgoT(), err, "getting version") diff --git a/test/e2e/settings/proxy_connect_timeout.go b/test/e2e/settings/proxy_connect_timeout.go index 1290775a5..185ac1dd1 100644 --- a/test/e2e/settings/proxy_connect_timeout.go +++ b/test/e2e/settings/proxy_connect_timeout.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:dupl // Ignore dupl errors for similar test case package settings import ( @@ -64,5 +65,4 @@ var _ = framework.DescribeSetting("proxy-connect-timeout", func() { return !strings.Contains(server, fmt.Sprintf("proxy_connect_timeout %ss;", proxyConnectTimeout)) }) }) - }) diff --git a/test/e2e/settings/proxy_protocol.go b/test/e2e/settings/proxy_protocol.go index 9939cad9e..cfce68bf8 100644 --- a/test/e2e/settings/proxy_protocol.go +++ b/test/e2e/settings/proxy_protocol.go @@ -33,8 +33,10 @@ import ( "k8s.io/ingress-nginx/test/e2e/framework" ) +const proxyProtocol = "proxy-protocol" + var _ = framework.DescribeSetting("use-proxy-protocol", func() { - f := framework.NewDefaultFramework("proxy-protocol") + f := framework.NewDefaultFramework(proxyProtocol) setting := "use-proxy-protocol" @@ -42,9 +44,9 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { f.NewEchoDeployment() f.UpdateNginxConfigMapData(setting, "false") }) - + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should respect port passed by the PROXY Protocol", func() { - host := "proxy-protocol" + host := proxyProtocol f.UpdateNginxConfigMapData(setting, "true") @@ -73,14 +75,15 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") body := string(data) - assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", "proxy-protocol")) + assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", proxyProtocol)) assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-port=1234") assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-proto=http") assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-for=192.168.0.1") }) + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should respect proto passed by the PROXY Protocol server port", func() { - host := "proxy-protocol" + host := proxyProtocol f.UpdateNginxConfigMapData(setting, "true") @@ -109,14 +112,14 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") body := string(data) - assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", "proxy-protocol")) + assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", proxyProtocol)) assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-port=443") assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-proto=https") assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-for=192.168.0.1") }) ginkgo.It("should enable PROXY Protocol for HTTPS", func() { - host := "proxy-protocol" + host := proxyProtocol f.UpdateNginxConfigMapData(setting, "true") @@ -151,7 +154,7 @@ var _ = framework.DescribeSetting("use-proxy-protocol", func() { assert.Nil(ginkgo.GinkgoT(), err, "unexpected error reading connection data") body := string(data) - assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", "proxy-protocol")) + assert.Contains(ginkgo.GinkgoT(), body, fmt.Sprintf("host=%v", proxyProtocol)) assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-port=1234") assert.Contains(ginkgo.GinkgoT(), body, "x-forwarded-proto=https") assert.Contains(ginkgo.GinkgoT(), body, "x-scheme=https") diff --git a/test/e2e/settings/proxy_read_timeout.go b/test/e2e/settings/proxy_read_timeout.go index c84956cc9..484b44f24 100644 --- a/test/e2e/settings/proxy_read_timeout.go +++ b/test/e2e/settings/proxy_read_timeout.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:dupl // Ignore dupl errors for similar test case package settings import ( @@ -64,5 +65,4 @@ var _ = framework.DescribeSetting("proxy-read-timeout", func() { return !strings.Contains(server, fmt.Sprintf("proxy_read_timeout %ss;", proxyReadtimeout)) }) }) - }) diff --git a/test/e2e/settings/proxy_send_timeout.go b/test/e2e/settings/proxy_send_timeout.go index 886642bc0..bdcd46f0f 100644 --- a/test/e2e/settings/proxy_send_timeout.go +++ b/test/e2e/settings/proxy_send_timeout.go @@ -14,6 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ +//nolint:dupl // Ignore dupl errors for similar test case package settings import ( @@ -64,5 +65,4 @@ var _ = framework.DescribeSetting("proxy-send-timeout", func() { return !strings.Contains(server, fmt.Sprintf("proxy_send_timeout %ss;", proxySendTimeout)) }) }) - }) diff --git a/test/e2e/settings/ssl_passthrough.go b/test/e2e/settings/ssl_passthrough.go index f0859f878..b10511bde 100644 --- a/test/e2e/settings/ssl_passthrough.go +++ b/test/e2e/settings/ssl_passthrough.go @@ -19,7 +19,7 @@ package settings import ( "context" "crypto/tls" - "fmt" + "net" "net/http" "strings" @@ -54,7 +54,6 @@ var _ = framework.IngressNginxDescribe("[Flag] enable-ssl-passthrough", func() { ginkgo.Describe("With enable-ssl-passthrough enabled", func() { ginkgo.It("should enable ssl-passthrough-proxy-port on a different port", func() { - err := f.UpdateIngressControllerDeployment(func(deployment *appsv1.Deployment) error { args := deployment.Spec.Template.Spec.Containers[0].Args args = append(args, "--ssl-passthrough-proxy-port=1442") @@ -77,7 +76,6 @@ var _ = framework.IngressNginxDescribe("[Flag] enable-ssl-passthrough", func() { }) ginkgo.It("should pass unknown traffic to default backend and handle known traffic", func() { - host := "testpassthrough.com" echoName := "echopass" @@ -170,20 +168,21 @@ var _ = framework.IngressNginxDescribe("[Flag] enable-ssl-passthrough", func() { return strings.Contains(server, "listen 442") }) + //nolint:gosec // Ignore the gosec error in testing f.HTTPTestClientWithTLSConfig(&tls.Config{ServerName: host, InsecureSkipVerify: true}). GET("/"). - WithURL(fmt.Sprintf("https://%s:443", host)). + WithURL("https://"+net.JoinHostPort(host, "443")). ForceResolve(f.GetNginxIP(), 443). Expect(). Status(http.StatusOK) + //nolint:gosec // Ignore the gosec error in testing f.HTTPTestClientWithTLSConfig(&tls.Config{ServerName: hostBad, InsecureSkipVerify: true}). GET("/"). - WithURL(fmt.Sprintf("https://%s:443", hostBad)). + WithURL("https://"+net.JoinHostPort(hostBad, "443")). ForceResolve(f.GetNginxIP(), 443). Expect(). Status(http.StatusNotFound) - }) }) }) diff --git a/test/e2e/settings/tls.go b/test/e2e/settings/tls.go index 2cead4a94..51f760df8 100644 --- a/test/e2e/settings/tls.go +++ b/test/e2e/settings/tls.go @@ -87,9 +87,7 @@ var _ = framework.DescribeSetting("[SSL] TLS protocols, ciphers and headers)", f }) ginkgo.Context("should configure HSTS policy header", func() { - var ( - tlsConfig *tls.Config - ) + var tlsConfig *tls.Config const ( hstsMaxAge = "hsts-max-age" @@ -182,7 +180,6 @@ var _ = framework.DescribeSetting("[SSL] TLS protocols, ciphers and headers)", f got := header["Strict-Transport-Security"] assert.Equal(ginkgo.GinkgoT(), 1, len(got)) }) - }) ginkgo.Context("ports or X-Forwarded-Host check during HTTP tp HTTPS redirection", func() { diff --git a/test/e2e/settings/validations/validations.go b/test/e2e/settings/validations/validations.go index 6f1715ada..19488d247 100644 --- a/test/e2e/settings/validations/validations.go +++ b/test/e2e/settings/validations/validations.go @@ -29,7 +29,7 @@ import ( var _ = framework.IngressNginxDescribeSerial("annotation validations", func() { f := framework.NewDefaultFramework("validations") - + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should allow ingress based on their risk on webhooks", func() { host := "annotation-validations" @@ -54,9 +54,8 @@ var _ = framework.IngressNginxDescribeSerial("annotation validations", func() { ing = framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) _, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Update(context.TODO(), ing, metav1.UpdateOptions{}) assert.NotNil(ginkgo.GinkgoT(), err, "creating ingress with risky annotations should trigger an error") - }) - + //nolint:dupl // Ignore dupl errors for similar test case ginkgo.It("should allow ingress based on their risk on webhooks", func() { host := "annotation-validations" @@ -81,6 +80,5 @@ var _ = framework.IngressNginxDescribeSerial("annotation validations", func() { ing = framework.NewSingleIngress(host, "/", host, f.Namespace, framework.EchoService, 80, annotations) _, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Update(context.TODO(), ing, metav1.UpdateOptions{}) assert.NotNil(ginkgo.GinkgoT(), err, "creating ingress with risky annotations should trigger an error") - }) }) diff --git a/test/e2e/ssl/secret_update.go b/test/e2e/ssl/secret_update.go index fe7bfca0c..8e81f09f9 100644 --- a/test/e2e/ssl/secret_update.go +++ b/test/e2e/ssl/secret_update.go @@ -98,7 +98,7 @@ var _ = framework.IngressNginxDescribe("[SSL] secret update", func() { return strings.Contains(server, "server_name invalid-ssl") && strings.Contains(server, "listen 443") }) - + //nolint:gosec // Ignore certificate validation in testing resp := f.HTTPTestClientWithTLSConfig(&tls.Config{ServerName: host, InsecureSkipVerify: true}). GET("/"). WithURL(f.GetURL(framework.HTTPS)). diff --git a/test/e2e/status/update.go b/test/e2e/status/update.go index 046752d2b..c3c48f8d2 100644 --- a/test/e2e/status/update.go +++ b/test/e2e/status/update.go @@ -108,6 +108,7 @@ var _ = framework.IngressNginxDescribe("[Status] status update", func() { } }() + //nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated err = wait.Poll(5*time.Second, 4*time.Minute, func() (done bool, err error) { ing, err = f.KubeClientSet.NetworkingV1().Ingresses(f.Namespace).Get(context.TODO(), host, metav1.GetOptions{}) if err != nil { @@ -134,7 +135,8 @@ func getHostIP() net.IP { } defer conn.Close() - localAddr := conn.LocalAddr().(*net.UDPAddr) + localAddr, ok := conn.LocalAddr().(*net.UDPAddr) + assert.True(ginkgo.GinkgoT(), ok, "unexpected type: %T", conn.LocalAddr()) return localAddr.IP } diff --git a/test/e2e/tcpudp/tcp.go b/test/e2e/tcpudp/tcp.go index 16a633b63..f06d6c9a3 100644 --- a/test/e2e/tcpudp/tcp.go +++ b/test/e2e/tcpudp/tcp.go @@ -148,18 +148,18 @@ var _ = framework.IngressNginxDescribe("[TCP] tcp-services", func() { } var ips []string - var retryErr error + var errRetry error err = wait.ExponentialBackoff(retry, func() (bool, error) { - ips, retryErr = resolver.LookupHost(context.Background(), "google-public-dns-b.google.com") - if retryErr == nil { + ips, errRetry = resolver.LookupHost(context.Background(), "google-public-dns-b.google.com") + if errRetry == nil { return true, nil } return false, nil }) - + //nolint:staticcheck // TODO: will replace it since wait.ErrWaitTimeout is deprecated if err == wait.ErrWaitTimeout { - err = retryErr + err = errRetry } assert.Nil(ginkgo.GinkgoT(), err, "unexpected error from DNS resolver") @@ -167,7 +167,6 @@ var _ = framework.IngressNginxDescribe("[TCP] tcp-services", func() { }) ginkgo.It("should reload after an update in the configuration", func() { - ginkgo.By("setting up a first deployment") f.NewEchoDeployment(framework.WithDeploymentName("first-service")) @@ -217,5 +216,4 @@ var _ = framework.IngressNginxDescribe("[TCP] tcp-services", func() { assert.Nil(ginkgo.GinkgoT(), err, "obtaining nginx logs") assert.Contains(ginkgo.GinkgoT(), logs, "Backend successfully reloaded") }) - }) From a687343fedbb26c3e2cef0608a975d6bfe31a0f7 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 31 Aug 2023 00:52:48 -0700 Subject: [PATCH 47/47] Bump docker/setup-buildx-action from 2.9.1 to 2.10.0 (#10353) Bumps [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) from 2.9.1 to 2.10.0. - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/4c0219f9ac95b02789c1075625400b2acbff50b1...885d1462b80bc1c1c7f0b00334ad271f09369c55) --- updated-dependencies: - dependency-name: docker/setup-buildx-action dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 596ef0427..a5dd136ae 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -158,7 +158,7 @@ jobs: - name: Set up Docker Buildx id: buildx - uses: docker/setup-buildx-action@4c0219f9ac95b02789c1075625400b2acbff50b1 # v2.9.1 + uses: docker/setup-buildx-action@885d1462b80bc1c1c7f0b00334ad271f09369c55 # v2.10.0 with: version: latest