From 1c30bad35c9f858acb013b8a839ef1b63d96ddc1 Mon Sep 17 00:00:00 2001 From: Kenjiro Nakayama Date: Thu, 16 Jun 2022 15:57:12 +0900 Subject: [PATCH 1/2] [RELEASE-1.4] Use internal-encryption to deploy internal certificates automatically --- .github/workflows/kind-e2e-upgrade.yaml | 2 +- go.mod | 12 +- go.sum | 29 +- pkg/config/config.go | 13 + pkg/generator/caches_test.go | 3 +- pkg/generator/ingress_translator.go | 21 +- pkg/generator/ingress_translator_test.go | 15 +- pkg/reconciler/ingress/config/store.go | 8 +- test/config/tls/config-network.yaml | 3 +- test/generate-upstream-cert.sh | 6 +- .../forked/golang/{net => }/LICENSE | 0 .../control-protocol/pkg/certificates/LICENSE | 201 ++++++++ .../github.com/imdario/mergo/.deepsource.toml | 12 + vendor/github.com/imdario/mergo/.travis.yml | 2 + vendor/github.com/imdario/mergo/README.md | 18 +- vendor/github.com/imdario/mergo/map.go | 8 +- vendor/github.com/imdario/mergo/merge.go | 261 ++++++---- .../forked/golang/golang-lru/lru.go | 133 +++++ vendor/k8s.io/utils/lru/lru.go | 79 +++ vendor/knative.dev/control-protocol/LICENSE | 201 ++++++++ .../pkg/certificates/certs.go | 221 +++++++++ .../pkg/certificates/constants.go | 26 + .../pkg/certificates/key_pair.go | 60 +++ .../networking/config/config-network.yaml | 52 +- .../pkg/apis/networking/register.go | 9 + .../pkg/{network.go => config/config.go} | 454 +++++------------- .../networking/pkg/{ => config}/doc.go | 4 +- .../pkg/{ => config}/zz_generated.deepcopy.go | 2 +- .../networking/pkg/deprecated_config.go | 213 ++++++++ .../networking/pkg/deprecated_header.go | 167 +++++++ .../networking/pkg/deprecated_http.go | 116 +++++ .../networking/pkg/deprecated_labels.go | 29 ++ .../networking/pkg/deprecated_port.go | 29 ++ .../networking/pkg/http/constants.go | 23 + .../knative.dev/networking/pkg/http/error.go | 29 ++ .../networking/pkg/http/header/header.go | 157 ++++++ .../probe/handler.go} | 23 +- .../pkg/{ => http/proxy}/bufferpool.go | 4 +- .../networking/pkg/http/proxy/constants.go | 28 ++ .../pkg/{stats.go => http/stats/request.go} | 7 +- .../networking/pkg/ingress/ingress.go | 6 +- .../knative.dev/networking/pkg/k8s/ports.go | 43 ++ .../networking/pkg/status/status.go | 15 +- .../test/conformance/ingress/headers.go | 16 +- .../test/conformance/ingress/util.go | 3 +- .../knative.dev/networking/test/e2e_flags.go | 6 +- .../test/test_images/grpc-ping/main.go | 4 +- .../test/test_images/httpproxy/httpproxy.go | 4 +- .../networking/test/test_images/retry/main.go | 4 +- .../test_images/runtime/handlers/handler.go | 8 +- .../test/test_images/timeout/timeout.go | 4 +- .../test/test_images/wsserver/echo.go | 7 +- vendor/modules.txt | 22 +- 53 files changed, 2250 insertions(+), 572 deletions(-) rename third_party/VENDOR-LICENSE/k8s.io/utils/internal/third_party/forked/golang/{net => }/LICENSE (100%) create mode 100644 third_party/VENDOR-LICENSE/knative.dev/control-protocol/pkg/certificates/LICENSE create mode 100644 vendor/github.com/imdario/mergo/.deepsource.toml create mode 100644 vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go create mode 100644 vendor/k8s.io/utils/lru/lru.go create mode 100644 vendor/knative.dev/control-protocol/LICENSE create mode 100644 vendor/knative.dev/control-protocol/pkg/certificates/certs.go create mode 100644 vendor/knative.dev/control-protocol/pkg/certificates/constants.go create mode 100644 vendor/knative.dev/control-protocol/pkg/certificates/key_pair.go rename vendor/knative.dev/networking/pkg/{network.go => config/config.go} (59%) rename vendor/knative.dev/networking/pkg/{ => config}/doc.go (93%) rename vendor/knative.dev/networking/pkg/{ => config}/zz_generated.deepcopy.go (99%) create mode 100644 vendor/knative.dev/networking/pkg/deprecated_config.go create mode 100644 vendor/knative.dev/networking/pkg/deprecated_header.go create mode 100644 vendor/knative.dev/networking/pkg/deprecated_http.go create mode 100644 vendor/knative.dev/networking/pkg/deprecated_labels.go create mode 100644 vendor/knative.dev/networking/pkg/deprecated_port.go create mode 100644 vendor/knative.dev/networking/pkg/http/constants.go create mode 100644 vendor/knative.dev/networking/pkg/http/error.go create mode 100644 vendor/knative.dev/networking/pkg/http/header/header.go rename vendor/knative.dev/networking/pkg/{probe_handler.go => http/probe/handler.go} (63%) rename vendor/knative.dev/networking/pkg/{ => http/proxy}/bufferpool.go (96%) create mode 100644 vendor/knative.dev/networking/pkg/http/proxy/constants.go rename vendor/knative.dev/networking/pkg/{stats.go => http/stats/request.go} (97%) create mode 100644 vendor/knative.dev/networking/pkg/k8s/ports.go diff --git a/.github/workflows/kind-e2e-upgrade.yaml b/.github/workflows/kind-e2e-upgrade.yaml index 4ba632dd0..d0fa94ef4 100644 --- a/.github/workflows/kind-e2e-upgrade.yaml +++ b/.github/workflows/kind-e2e-upgrade.yaml @@ -25,7 +25,7 @@ jobs: upstream-traffic: - plain - # TODO: Enable tls after 1.14 release. + # TODO: Enable tls after 1.16 release. # - tls # Map between K8s and KinD versions. diff --git a/go.mod b/go.mod index 50e592fd6..cccf644b1 100644 --- a/go.mod +++ b/go.mod @@ -19,7 +19,13 @@ require ( k8s.io/apimachinery v0.23.5 k8s.io/client-go v0.23.5 k8s.io/code-generator v0.23.5 - knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c - knative.dev/networking v0.0.0-20220412163509-1145ec58c8be - knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 + knative.dev/control-protocol v0.0.0-20220610133426-4a1c8e84039f + knative.dev/hack v0.0.0-20220610014127-dc6c287516dc + knative.dev/networking v0.0.0-20220614203516-07c9d7614c61 + knative.dev/pkg v0.0.0-20220610014025-7d607d643ee2 +) + +replace ( + knative.dev/hack => knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c + knative.dev/pkg => knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 ) diff --git a/go.sum b/go.sum index b39a10aca..5f75abbb4 100644 --- a/go.sum +++ b/go.sum @@ -83,6 +83,7 @@ github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk5 github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/antlr/antlr4/runtime/Go/antlr v0.0.0-20210826220005-b48c857c3a0e/go.mod h1:F7bn7fEU90QkQ3tnmaTx3LTKLEDqnwWODIYppRQ5hnY= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/asaskevich/govalidator v0.0.0-20190424111038-f61b66f89f4a/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= @@ -117,6 +118,8 @@ github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWR github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudevents/conformance v0.2.0/go.mod h1:rHKDwylBH89Rns6U3wL9ww8bg9/4GbwRCDNuyoC6bcc= +github.com/cloudevents/sdk-go/v2 v2.4.1/go.mod h1:MZiMwmAh5tGj+fPFvtHv9hKurKqXtdB9haJYMJ/7GJY= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= @@ -131,12 +134,16 @@ github.com/cockroachdb/datadriven v0.0.0-20200714090401-bf6692d28da5/go.mod h1:h github.com/cockroachdb/errors v1.2.4/go.mod h1:rQD95gz6FARkaKkQXUksEje/d9a6wBJoCr5oaCLELYA= github.com/cockroachdb/logtags v0.0.0-20190617123548-eb05cc24525f/go.mod h1:i/u985jwjWRlyHXQbwatDASoW0RMlZ/3i9yJHE2xLkI= github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= github.com/coreos/go-oidc v2.1.0+incompatible/go.mod h1:CgnwVTmzoESiwO9qyAFEMiHoZ1nMCKZlZ9V6mm3/LKc= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= @@ -319,6 +326,7 @@ github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= 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/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= @@ -371,8 +379,9 @@ github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/J github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/imdario/mergo v0.3.9 h1:UauaLniWCFHWd+Jp9oCEkTBj8VO/9DKg3PV3VCNMDIg= +github.com/imdario/mergo v0.3.9/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/influxdata/tdigest v0.0.0-20180711151920-a7d76c6f093a/go.mod h1:9GkyshztGufsdPQWjH+ifgnIr3xNUL5syI70g2dzU1o= github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs= @@ -417,6 +426,7 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lyft/protoc-gen-validate v0.0.13/go.mod h1:XbGvPuh87YZc5TdIa2/I4pLk0QoUACkjt2znoq26NVQ= +github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60= github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc= @@ -535,6 +545,7 @@ github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6L github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417 h1:Lt9DzQALzHoDwMBGJ6v8ObDPR0dzr2a6sXTB1Fq7IHs= github.com/rs/dnscache v0.0.0-20211102005908-e0241e321417/go.mod h1:qe5TWALJ8/a1Lqznoc5BDHpYX/8HU60Hm2AwRmqzxqA= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= @@ -554,6 +565,7 @@ github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTd github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo= github.com/spf13/cobra v1.2.1/go.mod h1:ExllRjgxM/piMAM+3tAZvg8fsklGAf3tPfi+i8t68Nk= github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= @@ -561,6 +573,7 @@ github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0 github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg= github.com/spf13/viper v1.8.1/go.mod h1:o0Pch8wJ9BVSWGQMbra6iw0oQ5oktSIBaujf1rJH9Ns= github.com/stoewer/go-strcase v1.2.0/go.mod h1:IBiWB2sKIp3wVVQ3Y035++gc+knqhUQag1KpM8ahLw8= @@ -580,11 +593,14 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1 github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tsenart/go-tsz v0.0.0-20180814232043-cdeb9e1e981e/go.mod h1:SWZznP1z5Ki7hDT2ioqiFKEse8K9tU2OUvaRI0NeGQo= github.com/tsenart/vegeta/v12 v12.8.4/go.mod h1:ZiJtwLn/9M4fTPdMY7bdbIeyNeFVE8/AHbWFqCsUuho= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/urfave/cli/v2 v2.3.0/go.mod h1:LJmUH05zAU44vOAcrfzZQKsZbVcdbOG8rtL3/XcUArI= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= github.com/xdg-go/scram v1.0.2/go.mod h1:1WAq6h33pAW+iRreB34OORO2Nf7qel3VV3fjBj+hCSs= github.com/xdg-go/stringprep v1.0.2/go.mod h1:8F9zXuvzgwmyT5DUm4GUfZGDdT3W+LCvS6+da4O5kxM= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -640,6 +656,7 @@ go.uber.org/zap v1.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI= go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= @@ -782,6 +799,7 @@ golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5h golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -1155,6 +1173,8 @@ k8s.io/component-base v0.23.4/go.mod h1:8o3Gg8i2vnUXGPOwciiYlkSaZT+p+7gA9Scoz8y4 k8s.io/gengo v0.0.0-20210813121822-485abfe95c7c/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= k8s.io/gengo v0.0.0-20220307231824-4627b89bbf1b h1:vEhKDJESYfeRiaBNmRvO+/12RAo1cFeu6vGm1fBFY34= k8s.io/gengo v0.0.0-20220307231824-4627b89bbf1b/go.mod h1:FiNAH4ZV3gBg2Kwh89tzAEV2be7d5xI0vBa/VySYy3E= +k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= +k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= k8s.io/klog/v2 v2.30.0/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0= @@ -1166,12 +1186,15 @@ k8s.io/utils v0.0.0-20210802155522-efc7438f0176/go.mod h1:jPW/WVKK9YHAvNhRxK0md/ k8s.io/utils v0.0.0-20211116205334-6203023598ed/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9 h1:HNSDgDCrr/6Ly3WEGKZftiE7IY19Vz2GdbOCyI4qqhc= k8s.io/utils v0.0.0-20220210201930-3a6ce19ff2f9/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= +knative.dev/control-protocol v0.0.0-20220610133426-4a1c8e84039f h1:vdhs0WWGojtUldsM/ijbOfYY2LTO3GlulilCgeZX4Js= +knative.dev/control-protocol v0.0.0-20220610133426-4a1c8e84039f/go.mod h1:MjnhSes1u2GIoqwQia5bSe3Ny8r+d5//UB+Y/en2ZL8= knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c h1:aXsFXeky/GccNQxwf72CS4NR3EoqTqsCVNKQnblfwr0= knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c/go.mod h1:PHt8x8yX5Z9pPquBEfIj0X66f8iWkWfR0S/sarACJrI= -knative.dev/networking v0.0.0-20220412163509-1145ec58c8be h1:MmwR4SfwlXgt/jnjronkTTOKBrwN1mP/VNhHH08pIoc= -knative.dev/networking v0.0.0-20220412163509-1145ec58c8be/go.mod h1:6OZIUimxPelIIudzHWRd+Lc7ippC5t+DC8CsZKCOjcI= +knative.dev/networking v0.0.0-20220614203516-07c9d7614c61 h1:IsEfLWjHFt10XEUnAE/W4XcEU2uA+PMd1aZFkz5vrzA= +knative.dev/networking v0.0.0-20220614203516-07c9d7614c61/go.mod h1:oIETD09Q4GSOXjdBdiPc0eEQxMwmjH7/gdhfg+sgdW8= knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 h1:4AmaxeY7+r/PYYz3HS9pMY21Mw3ykO6STLFEk2FoJ2s= knative.dev/pkg v0.0.0-20220412134708-e325df66cb51/go.mod h1:j2MeD8s+JoCu1vegX80GbRXV/xd20Jm1NznxBYtVXiM= +knative.dev/reconciler-test v0.0.0-20220610014025-b62b10257cbf/go.mod h1:/ps2aEdmtjId+pUGJuuADQN4IucIp4rI7KnrYEahOgE= pgregory.net/rapid v0.3.3/go.mod h1:UYpPVyjFHzYBGHIxLFoupi8vwk6rXNzRY9OMvVxFIOU= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= diff --git a/pkg/config/config.go b/pkg/config/config.go index b9cd8a0f5..b47bfb1a8 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -63,6 +63,10 @@ const ( // disableHTTP2AnnotationKey is the annotation key attached to a Knative Domain Mapping // to indicate that http2 should not be enabled for it. disableHTTP2AnnotationKey = "kourier.knative.dev/disable-http2" + + // ServingNamespaceEnv is an env variable specifying where the serving is deployed. + // e.g. OpenShift deploys Kourier in different namespace so `system.Namespace()` does not work. + ServingNamespaceEnv = "SERVING_NAMESPACE" ) var disableHTTP2Annotation = kmap.KeyPriority{ @@ -86,6 +90,15 @@ func GatewayNamespace() string { return namespace } +// ServingNamespace returns the namespace where the serving is deployed. +func ServingNamespace() string { + namespace := os.Getenv(ServingNamespaceEnv) + if namespace == "" { + return system.Namespace() + } + return namespace +} + // GetDisableHTTP2 specifies whether http2 is going to be disabled func GetDisableHTTP2(annotations map[string]string) (val string) { return disableHTTP2Annotation.Value(annotations) diff --git a/pkg/generator/caches_test.go b/pkg/generator/caches_test.go index 43b5427d9..31a5a713e 100644 --- a/pkg/generator/caches_test.go +++ b/pkg/generator/caches_test.go @@ -32,6 +32,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/fake" + "knative.dev/control-protocol/pkg/certificates" "knative.dev/net-kourier/pkg/config" envoy "knative.dev/net-kourier/pkg/envoy/api" rconfig "knative.dev/net-kourier/pkg/reconciler/ingress/config" @@ -267,7 +268,7 @@ func TestTLSListenerWithInternalCertSecret(t *testing.T) { Name: "test-ca", }, Data: map[string][]byte{ - caDataName: cert, + certificates.SecretCaCertKey: cert, }, } diff --git a/pkg/generator/ingress_translator.go b/pkg/generator/ingress_translator.go index 730d04fc0..4e1c0c0e4 100644 --- a/pkg/generator/ingress_translator.go +++ b/pkg/generator/ingress_translator.go @@ -34,20 +34,17 @@ import ( corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/types" + "knative.dev/control-protocol/pkg/certificates" pkgconfig "knative.dev/net-kourier/pkg/config" envoy "knative.dev/net-kourier/pkg/envoy/api" "knative.dev/net-kourier/pkg/reconciler/ingress/config" "knative.dev/networking/pkg/apis/networking/v1alpha1" + netconfig "knative.dev/networking/pkg/config" "knative.dev/pkg/kmeta" "knative.dev/pkg/logging" - "knative.dev/pkg/system" "knative.dev/pkg/tracker" ) -const ( - caDataName = "ca.crt" -) - type translatedIngress struct { name types.NamespacedName sniMatches []*envoy.SNIMatch @@ -197,9 +194,9 @@ func (translator *IngressTranslator) translateIngress(ctx context.Context, ingre cfg := config.FromContextOrDefaults(ctx) // As Ingress with RewriteHost points to ExternalService(kourier-internal), we don't enable TLS. - if activatorCA := cfg.Network.ActivatorCA; activatorCA != "" && httpPath.RewriteHost == "" { + if cfg.Network.InternalEncryption && httpPath.RewriteHost == "" { var err error - transportSocket, err = translator.createUpstreamTransportSocket(activatorCA, config.FromContext(ctx).Network.ActivatorSAN, http2) + transportSocket, err = translator.createUpstreamTransportSocket(http2) if err != nil { return nil, err } @@ -276,8 +273,8 @@ func (translator *IngressTranslator) translateIngress(ctx context.Context, ingre }, nil } -func (translator *IngressTranslator) createUpstreamTransportSocket(activatorCA, activatorSAN string, http2 bool) (*envoycorev3.TransportSocket, error) { - caSecret, err := translator.secretGetter(system.Namespace(), activatorCA) +func (translator *IngressTranslator) createUpstreamTransportSocket(http2 bool) (*envoycorev3.TransportSocket, error) { + caSecret, err := translator.secretGetter(pkgconfig.ServingNamespace(), netconfig.ServingInternalCertName) if err != nil { return nil, fmt.Errorf("failed to fetch activator CA secret: %w", err) } @@ -285,7 +282,7 @@ func (translator *IngressTranslator) createUpstreamTransportSocket(activatorCA, if http2 { alpnProtocols = "h2" } - tlsAny, err := anypb.New(createUpstreamTLSContext(caSecret.Data[caDataName], activatorSAN, alpnProtocols)) + tlsAny, err := anypb.New(createUpstreamTLSContext(caSecret.Data[certificates.SecretCaCertKey], alpnProtocols)) if err != nil { return nil, err } @@ -297,7 +294,7 @@ func (translator *IngressTranslator) createUpstreamTransportSocket(activatorCA, }, nil } -func createUpstreamTLSContext(caCertificate []byte, activatorSAN string, alpnProtocols ...string) *tls.UpstreamTlsContext { +func createUpstreamTLSContext(caCertificate []byte, alpnProtocols ...string) *tls.UpstreamTlsContext { return &tls.UpstreamTlsContext{ CommonTlsContext: &tls.CommonTlsContext{ AlpnProtocols: alpnProtocols, @@ -313,7 +310,7 @@ func createUpstreamTLSContext(caCertificate []byte, activatorSAN string, alpnPro }, MatchSubjectAltNames: []*envoymatcherv3.StringMatcher{{ MatchPattern: &envoymatcherv3.StringMatcher_Exact{ - Exact: activatorSAN, + Exact: certificates.FakeDnsName, }}, }, }, diff --git a/pkg/generator/ingress_translator_test.go b/pkg/generator/ingress_translator_test.go index 219097234..f83d98082 100644 --- a/pkg/generator/ingress_translator_test.go +++ b/pkg/generator/ingress_translator_test.go @@ -38,10 +38,12 @@ import ( "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/kubernetes/fake" + "knative.dev/control-protocol/pkg/certificates" envoy "knative.dev/net-kourier/pkg/envoy/api" "knative.dev/net-kourier/pkg/reconciler/ingress/config" network "knative.dev/networking/pkg" "knative.dev/networking/pkg/apis/networking/v1alpha1" + netconfig "knative.dev/networking/pkg/config" pkgtest "knative.dev/pkg/reconciler/testing" ) @@ -635,10 +637,9 @@ var ( }, } upstreamTLSConfig = &config.Config{ - Network: &network.Config{ - AutoTLS: false, - ActivatorCA: "test-ca", - ActivatorSAN: "test-san", + Network: &netconfig.Config{ + AutoTLS: false, + InternalEncryption: true, }, } ) @@ -1481,10 +1482,10 @@ var ( caSecret = &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: "knative-testing", - Name: "test-ca", + Name: netconfig.ServingInternalCertName, }, Data: map[string][]byte{ - caDataName: cert, + certificates.SecretCaCertKey: cert, }, } ) @@ -1509,7 +1510,7 @@ func typedConfig(http2 bool) *envoycorev3.TransportSocket_TypedConfig { }, MatchSubjectAltNames: []*envoymatcherv3.StringMatcher{{ MatchPattern: &envoymatcherv3.StringMatcher_Exact{ - Exact: "test-san", + Exact: certificates.FakeDnsName, }}, }, }, diff --git a/pkg/reconciler/ingress/config/store.go b/pkg/reconciler/ingress/config/store.go index de9c15b1b..b7afc1976 100644 --- a/pkg/reconciler/ingress/config/store.go +++ b/pkg/reconciler/ingress/config/store.go @@ -21,6 +21,7 @@ import ( "knative.dev/net-kourier/pkg/config" network "knative.dev/networking/pkg" + netconfig "knative.dev/networking/pkg/config" "knative.dev/pkg/configmap" ) @@ -48,10 +49,9 @@ func FromContextOrDefaults(ctx context.Context) *Config { } } -func defaultConfig() *network.Config { - return &network.Config{ - ActivatorCA: "", - ActivatorSAN: "", +func defaultConfig() *netconfig.Config { + return &netconfig.Config{ + InternalEncryption: false, } } diff --git a/test/config/tls/config-network.yaml b/test/config/tls/config-network.yaml index dd12c87ef..963e10e85 100644 --- a/test/config/tls/config-network.yaml +++ b/test/config/tls/config-network.yaml @@ -22,5 +22,4 @@ metadata: app.kubernetes.io/component: networking app.kubernetes.io/version: devel data: - activator-ca: "serving-ca" - activator-san: "knative" + internal-encryption: "true" diff --git a/test/generate-upstream-cert.sh b/test/generate-upstream-cert.sh index 46472eb8e..5b3317bae 100755 --- a/test/generate-upstream-cert.sh +++ b/test/generate-upstream-cert.sh @@ -17,7 +17,7 @@ SERVING_SYSTEM_NAMESPACE=knative-serving TEST_NAMESPACE=serving-tests out_dir="$(mktemp -d /tmp/certs-XXX)" -san="knative" +san="data-plane.knative.dev" kubectl create ns $SERVING_SYSTEM_NAMESPACE kubectl create ns $TEST_NAMESPACE @@ -32,8 +32,8 @@ openssl req -out "${out_dir}"/tls.csr -newkey rsa:2048 -nodes -keyout "${out_dir openssl x509 -req -extfile <(printf "subjectAltName=DNS:$san") -days 365 -in "${out_dir}"/tls.csr -CA "${out_dir}"/root.crt -CAkey "${out_dir}"/root.key -CAcreateserial -out "${out_dir}"/tls.crt # Create secret -kubectl create -n ${SERVING_SYSTEM_NAMESPACE} secret generic serving-ca \ - --from-file=ca.crt="${out_dir}"/root.crt --dry-run=client -o yaml | kubectl apply -f - +kubectl create -n ${SERVING_SYSTEM_NAMESPACE} secret generic knative-serving-certs \ + --from-file=ca-cert.pem="${out_dir}"/root.crt --dry-run=client -o yaml | kubectl apply -f - kubectl create -n ${TEST_NAMESPACE} secret tls server-certs \ --key="${out_dir}"/tls.key \ diff --git a/third_party/VENDOR-LICENSE/k8s.io/utils/internal/third_party/forked/golang/net/LICENSE b/third_party/VENDOR-LICENSE/k8s.io/utils/internal/third_party/forked/golang/LICENSE similarity index 100% rename from third_party/VENDOR-LICENSE/k8s.io/utils/internal/third_party/forked/golang/net/LICENSE rename to third_party/VENDOR-LICENSE/k8s.io/utils/internal/third_party/forked/golang/LICENSE diff --git a/third_party/VENDOR-LICENSE/knative.dev/control-protocol/pkg/certificates/LICENSE b/third_party/VENDOR-LICENSE/knative.dev/control-protocol/pkg/certificates/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/third_party/VENDOR-LICENSE/knative.dev/control-protocol/pkg/certificates/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/github.com/imdario/mergo/.deepsource.toml b/vendor/github.com/imdario/mergo/.deepsource.toml new file mode 100644 index 000000000..8a0681af8 --- /dev/null +++ b/vendor/github.com/imdario/mergo/.deepsource.toml @@ -0,0 +1,12 @@ +version = 1 + +test_patterns = [ + "*_test.go" +] + +[[analyzers]] +name = "go" +enabled = true + + [analyzers.meta] + import_path = "github.com/imdario/mergo" \ No newline at end of file diff --git a/vendor/github.com/imdario/mergo/.travis.yml b/vendor/github.com/imdario/mergo/.travis.yml index b13a50ed1..dad29725f 100644 --- a/vendor/github.com/imdario/mergo/.travis.yml +++ b/vendor/github.com/imdario/mergo/.travis.yml @@ -4,4 +4,6 @@ install: - go get golang.org/x/tools/cmd/cover - go get github.com/mattn/goveralls script: + - go test -race -v ./... +after_script: - $HOME/gopath/bin/goveralls -service=travis-ci -repotoken $COVERALLS_TOKEN diff --git a/vendor/github.com/imdario/mergo/README.md b/vendor/github.com/imdario/mergo/README.md index d1cefa871..02fc81e06 100644 --- a/vendor/github.com/imdario/mergo/README.md +++ b/vendor/github.com/imdario/mergo/README.md @@ -13,6 +13,7 @@ It is ready for production use. [It is used in several projects by Docker, Googl [![Build Status][1]][2] [![Coverage Status][7]][8] [![Sourcegraph][9]][10] +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_shield) [1]: https://travis-ci.org/imdario/mergo.png [2]: https://travis-ci.org/imdario/mergo @@ -27,7 +28,7 @@ It is ready for production use. [It is used in several projects by Docker, Googl ### Latest release -[Release v0.3.4](https://github.com/imdario/mergo/releases/tag/v0.3.4). +[Release v0.3.7](https://github.com/imdario/mergo/releases/tag/v0.3.7). ### Important note @@ -217,6 +218,21 @@ If I can help you, you have an idea or you are using Mergo in your projects, don Written by [Dario Castañé](http://dario.im). +## Top Contributors + +[![0](https://sourcerer.io/fame/imdario/imdario/mergo/images/0)](https://sourcerer.io/fame/imdario/imdario/mergo/links/0) +[![1](https://sourcerer.io/fame/imdario/imdario/mergo/images/1)](https://sourcerer.io/fame/imdario/imdario/mergo/links/1) +[![2](https://sourcerer.io/fame/imdario/imdario/mergo/images/2)](https://sourcerer.io/fame/imdario/imdario/mergo/links/2) +[![3](https://sourcerer.io/fame/imdario/imdario/mergo/images/3)](https://sourcerer.io/fame/imdario/imdario/mergo/links/3) +[![4](https://sourcerer.io/fame/imdario/imdario/mergo/images/4)](https://sourcerer.io/fame/imdario/imdario/mergo/links/4) +[![5](https://sourcerer.io/fame/imdario/imdario/mergo/images/5)](https://sourcerer.io/fame/imdario/imdario/mergo/links/5) +[![6](https://sourcerer.io/fame/imdario/imdario/mergo/images/6)](https://sourcerer.io/fame/imdario/imdario/mergo/links/6) +[![7](https://sourcerer.io/fame/imdario/imdario/mergo/images/7)](https://sourcerer.io/fame/imdario/imdario/mergo/links/7) + + ## License [BSD 3-Clause](http://opensource.org/licenses/BSD-3-Clause) license, as [Go language](http://golang.org/LICENSE). + + +[![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fimdario%2Fmergo.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fimdario%2Fmergo?ref=badge_large) diff --git a/vendor/github.com/imdario/mergo/map.go b/vendor/github.com/imdario/mergo/map.go index 6ea38e636..d83258b4d 100644 --- a/vendor/github.com/imdario/mergo/map.go +++ b/vendor/github.com/imdario/mergo/map.go @@ -72,6 +72,7 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf case reflect.Struct: srcMap := src.Interface().(map[string]interface{}) for key := range srcMap { + config.overwriteWithEmptyValue = true srcValue := srcMap[key] fieldName := changeInitialCase(key, unicode.ToUpper) dstElement := dst.FieldByName(fieldName) @@ -98,11 +99,11 @@ func deepMap(dst, src reflect.Value, visited map[uintptr]*visit, depth int, conf continue } if srcKind == dstKind { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + if _, err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if dstKind == reflect.Interface && dstElement.Kind() == reflect.Interface { - if err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { + if _, err = deepMerge(dstElement, srcElement, visited, depth+1, config); err != nil { return } } else if srcKind == reflect.Map { @@ -156,7 +157,8 @@ func _map(dst, src interface{}, opts ...func(*Config)) error { // To be friction-less, we redirect equal-type arguments // to deepMerge. Only because arguments can be anything. if vSrc.Kind() == vDst.Kind() { - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) + _, err := deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) + return err } switch vSrc.Kind() { case reflect.Struct: diff --git a/vendor/github.com/imdario/mergo/merge.go b/vendor/github.com/imdario/mergo/merge.go index 706b22069..3332c9c2a 100644 --- a/vendor/github.com/imdario/mergo/merge.go +++ b/vendor/github.com/imdario/mergo/merge.go @@ -9,25 +9,41 @@ package mergo import ( + "fmt" "reflect" + "unsafe" ) func hasExportedField(dst reflect.Value) (exported bool) { for i, n := 0, dst.NumField(); i < n; i++ { field := dst.Type().Field(i) - if field.Anonymous && dst.Field(i).Kind() == reflect.Struct { - exported = exported || hasExportedField(dst.Field(i)) - } else { - exported = exported || len(field.PkgPath) == 0 + if isExportedComponent(&field) { + return true } } return } +func isExportedComponent(field *reflect.StructField) bool { + name := field.Name + pkgPath := field.PkgPath + if len(pkgPath) > 0 { + return false + } + c := name[0] + if 'a' <= c && c <= 'z' || c == '_' { + return false + } + return true +} + type Config struct { - Overwrite bool - AppendSlice bool - Transformers Transformers + Overwrite bool + AppendSlice bool + TypeCheck bool + Transformers Transformers + overwriteWithEmptyValue bool + overwriteSliceWithEmptyValue bool } type Transformers interface { @@ -37,12 +53,17 @@ type Transformers interface { // Traverses recursively both values, assigning src's fields values to dst. // The map argument tracks comparisons that have already been seen, which allows // short circuiting on recursive types. -func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (err error) { +func deepMerge(dstIn, src reflect.Value, visited map[uintptr]*visit, depth int, config *Config) (dst reflect.Value, err error) { + dst = dstIn overwrite := config.Overwrite + typeCheck := config.TypeCheck + overwriteWithEmptySrc := config.overwriteWithEmptyValue + overwriteSliceWithEmptySrc := config.overwriteSliceWithEmptyValue if !src.IsValid() { return } + if dst.CanAddr() { addr := dst.UnsafeAddr() h := 17 * addr @@ -50,7 +71,7 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co typ := dst.Type() for p := seen; p != nil; p = p.next { if p.ptr == addr && p.typ == typ { - return nil + return dst, nil } } // Remember, remember... @@ -64,130 +85,170 @@ func deepMerge(dst, src reflect.Value, visited map[uintptr]*visit, depth int, co } } + if dst.IsValid() && src.IsValid() && src.Type() != dst.Type() { + err = fmt.Errorf("cannot append two different types (%s, %s)", src.Kind(), dst.Kind()) + return + } + switch dst.Kind() { case reflect.Struct: if hasExportedField(dst) { + dstCp := reflect.New(dst.Type()).Elem() for i, n := 0, dst.NumField(); i < n; i++ { - if err = deepMerge(dst.Field(i), src.Field(i), visited, depth+1, config); err != nil { + dstField := dst.Field(i) + structField := dst.Type().Field(i) + // copy un-exported struct fields + if !isExportedComponent(&structField) { + rf := dstCp.Field(i) + rf = reflect.NewAt(rf.Type(), unsafe.Pointer(rf.UnsafeAddr())).Elem() //nolint:gosec + dstRF := dst.Field(i) + if !dst.Field(i).CanAddr() { + continue + } + + dstRF = reflect.NewAt(dstRF.Type(), unsafe.Pointer(dstRF.UnsafeAddr())).Elem() //nolint:gosec + rf.Set(dstRF) + continue + } + dstField, err = deepMerge(dstField, src.Field(i), visited, depth+1, config) + if err != nil { return } + dstCp.Field(i).Set(dstField) } + + if dst.CanSet() { + dst.Set(dstCp) + } else { + dst = dstCp + } + return } else { - if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) { - dst.Set(src) + if (isReflectNil(dst) || overwrite) && (!isEmptyValue(src) || overwriteWithEmptySrc) { + dst = src } } + case reflect.Map: if dst.IsNil() && !src.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) + if dst.CanSet() { + dst.Set(reflect.MakeMap(dst.Type())) + } else { + dst = src + return + } } for _, key := range src.MapKeys() { srcElement := src.MapIndex(key) + dstElement := dst.MapIndex(key) if !srcElement.IsValid() { continue } - dstElement := dst.MapIndex(key) - switch srcElement.Kind() { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Interface, reflect.Slice: - if srcElement.IsNil() { - continue - } - fallthrough - default: - if !srcElement.CanInterface() { - continue - } - switch reflect.TypeOf(srcElement.Interface()).Kind() { - case reflect.Struct: - fallthrough - case reflect.Ptr: - fallthrough - case reflect.Map: - srcMapElm := srcElement - dstMapElm := dstElement - if srcMapElm.CanInterface() { - srcMapElm = reflect.ValueOf(srcMapElm.Interface()) - if dstMapElm.IsValid() { - dstMapElm = reflect.ValueOf(dstMapElm.Interface()) - } - } - if err = deepMerge(dstMapElm, srcMapElm, visited, depth+1, config); err != nil { - return - } - case reflect.Slice: - srcSlice := reflect.ValueOf(srcElement.Interface()) - - var dstSlice reflect.Value - if !dstElement.IsValid() || dstElement.IsNil() { - dstSlice = reflect.MakeSlice(srcSlice.Type(), 0, srcSlice.Len()) - } else { - dstSlice = reflect.ValueOf(dstElement.Interface()) - } - - if !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice { - dstSlice = srcSlice - } else if config.AppendSlice { - dstSlice = reflect.AppendSlice(dstSlice, srcSlice) - } - dst.SetMapIndex(key, dstSlice) + if dst.MapIndex(key).IsValid() { + k := dstElement.Interface() + dstElement = reflect.ValueOf(k) + } + if isReflectNil(srcElement) { + if overwrite || isReflectNil(dstElement) { + dst.SetMapIndex(key, srcElement) } + continue } - if dstElement.IsValid() && reflect.TypeOf(srcElement.Interface()).Kind() == reflect.Map { + if !srcElement.CanInterface() { continue } - if srcElement.IsValid() && (overwrite || (!dstElement.IsValid() || isEmptyValue(dstElement))) { - if dst.IsNil() { - dst.Set(reflect.MakeMap(dst.Type())) + if srcElement.CanInterface() { + srcElement = reflect.ValueOf(srcElement.Interface()) + if dstElement.IsValid() { + dstElement = reflect.ValueOf(dstElement.Interface()) } - dst.SetMapIndex(key, srcElement) } + dstElement, err = deepMerge(dstElement, srcElement, visited, depth+1, config) + if err != nil { + return + } + dst.SetMapIndex(key, dstElement) + } case reflect.Slice: - if !dst.CanSet() { - break - } - if !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice { - dst.Set(src) + newSlice := dst + if (!isEmptyValue(src) || overwriteWithEmptySrc || overwriteSliceWithEmptySrc) && (overwrite || isEmptyValue(dst)) && !config.AppendSlice { + if typeCheck && src.Type() != dst.Type() { + return dst, fmt.Errorf("cannot override two slices with different type (%s, %s)", src.Type(), dst.Type()) + } + newSlice = src } else if config.AppendSlice { - dst.Set(reflect.AppendSlice(dst, src)) + if typeCheck && src.Type() != dst.Type() { + err = fmt.Errorf("cannot append two slice with different type (%s, %s)", src.Type(), dst.Type()) + return + } + newSlice = reflect.AppendSlice(dst, src) + } + if dst.CanSet() { + dst.Set(newSlice) + } else { + dst = newSlice } - case reflect.Ptr: - fallthrough - case reflect.Interface: - if src.IsNil() { + case reflect.Ptr, reflect.Interface: + if isReflectNil(src) { break } - if src.Kind() != reflect.Interface { + + if dst.Kind() != reflect.Ptr && src.Type().AssignableTo(dst.Type()) { if dst.IsNil() || overwrite { + if overwrite || isEmptyValue(dst) { + if dst.CanSet() { + dst.Set(src) + } else { + dst = src + } + } + } + break + } + + if src.Kind() != reflect.Interface { + if dst.IsNil() || (src.Kind() != reflect.Ptr && overwrite) { if dst.CanSet() && (overwrite || isEmptyValue(dst)) { dst.Set(src) } } else if src.Kind() == reflect.Ptr { - if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + if dst, err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } + dst = dst.Addr() } else if dst.Elem().Type() == src.Type() { - if err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { + if dst, err = deepMerge(dst.Elem(), src, visited, depth+1, config); err != nil { return } } else { - return ErrDifferentArgumentsTypes + return dst, ErrDifferentArgumentsTypes } break } if dst.IsNil() || overwrite { - if dst.CanSet() && (overwrite || isEmptyValue(dst)) { - dst.Set(src) + if (overwrite || isEmptyValue(dst)) && (overwriteWithEmptySrc || !isEmptyValue(src)) { + if dst.CanSet() { + dst.Set(src) + } else { + dst = src + } } - } else if err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { + } else if _, err = deepMerge(dst.Elem(), src.Elem(), visited, depth+1, config); err != nil { return } default: - if dst.CanSet() && !isEmptyValue(src) && (overwrite || isEmptyValue(dst)) { - dst.Set(src) + overwriteFull := (!isEmptyValue(src) || overwriteWithEmptySrc) && (overwrite || isEmptyValue(dst)) + if overwriteFull { + if dst.CanSet() { + dst.Set(src) + } else { + dst = src + } } } + return } @@ -199,7 +260,7 @@ func Merge(dst, src interface{}, opts ...func(*Config)) error { return merge(dst, src, opts...) } -// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overriden by +// MergeWithOverwrite will do the same as Merge except that non-empty dst attributes will be overridden by // non-empty src attribute values. // Deprecated: use Merge(…) with WithOverride func MergeWithOverwrite(dst, src interface{}, opts ...func(*Config)) error { @@ -218,11 +279,26 @@ func WithOverride(config *Config) { config.Overwrite = true } -// WithAppendSlice will make merge append slices instead of overwriting it +// WithOverwriteWithEmptyValue will make merge override non empty dst attributes with empty src attributes values. +func WithOverwriteWithEmptyValue(config *Config) { + config.overwriteWithEmptyValue = true +} + +// WithOverrideEmptySlice will make merge override empty dst slice with empty src slice. +func WithOverrideEmptySlice(config *Config) { + config.overwriteSliceWithEmptyValue = true +} + +// WithAppendSlice will make merge append slices instead of overwriting it. func WithAppendSlice(config *Config) { config.AppendSlice = true } +// WithTypeCheck will make merge check types while overwriting it (must be used with WithOverride). +func WithTypeCheck(config *Config) { + config.TypeCheck = true +} + func merge(dst, src interface{}, opts ...func(*Config)) error { var ( vDst, vSrc reflect.Value @@ -238,8 +314,25 @@ func merge(dst, src interface{}, opts ...func(*Config)) error { if vDst, vSrc, err = resolveValues(dst, src); err != nil { return err } + if !vDst.CanSet() { + return fmt.Errorf("cannot set dst, needs reference") + } if vDst.Type() != vSrc.Type() { return ErrDifferentArgumentsTypes } - return deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) + _, err = deepMerge(vDst, vSrc, make(map[uintptr]*visit), 0, config) + return err +} + +// IsReflectNil is the reflect value provided nil +func isReflectNil(v reflect.Value) bool { + k := v.Kind() + switch k { + case reflect.Interface, reflect.Slice, reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr: + // Both interface and slice are nil if first word is 0. + // Both are always bigger than a word; assume flagIndir. + return v.IsNil() + default: + return false + } } diff --git a/vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go b/vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go new file mode 100644 index 000000000..fd4db4407 --- /dev/null +++ b/vendor/k8s.io/utils/internal/third_party/forked/golang/golang-lru/lru.go @@ -0,0 +1,133 @@ +/* +Copyright 2013 Google Inc. + +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 lru implements an LRU cache. +package golang_lru + +import "container/list" + +// Cache is an LRU cache. It is not safe for concurrent access. +type Cache struct { + // MaxEntries is the maximum number of cache entries before + // an item is evicted. Zero means no limit. + MaxEntries int + + // OnEvicted optionally specifies a callback function to be + // executed when an entry is purged from the cache. + OnEvicted func(key Key, value interface{}) + + ll *list.List + cache map[interface{}]*list.Element +} + +// A Key may be any value that is comparable. See http://golang.org/ref/spec#Comparison_operators +type Key interface{} + +type entry struct { + key Key + value interface{} +} + +// New creates a new Cache. +// If maxEntries is zero, the cache has no limit and it's assumed +// that eviction is done by the caller. +func New(maxEntries int) *Cache { + return &Cache{ + MaxEntries: maxEntries, + ll: list.New(), + cache: make(map[interface{}]*list.Element), + } +} + +// Add adds a value to the cache. +func (c *Cache) Add(key Key, value interface{}) { + if c.cache == nil { + c.cache = make(map[interface{}]*list.Element) + c.ll = list.New() + } + if ee, ok := c.cache[key]; ok { + c.ll.MoveToFront(ee) + ee.Value.(*entry).value = value + return + } + ele := c.ll.PushFront(&entry{key, value}) + c.cache[key] = ele + if c.MaxEntries != 0 && c.ll.Len() > c.MaxEntries { + c.RemoveOldest() + } +} + +// Get looks up a key's value from the cache. +func (c *Cache) Get(key Key) (value interface{}, ok bool) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.ll.MoveToFront(ele) + return ele.Value.(*entry).value, true + } + return +} + +// Remove removes the provided key from the cache. +func (c *Cache) Remove(key Key) { + if c.cache == nil { + return + } + if ele, hit := c.cache[key]; hit { + c.removeElement(ele) + } +} + +// RemoveOldest removes the oldest item from the cache. +func (c *Cache) RemoveOldest() { + if c.cache == nil { + return + } + ele := c.ll.Back() + if ele != nil { + c.removeElement(ele) + } +} + +func (c *Cache) removeElement(e *list.Element) { + c.ll.Remove(e) + kv := e.Value.(*entry) + delete(c.cache, kv.key) + if c.OnEvicted != nil { + c.OnEvicted(kv.key, kv.value) + } +} + +// Len returns the number of items in the cache. +func (c *Cache) Len() int { + if c.cache == nil { + return 0 + } + return c.ll.Len() +} + +// Clear purges all stored items from the cache. +func (c *Cache) Clear() { + if c.OnEvicted != nil { + for _, e := range c.cache { + kv := e.Value.(*entry) + c.OnEvicted(kv.key, kv.value) + } + } + c.ll = nil + c.cache = nil +} diff --git a/vendor/k8s.io/utils/lru/lru.go b/vendor/k8s.io/utils/lru/lru.go new file mode 100644 index 000000000..5d0077abf --- /dev/null +++ b/vendor/k8s.io/utils/lru/lru.go @@ -0,0 +1,79 @@ +/* +Copyright 2021 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 lru + +import ( + "sync" + + groupcache "k8s.io/utils/internal/third_party/forked/golang/golang-lru" +) + +type Key = groupcache.Key + +// Cache is a thread-safe fixed size LRU cache. +type Cache struct { + cache *groupcache.Cache + lock sync.RWMutex +} + +// New creates an LRU of the given size. +func New(size int) *Cache { + return &Cache{ + cache: groupcache.New(size), + } +} + +// Add adds a value to the cache. +func (c *Cache) Add(key Key, value interface{}) { + c.lock.Lock() + defer c.lock.Unlock() + c.cache.Add(key, value) +} + +// Get looks up a key's value from the cache. +func (c *Cache) Get(key Key) (value interface{}, ok bool) { + c.lock.Lock() + defer c.lock.Unlock() + return c.cache.Get(key) +} + +// Remove removes the provided key from the cache. +func (c *Cache) Remove(key Key) { + c.lock.Lock() + defer c.lock.Unlock() + c.cache.Remove(key) +} + +// RemoveOldest removes the oldest item from the cache. +func (c *Cache) RemoveOldest() { + c.lock.Lock() + defer c.lock.Unlock() + c.cache.RemoveOldest() +} + +// Len returns the number of items in the cache. +func (c *Cache) Len() int { + c.lock.RLock() + defer c.lock.RUnlock() + return c.cache.Len() +} + +// Clear purges all stored items from the cache. +func (c *Cache) Clear() { + c.lock.Lock() + defer c.lock.Unlock() + c.cache.Clear() +} diff --git a/vendor/knative.dev/control-protocol/LICENSE b/vendor/knative.dev/control-protocol/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/vendor/knative.dev/control-protocol/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/vendor/knative.dev/control-protocol/pkg/certificates/certs.go b/vendor/knative.dev/control-protocol/pkg/certificates/certs.go new file mode 100644 index 000000000..9f79c827f --- /dev/null +++ b/vendor/knative.dev/control-protocol/pkg/certificates/certs.go @@ -0,0 +1,221 @@ +/* +Copyright 2021 The Knative 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 certificates + +import ( + "context" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "crypto/x509/pkix" + "encoding/pem" + "errors" + "fmt" + "math/big" + "time" + + "go.uber.org/zap" + "knative.dev/pkg/logging" +) + +var randReader = rand.Reader +var serialNumberLimit = new(big.Int).Lsh(big.NewInt(1), 128) + +// Copy-pasted from https://github.com/knative/pkg/blob/975a1cf9e4470b26ce54d9cc628dbd50716b6b95/webhook/certificates/resources/certs.go +func createCertTemplate(expirationInterval time.Duration) (*x509.Certificate, error) { + serialNumber, err := rand.Int(randReader, serialNumberLimit) + if err != nil { + return nil, errors.New("failed to generate serial number: " + err.Error()) + } + + tmpl := x509.Certificate{ + SerialNumber: serialNumber, + Subject: pkix.Name{ + Organization: []string{Organization}, + CommonName: "control-plane", + }, + SignatureAlgorithm: x509.SHA256WithRSA, + NotBefore: time.Now(), + NotAfter: time.Now().Add(expirationInterval), + BasicConstraintsValid: true, + DNSNames: []string{FakeDnsName}, + } + return &tmpl, nil +} + +// Create cert template suitable for CA and hence signing +func createCACertTemplate(expirationInterval time.Duration) (*x509.Certificate, error) { + rootCert, err := createCertTemplate(expirationInterval) + if err != nil { + return nil, err + } + // Make it into a CA cert and change it so we can use it to sign certs + rootCert.IsCA = true + rootCert.KeyUsage = x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature + rootCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth} + return rootCert, nil +} + +// Create cert template that we can use on the server for TLS +func createServerCertTemplate(expirationInterval time.Duration) (*x509.Certificate, error) { + serverCert, err := createCertTemplate(expirationInterval) + if err != nil { + return nil, err + } + serverCert.KeyUsage = x509.KeyUsageDigitalSignature + serverCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} + return serverCert, err +} + +// Create cert template that we can use on the server for TLS +func createClientCertTemplate(expirationInterval time.Duration) (*x509.Certificate, error) { + serverCert, err := createCertTemplate(expirationInterval) + if err != nil { + return nil, err + } + serverCert.KeyUsage = x509.KeyUsageDigitalSignature + serverCert.ExtKeyUsage = []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth} + return serverCert, err +} + +func createCert(template, parent *x509.Certificate, pub, parentPriv interface{}) (cert *x509.Certificate, certPEM *pem.Block, err error) { + certDER, err := x509.CreateCertificate(rand.Reader, template, parent, pub, parentPriv) + if err != nil { + return + } + cert, err = x509.ParseCertificate(certDER) + if err != nil { + return + } + certPEM = &pem.Block{Type: "CERTIFICATE", Bytes: certDER} + return +} + +// CreateCACerts generates the root CA cert +func CreateCACerts(ctx context.Context, expirationInterval time.Duration) (*KeyPair, error) { + logger := logging.FromContext(ctx) + caKeyPair, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + logger.Errorw("error generating random key", zap.Error(err)) + return nil, err + } + + rootCertTmpl, err := createCACertTemplate(expirationInterval) + if err != nil { + logger.Errorw("error generating CA cert", zap.Error(err)) + return nil, err + } + + _, caCertPem, err := createCert(rootCertTmpl, rootCertTmpl, &caKeyPair.PublicKey, caKeyPair) + if err != nil { + logger.Errorw("error signing the CA cert", zap.Error(err)) + return nil, err + } + caPrivateKeyPem := &pem.Block{ + Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(caKeyPair), + } + return NewKeyPair(caPrivateKeyPem, caCertPem), nil +} + +// CreateControlPlaneCert generates the certificate for the client +func CreateControlPlaneCert(ctx context.Context, caKey *rsa.PrivateKey, caCertificate *x509.Certificate, expirationInterval time.Duration) (*KeyPair, error) { + logger := logging.FromContext(ctx) + + // Then create the private key for the serving cert + clientKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + logger.Errorw("error generating random key", zap.Error(err)) + return nil, err + } + clientCertTemplate, err := createClientCertTemplate(expirationInterval) + if err != nil { + logger.Errorw("failed to create the server certificate template", zap.Error(err)) + return nil, err + } + + // create a certificate which wraps the server's public key, sign it with the CA private key + _, clientCertPEM, err := createCert(clientCertTemplate, caCertificate, &clientKey.PublicKey, caKey) + if err != nil { + logger.Errorw("error signing client certificate template", zap.Error(err)) + return nil, err + } + privateClientKeyPEM := &pem.Block{ + Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(clientKey), + } + return NewKeyPair(privateClientKeyPEM, clientCertPEM), nil +} + +// CreateDataPlaneCert generates the certificate for the server +func CreateDataPlaneCert(ctx context.Context, caKey *rsa.PrivateKey, caCertificate *x509.Certificate, expirationInterval time.Duration) (*KeyPair, error) { + logger := logging.FromContext(ctx) + + // Then create the private key for the serving cert + serverKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + logger.Errorw("error generating random key", zap.Error(err)) + return nil, err + } + serverCertTemplate, err := createServerCertTemplate(expirationInterval) + if err != nil { + logger.Errorw("failed to create the server certificate template", zap.Error(err)) + return nil, err + } + + // create a certificate which wraps the server's public key, sign it with the CA private key + _, serverCertPEM, err := createCert(serverCertTemplate, caCertificate, &serverKey.PublicKey, caKey) + if err != nil { + logger.Errorw("error signing server certificate template", zap.Error(err)) + return nil, err + } + privateServerKeyPEM := &pem.Block{ + Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(serverKey), + } + return NewKeyPair(privateServerKeyPEM, serverCertPEM), nil +} + +// ParseCert parses a certificate/private key pair from serialized pem blocks +func ParseCert(certPemBytes []byte, privateKeyPemBytes []byte) (*x509.Certificate, *rsa.PrivateKey, error) { + certBlock, _ := pem.Decode(certPemBytes) + if certBlock == nil { + return nil, nil, fmt.Errorf("decoding the cert block returned nil") + } + if certBlock.Type != "CERTIFICATE" { + return nil, nil, fmt.Errorf("bad pem block, expecting type 'CERTIFICATE', found %q", certBlock.Type) + } + cert, err := x509.ParseCertificate(certBlock.Bytes) + if err != nil { + return nil, nil, err + } + + pkBlock, _ := pem.Decode(privateKeyPemBytes) + if pkBlock == nil { + return nil, nil, fmt.Errorf("decoding the pk block returned nil") + } + if pkBlock.Type != "RSA PRIVATE KEY" { + return nil, nil, fmt.Errorf("bad pem block, expecting type 'RSA PRIVATE KEY', found %q", pkBlock.Type) + } + pk, err := x509.ParsePKCS1PrivateKey(pkBlock.Bytes) + return cert, pk, err +} + +// ValidateCert checks the expiration of the certificate +func ValidateCert(cert *x509.Certificate, rotationThreshold time.Duration) error { + if !cert.NotAfter.After(time.Now().Add(rotationThreshold)) { + return fmt.Errorf("certificate is going to expire %v", cert.NotAfter) + } + return nil +} diff --git a/vendor/knative.dev/control-protocol/pkg/certificates/constants.go b/vendor/knative.dev/control-protocol/pkg/certificates/constants.go new file mode 100644 index 000000000..77f18c8df --- /dev/null +++ b/vendor/knative.dev/control-protocol/pkg/certificates/constants.go @@ -0,0 +1,26 @@ +/* +Copyright 2021 The Knative 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 certificates + +const ( + Organization = "knative.dev" + FakeDnsName = "data-plane." + Organization + + SecretCaCertKey = "ca-cert.pem" + SecretCertKey = "public-cert.pem" + SecretPKKey = "private-key.pem" +) diff --git a/vendor/knative.dev/control-protocol/pkg/certificates/key_pair.go b/vendor/knative.dev/control-protocol/pkg/certificates/key_pair.go new file mode 100644 index 000000000..67abc42dd --- /dev/null +++ b/vendor/knative.dev/control-protocol/pkg/certificates/key_pair.go @@ -0,0 +1,60 @@ +/* +Copyright 2021 The Knative 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 certificates + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" +) + +type KeyPair struct { + privateKeyBlock *pem.Block + privateKeyPemBytes []byte + + certBlock *pem.Block + certPemBytes []byte +} + +func NewKeyPair(privateKey *pem.Block, cert *pem.Block) *KeyPair { + return &KeyPair{ + privateKeyBlock: privateKey, + privateKeyPemBytes: pem.EncodeToMemory(privateKey), + certBlock: cert, + certPemBytes: pem.EncodeToMemory(cert), + } +} + +func (kh *KeyPair) PrivateKey() *pem.Block { + return kh.privateKeyBlock +} + +func (kh *KeyPair) PrivateKeyBytes() []byte { + return kh.privateKeyPemBytes +} + +func (kh *KeyPair) Cert() *pem.Block { + return kh.certBlock +} + +func (kh *KeyPair) CertBytes() []byte { + return kh.certPemBytes +} + +func (kh *KeyPair) Parse() (*x509.Certificate, *rsa.PrivateKey, error) { + return ParseCert(kh.certPemBytes, kh.privateKeyPemBytes) +} diff --git a/vendor/knative.dev/networking/config/config-network.yaml b/vendor/knative.dev/networking/config/config-network.yaml index aed72bba5..39cbc4a1b 100644 --- a/vendor/knative.dev/networking/config/config-network.yaml +++ b/vendor/knative.dev/networking/config/config-network.yaml @@ -22,7 +22,7 @@ metadata: app.kubernetes.io/component: networking app.kubernetes.io/version: devel annotations: - knative.dev/example-checksum: "d0b91f80" + knative.dev/example-checksum: "73d96d1b" data: _example: | ################################ @@ -173,50 +173,12 @@ data: # Knative doesn't know about that otherwise. default-external-scheme: "http" - # The CA public certificate used to sign the activator TLS certificate. - # It is specified by the secret name, which has the "ca.crt" data field. - # Use an empty value to disable the feature (default). + # internal-encryption indicates whether internal traffic is encrypted or not. + # If this is "true", the following traffic are encrypted: + # - ingress to activator + # - ingress to queue-proxy + # - activator to queue-proxy # # NOTE: This flag is in an alpha state and is mostly here to enable internal testing # for now. Use with caution. - activator-ca: "" - - # The SAN (Subject Alt Name) used to validate the activator TLS certificate. - # It must be set when "activator-ca" is specified. - # Use an empty value to disable the feature (default). - # - # NOTE: This flag is in an alpha state and is mostly here to enable internal testing - # for now. Use with caution. - activator-san: "" - - # The server certificates to serve the TLS traffic from ingress to activator. - # It is specified by the secret name, which has the "tls.crt" and "tls.key" data field. - # Use an empty value to disable the feature (default). - # - # NOTE: This flag is in an alpha state and is mostly here to enable internal testing - # for now. Use with caution. - activator-cert-secret: "" - - # The CA public certificate used to sign the queue-proxy TLS certificate. - # It is specified by the secret name, which has the "ca.crt" data field. - # Use an empty value to disable the feature (default). - # - # NOTE: This flag is in an alpha state and is mostly here to enable internal testing - # for now. Use with caution. - queue-proxy-ca: "" - - # The SAN (Subject Alt Name) used to validate the activator TLS certificate. - # It must be set when "queue-proxy-ca" is specified. - # Use an empty value to disable the feature (default). - # - # NOTE: This flag is in an alpha state and is mostly here to enable internal testing - # for now. Use with caution. - queue-proxy-san: "" - - # The server certificates to serve the TLS traffic from activator to queue-proxy. - # It is specified by the secret name, which has the "tls.crt" and "tls.key" data field. - # Use an empty value to disable the feature (default). - # - # NOTE: This flag is in an alpha state and is mostly here to enable internal testing - # for now. Use with caution. - queue-proxy-cert-secret: "" + internal-encryption: "false" diff --git a/vendor/knative.dev/networking/pkg/apis/networking/register.go b/vendor/knative.dev/networking/pkg/apis/networking/register.go index 80751d127..f7bdd81d7 100644 --- a/vendor/knative.dev/networking/pkg/apis/networking/register.go +++ b/vendor/knative.dev/networking/pkg/apis/networking/register.go @@ -22,6 +22,9 @@ const ( // GroupName is the name for the networking API group. GroupName = "networking.internal.knative.dev" + // CertifcateUIDLabelKey is used to specify a label selector for informers listing ingress secrets. + CertificateUIDLabelKey = GroupName + "/certificate-uid" + // IngressLabelKey is the label key attached to underlying network programming // resources to indicate which Ingress triggered their creation. IngressLabelKey = GroupName + "/ingress" @@ -104,6 +107,12 @@ const ( // WildcardCertDomainLabelKey is the label key attached to a certificate to indicate the // domain for which it was issued. WildcardCertDomainLabelKey = PublicGroupName + "/wildcardDomain" + + // VisibilityLabelKey is the label to indicate visibility of Route + // and KServices. It can be an annotation too but since users are + // already using labels for domain, it probably best to keep this + // consistent. + VisibilityLabelKey = PublicGroupName + "/visibility" ) // Pseudo-constants diff --git a/vendor/knative.dev/networking/pkg/network.go b/vendor/knative.dev/networking/pkg/config/config.go similarity index 59% rename from vendor/knative.dev/networking/pkg/network.go rename to vendor/knative.dev/networking/pkg/config/config.go index fef813530..30580161a 100644 --- a/vendor/knative.dev/networking/pkg/network.go +++ b/vendor/knative.dev/networking/pkg/config/config.go @@ -1,11 +1,11 @@ /* -Copyright 2018 The Knative Authors +Copyright 2022 The Knative 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 - https://www.apache.org/licenses/LICENSE-2.0 + 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, @@ -14,65 +14,49 @@ See the License for the specific language governing permissions and limitations under the License. */ -package pkg +package config import ( "bytes" "errors" "fmt" "io/ioutil" - "net/http" "net/url" "strings" "text/template" - lru "github.com/hashicorp/golang-lru" - corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/utils/lru" cm "knative.dev/pkg/configmap" "sigs.k8s.io/yaml" ) -const ( - // ProbePath is the name of a path that activator, autoscaler and - // prober(used by KIngress generally) use for health check. - ProbePath = "/healthz" - - // ProbeHeaderName is the name of a header that can be added to - // requests to probe the knative networking layer. Requests - // with this header will not be passed to the user container or - // included in request metrics. - ProbeHeaderName = "K-Network-Probe" - - // ProxyHeaderName is the name of an internal header that activator - // uses to mark requests going through it. - ProxyHeaderName = "K-Proxy-Request" - - // HashHeaderName is the name of an internal header that Ingress controller - // uses to find out which version of the networking config is deployed. - HashHeaderName = "K-Network-Hash" - - // HashHeaderValue is the value that must appear in the HashHeaderName - // header in order for our network hash to be injected. - HashHeaderValue = "override" - - // OriginalHostHeader is used to avoid Istio host based routing rules - // in Activator. - // The header contains the original Host value that can be rewritten - // at the Queue proxy level back to be a host header. - OriginalHostHeader = "K-Original-Host" +var ( + templateCache *lru.Cache + + // Verify the default templates are valid. + _ = template.Must(template.New("domain-template").Parse(DefaultDomainTemplate)) + _ = template.Must(template.New("tag-template").Parse(DefaultTagTemplate)) +) +func init() { + // The only failure is due to negative size. + // Store ~10 latest templates per template type. + templateCache = lru.New(10 * 2) +} + +const ( // ConfigName is the name of the configmap containing all // customizations for networking features. - ConfigName = "config-network" + ConfigMapName = "config-network" - // DefaultIngressClassKey is the name of the configuration entry - // that specifies the default Ingress. - DefaultIngressClassKey = "ingress-class" + // DefaultDomainTemplate is the default golang template to use when + // constructing the Knative Route's Domain(host) + DefaultDomainTemplate = "{{.Name}}.{{.Namespace}}.{{.Domain}}" - // DefaultCertificateClassKey is the name of the configuration entry - // that specifies the default Certificate. - DefaultCertificateClassKey = "certificate-class" + // DefaultTagTemplate is the default golang template to use when + // constructing the Knative Route's tag names. + DefaultTagTemplate = "{{.Tag}}-{{.Name}}" // IstioIngressClassName value for specifying knative's Istio // Ingress reconciler. @@ -82,42 +66,13 @@ const ( // Certificate reconciler. CertManagerCertificateClassName = "cert-manager.certificate.networking.knative.dev" - // DomainTemplateKey is the name of the configuration entry that - // specifies the golang template string to use to construct the - // Knative service's DNS name. - DomainTemplateKey = "domain-template" - - // TagTemplateKey is the name of the configuration entry that - // specifies the golang template string to use to construct the - // hostname for a Route's tag. - TagTemplateKey = "tag-template" - - // RolloutDurationKey is the name of the configuration entry - // that specifies the default duration of the configuration rollout. - RolloutDurationKey = "rollout-duration" - - // NamespaceWildcardCertSelectorKey is the name of the configuration - // entry that specifies a LabelSelector to control which namespaces - // have a wildcard certificate provisioned for them. - NamespaceWildcardCertSelectorKey = "namespace-wildcard-cert-selector" - - // KubeProbeUAPrefix is the user agent prefix of the probe. - // Since K8s 1.8, prober requests have - // User-Agent = "kube-probe/{major-version}.{minor-version}". - KubeProbeUAPrefix = "kube-probe/" - - // KubeletProbeHeaderName is the name of the header supplied by kubelet - // probes. Istio with mTLS rewrites probes, but their probes pass a - // different user-agent. So we augment the probes with this header. - KubeletProbeHeaderName = "K-Kubelet-Probe" - - // DefaultDomainTemplate is the default golang template to use when - // constructing the Knative Route's Domain(host) - DefaultDomainTemplate = "{{.Name}}.{{.Namespace}}.{{.Domain}}" + // ServingInternalCertName is the name of secret contains certificates in serving + // system namespace. + ServingInternalCertName = "knative-serving-certs" +) - // DefaultTagTemplate is the default golang template to use when - // constructing the Knative Route's tag names. - DefaultTagTemplate = "{{.Tag}}-{{.Name}}" +// Config Keys +const ( // AutocreateClusterDomainClaimsKey is the key for the // AutocreateClusterDomainClaims property. @@ -127,90 +82,90 @@ const ( // that specifies enabling auto-TLS or not. AutoTLSKey = "auto-tls" - // HTTPProtocolKey is the name of the configuration entry that - // specifies the HTTP endpoint behavior of Knative ingress. - HTTPProtocolKey = "http-protocol" - - // UserAgentKey is the constant for header "User-Agent". - UserAgentKey = "User-Agent" - - // ActivatorUserAgent is the user-agent header value set in probe requests sent - // from activator. - ActivatorUserAgent = "Knative-Activator-Probe" + // DefaultCertificateClassKey is the name of the configuration entry + // that specifies the default Certificate. + DefaultCertificateClassKey = "certificate-class" - // QueueProxyUserAgent is the user-agent header value set in probe requests sent - // from queue-proxy. - QueueProxyUserAgent = "Knative-Queue-Proxy-Probe" + // DefaultExternalSchemeKey is the config for defining the scheme of external URLs. + DefaultExternalSchemeKey = "default-external-scheme" - // IngressReadinessUserAgent is the user-agent header value - // set in probe requests for Ingress status. - IngressReadinessUserAgent = "Knative-Ingress-Probe" + // DefaultIngressClassKey is the name of the configuration entry + // that specifies the default Ingress. + DefaultIngressClassKey = "ingress-class" - // AutoscalingUserAgent is the user-agent header value set in probe - // requests sent by autoscaling implementations. - AutoscalingUserAgent = "Knative-Autoscaling-Probe" + // DomainTemplateKey is the name of the configuration entry that + // specifies the golang template string to use to construct the + // Knative service's DNS name. + DomainTemplateKey = "domain-template" - // TagHeaderName is the name of the header entry which has a tag name as value. - // The tag name specifies which route was expected to be chosen by Ingress. - TagHeaderName = "Knative-Serving-Tag" + // EnableMeshPodAddressabilityKey is the config for enabling pod addressability in mesh. + EnableMeshPodAddressabilityKey = "enable-mesh-pod-addressability" - // DefaultRouteHeaderName is the name of the header entry - // identifying whether a request is routed via the default route or not. - // It has one of the string value "true" or "false". - DefaultRouteHeaderName = "Knative-Serving-Default-Route" + // HTTPProtocolKey is the name of the configuration entry that + // specifies the HTTP endpoint behavior of Knative ingress. + HTTPProtocolKey = "http-protocol" - // ProtoAcceptContent is the content type to be used when autoscaler scrapes metrics from the QP - ProtoAcceptContent = "application/protobuf" + // MeshCompatibilityModeKey is the config for selecting the mesh compatibility mode. + MeshCompatibilityModeKey = "mesh-compatibility-mode" - // FlushInterval controls the time when we flush the connection in the - // reverse proxies (Activator, QP). - // As of go1.16, a FlushInterval of 0 (the default) still flushes immediately - // when Content-Length is -1, which means the default works properly for - // streaming/websockets, without flushing more often than necessary for - // non-streaming requests. - FlushInterval = 0 + // NamespaceWildcardCertSelectorKey is the name of the configuration + // entry that specifies a LabelSelector to control which namespaces + // have a wildcard certificate provisioned for them. + NamespaceWildcardCertSelectorKey = "namespace-wildcard-cert-selector" - // VisibilityLabelKey is the label to indicate visibility of Route - // and KServices. It can be an annotation too but since users are - // already using labels for domain, it probably best to keep this - // consistent. - VisibilityLabelKey = "networking.knative.dev/visibility" + // RolloutDurationKey is the name of the configuration entry + // that specifies the default duration of the configuration rollout. + RolloutDurationKey = "rollout-duration" - // PassthroughLoadbalancingHeaderName is the name of the header that directs - // load balancers to not load balance the respective request but to - // send it to the request's target directly. - PassthroughLoadbalancingHeaderName = "K-Passthrough-Lb" + // TagTemplateKey is the name of the configuration entry that + // specifies the golang template string to use to construct the + // hostname for a Route's tag. + TagTemplateKey = "tag-template" - // EnableMeshPodAddressabilityKey is the config for enabling pod addressability in mesh. - EnableMeshPodAddressabilityKey = "enable-mesh-pod-addressability" + // InternalEncryptionKey is the name of the configuration whether + // internal traffic is encrypted or not. + InternalEncryptionKey = "internal-encryption" +) - // MeshCompatibilityModeKey is the config for selecting the mesh compatibility mode. - MeshCompatibilityModeKey = "mesh-compatibility-mode" +// HTTPProtocol indicates a type of HTTP endpoint behavior +// that Knative ingress could take. +type HTTPProtocol string - // DefaultExternalSchemeKey is the config for defining the scheme of external URLs. - DefaultExternalSchemeKey = "default-external-scheme" +const ( + // HTTPEnabled represents HTTP protocol is enabled in Knative ingress. + HTTPEnabled HTTPProtocol = "enabled" - // ActivatorCAKey is the config for the secret name, which stores CA public certificate used - // to sign the activator TLS certificate. - ActivatorCAKey = "activator-ca" + // HTTPDisabled represents HTTP protocol is disabled in Knative ingress. + HTTPDisabled HTTPProtocol = "disabled" - // ActivatorSANKey is the config for the SAN used to validate the activator TLS certificate. - ActivatorSANKey = "activator-san" + // HTTPRedirected represents HTTP connection is redirected to HTTPS in Knative ingress. + HTTPRedirected HTTPProtocol = "redirected" +) - // ActivatorCertKey is the config for the secret name, which stores certificates - // to serve the TLS traffic from ingress to activator. - ActivatorCertKey = "activator-cert-secret" +// MeshCompatibilityMode is one of enabled (always use ClusterIP), disabled +// (always use Pod IP), or auto (try PodIP, and fall back to ClusterIP if mesh +// is detected). +type MeshCompatibilityMode string - // QueueProxyCAKey is the config for the secret name, which stores CA public certificate used - // to sign the queue-proxy TLS certificate. - QueueProxyCAKey = "queue-proxy-ca" +const ( + // MeshCompatibilityModeEnabled instructs consumers of network plugins, such as + // Knative Serving, to use ClusterIP when connecting to pods. This is + // required when mesh is enabled (unless EnableMeshPodAddressability is set), + // but is less efficient. + MeshCompatibilityModeEnabled MeshCompatibilityMode = "enabled" - // QueueProxySANKey is the config for the SAN used to validate the queue-proxy TLS certificate. - QueueProxySANKey = "queue-proxy-san" + // MeshCompatibilityModeDisabled instructs consumers of network plugins, such as + // Knative Serving, to connect to individual Pod IPs. This is most efficient, + // but will only work with mesh enabled when EnableMeshPodAddressability is + // used. + MeshCompatibilityModeDisabled MeshCompatibilityMode = "disabled" - // QueueProxyCertKey is the config for the secret name, which stores certificates - // to serve the TLS traffic from activator to queue-proxy. - QueueProxyCertKey = "queue-proxy-cert-secret" + // MeshCompatibilityModeAuto instructs consumers of network plugins, such as + // Knative Serving, to heuristically determine whether to connect using the + // Cluster IP, or to ocnnect to individual Pod IPs. This is most efficient, + // determine whether mesh is enabled, and fall back from Direct Pod IP + // communication to Cluster IP as needed. + MeshCompatibilityModeAuto MeshCompatibilityMode = "auto" ) // DomainTemplateValues are the available properties people can choose from @@ -232,20 +187,6 @@ type TagTemplateValues struct { Tag string } -var ( - templateCache *lru.Cache - - // Verify the default templates are valid. - _ = template.Must(template.New("domain-template").Parse(DefaultDomainTemplate)) - _ = template.Must(template.New("tag-template").Parse(DefaultTagTemplate)) -) - -func init() { - // The only failure is due to negative size. - // Store ~10 latest templates per template type. - templateCache, _ = lru.New(10 * 2) -} - // Config contains the networking configuration defined in the // network config map. type Config struct { @@ -310,70 +251,10 @@ type Config struct { // not enabled. Defaults to "http". DefaultExternalScheme string - // ActivatorCA defines the secret name of the CA public certificate used to sign the activator TLS certificate. - // The traffic is not encrypted if ActivatorCA is empty. - ActivatorCA string - - // ActivatorSAN defines the SAN (Subject Alt Name) used to validate the activator TLS certificate. - // It is used only when ActivatorCA is specified. - ActivatorSAN string - - // ActivatorCertSecret defines the secret name of the server certificates to serve the TLS traffic from ingress to activator. - ActivatorCertSecret string - - // QueueProxyCA defines the secret name of the CA public certificate used to sign the queue-proxy TLS certificate. - // The traffic to queue-proxy is not encrypted if QueueProxyCA is empty. - QueueProxyCA string - - // QueueProxySAN defines the SAN (Subject Alt Name) used to validate the queue-proxy TLS certificate. - // It is used only when QueueProxyCA is specified. - QueueProxySAN string - - // QueueProxyCertSecret defines the secret name of the server certificates to serve the TLS traffic from activator to queue-proxy. - QueueProxyCertSecret string + // DefaultExternal specifies whether internal traffic is encrypted or not. + InternalEncryption bool } -// HTTPProtocol indicates a type of HTTP endpoint behavior -// that Knative ingress could take. -type HTTPProtocol string - -const ( - // HTTPEnabled represents HTTP protocol is enabled in Knative ingress. - HTTPEnabled HTTPProtocol = "enabled" - - // HTTPDisabled represents HTTP protocol is disabled in Knative ingress. - HTTPDisabled HTTPProtocol = "disabled" - - // HTTPRedirected represents HTTP connection is redirected to HTTPS in Knative ingress. - HTTPRedirected HTTPProtocol = "redirected" -) - -// MeshCompatibilityMode is one of enabled (always use ClusterIP), disabled -// (always use Pod IP), or auto (try PodIP, and fall back to ClusterIP if mesh -// is detected). -type MeshCompatibilityMode string - -const ( - // MeshCompatibilityModeEnabled instructs consumers of network plugins, such as - // Knative Serving, to use ClusterIP when connecting to pods. This is - // required when mesh is enabled (unless EnableMeshPodAddressability is set), - // but is less efficient. - MeshCompatibilityModeEnabled MeshCompatibilityMode = "enabled" - - // MeshCompatibilityModeDisabled instructs consumers of network plugins, such as - // Knative Serving, to connect to individual Pod IPs. This is most efficient, - // but will only work with mesh enabled when EnableMeshPodAddressability is - // used. - MeshCompatibilityModeDisabled MeshCompatibilityMode = "disabled" - - // MeshCompatibilityModeAuto instructs consumers of network plugins, such as - // Knative Serving, to heuristically determine whether to connect using the - // Cluster IP, or to ocnnect to individual Pod IPs. This is most efficient, - // determine whether mesh is enabled, and fall back from Direct Pod IP - // communication to Cluster IP as needed. - MeshCompatibilityModeAuto MeshCompatibilityMode = "auto" -) - func defaultConfig() *Config { return &Config{ DefaultIngressClass: IstioIngressClassName, @@ -386,20 +267,10 @@ func defaultConfig() *Config { AutocreateClusterDomainClaims: false, DefaultExternalScheme: "http", MeshCompatibilityMode: MeshCompatibilityModeAuto, - ActivatorCA: "", - ActivatorSAN: "", - ActivatorCertSecret: "", - QueueProxyCA: "", - QueueProxySAN: "", - QueueProxyCertSecret: "", + InternalEncryption: false, } } -// NewConfigFromConfigMap creates a Config from the supplied ConfigMap -func NewConfigFromConfigMap(configMap *corev1.ConfigMap) (*Config, error) { - return NewConfigFromMap(configMap.Data) -} - // NewConfigFromMap creates a Config from the supplied data. func NewConfigFromMap(data map[string]string) (*Config, error) { nc := defaultConfig() @@ -423,12 +294,7 @@ func NewConfigFromMap(data map[string]string) (*Config, error) { cm.AsBool(AutocreateClusterDomainClaimsKey, &nc.AutocreateClusterDomainClaims), cm.AsBool(EnableMeshPodAddressabilityKey, &nc.EnableMeshPodAddressability), cm.AsString(DefaultExternalSchemeKey, &nc.DefaultExternalScheme), - cm.AsString(ActivatorCAKey, &nc.ActivatorCA), - cm.AsString(ActivatorSANKey, &nc.ActivatorSAN), - cm.AsString(ActivatorCertKey, &nc.ActivatorCertSecret), - cm.AsString(QueueProxyCAKey, &nc.QueueProxyCA), - cm.AsString(QueueProxySANKey, &nc.QueueProxySAN), - cm.AsString(QueueProxyCertKey, &nc.QueueProxyCertSecret), + cm.AsBool(InternalEncryptionKey, &nc.InternalEncryption), asMode(MeshCompatibilityModeKey, &nc.MeshCompatibilityMode), asLabelSelector(NamespaceWildcardCertSelectorKey, &nc.NamespaceWildcardCertSelector), ); err != nil { @@ -485,22 +351,6 @@ func NewConfigFromMap(data map[string]string) (*Config, error) { return nil, fmt.Errorf("httpProtocol %s in config-network ConfigMap is not supported", data[HTTPProtocolKey]) } - if nc.ActivatorCA != "" && nc.ActivatorSAN == "" { - return nil, fmt.Errorf("%q must be set when %q was set", ActivatorSANKey, ActivatorCAKey) - } - - if nc.ActivatorCA == "" && nc.ActivatorSAN != "" { - return nil, fmt.Errorf("%q must be set when %q was set", ActivatorCAKey, ActivatorSANKey) - } - - if nc.QueueProxyCA != "" && nc.QueueProxySAN == "" { - return nil, fmt.Errorf("%q must be set when %q was set", QueueProxySANKey, QueueProxyCAKey) - } - - if nc.QueueProxyCA == "" && nc.QueueProxySAN != "" { - return nil, fmt.Errorf("%q must be set when %q was set", QueueProxyCAKey, QueueProxySANKey) - } - return nc, nil } @@ -571,82 +421,20 @@ func checkTagTemplate(t *template.Template) error { return t.Execute(ioutil.Discard, data) } -// IsKubeletProbe returns true if the request is a Kubernetes probe. -func IsKubeletProbe(r *http.Request) bool { - return strings.HasPrefix(r.Header.Get("User-Agent"), KubeProbeUAPrefix) || - r.Header.Get(KubeletProbeHeaderName) != "" -} - -// KnativeProbeHeader returns the value for key ProbeHeaderName in request headers. -func KnativeProbeHeader(r *http.Request) string { - return r.Header.Get(ProbeHeaderName) -} - -// KnativeProxyHeader returns the value for key ProxyHeaderName in request headers. -func KnativeProxyHeader(r *http.Request) string { - return r.Header.Get(ProxyHeaderName) -} - -// IsProbe returns true if the request is a Kubernetes probe or a Knative probe, -// i.e. non-empty ProbeHeaderName header. -func IsProbe(r *http.Request) bool { - return IsKubeletProbe(r) || KnativeProbeHeader(r) != "" -} - -// RewriteHostIn removes the `Host` header from the inbound (server) request -// and replaces it with our custom header. -// This is done to avoid Istio Host based routing, see #3870. -// Queue-Proxy will execute the reverse process. -func RewriteHostIn(r *http.Request) { - h := r.Host - r.Host = "" - r.Header.Del("Host") - // Don't overwrite an existing OriginalHostHeader. - if r.Header.Get(OriginalHostHeader) == "" { - r.Header.Set(OriginalHostHeader, h) - } -} - -// RewriteHostOut undoes the `RewriteHostIn` action. -// RewriteHostOut checks if network.OriginalHostHeader was set and if it was, -// then uses that as the r.Host (which takes priority over Request.Header["Host"]). -// If the request did not have the OriginalHostHeader header set, the request is untouched. -func RewriteHostOut(r *http.Request) { - if ohh := r.Header.Get(OriginalHostHeader); ohh != "" { - r.Host = ohh - r.Header.Del("Host") - r.Header.Del(OriginalHostHeader) - } -} - -// NameForPortNumber finds the name for a given port as defined by a Service. -func NameForPortNumber(svc *corev1.Service, portNumber int32) (string, error) { - for _, port := range svc.Spec.Ports { - if port.Port == portNumber { - return port.Name, nil - } - } - return "", fmt.Errorf("no port with number %d found", portNumber) -} - -// PortNumberForName resolves a given name to a portNumber as defined by an EndpointSubset. -func PortNumberForName(sub corev1.EndpointSubset, portName string) (int32, error) { - for _, subPort := range sub.Ports { - if subPort.Name == portName { - return subPort.Port, nil +// asLabelSelector returns a LabelSelector extracted from a given configmap key. +func asLabelSelector(key string, target **metav1.LabelSelector) cm.ParseFunc { + return func(data map[string]string) error { + if raw, ok := data[key]; ok { + if len(raw) > 0 { + var selector *metav1.LabelSelector + if err := yaml.Unmarshal([]byte(raw), &selector); err != nil { + return err + } + *target = selector + } } + return nil } - return 0, fmt.Errorf("no port for name %q found", portName) -} - -// IsPotentialMeshErrorResponse returns whether the HTTP response is compatible -// with having been caused by attempting direct connection when mesh was -// enabled. For example if we get a HTTP 404 status code it's safe to assume -// mesh is not enabled even if a probe was otherwise unsuccessful. This is -// useful to avoid falling back to ClusterIP when we see errors which are -// unrelated to mesh being enabled. -func IsPotentialMeshErrorResponse(resp *http.Response) bool { - return resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusBadGateway } // asMode parses the value at key as a MeshCompatibilityMode into the target, if it exists. @@ -663,19 +451,3 @@ func asMode(key string, target *MeshCompatibilityMode) cm.ParseFunc { return nil } } - -// asLabelSelector returns a LabelSelector extracted from a given configmap key. -func asLabelSelector(key string, target **metav1.LabelSelector) cm.ParseFunc { - return func(data map[string]string) error { - if raw, ok := data[key]; ok { - if len(raw) > 0 { - var selector *metav1.LabelSelector - if err := yaml.Unmarshal([]byte(raw), &selector); err != nil { - return err - } - *target = selector - } - } - return nil - } -} diff --git a/vendor/knative.dev/networking/pkg/doc.go b/vendor/knative.dev/networking/pkg/config/doc.go similarity index 93% rename from vendor/knative.dev/networking/pkg/doc.go rename to vendor/knative.dev/networking/pkg/config/doc.go index a0b73a258..4d6130b24 100644 --- a/vendor/knative.dev/networking/pkg/doc.go +++ b/vendor/knative.dev/networking/pkg/config/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2018 The Knative Authors +Copyright 2022 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -17,4 +17,4 @@ limitations under the License. // +k8s:deepcopy-gen=package // Package network holds the typed objects that define the schemas for // configuring the knative/serving networking layer. -package pkg +package config diff --git a/vendor/knative.dev/networking/pkg/zz_generated.deepcopy.go b/vendor/knative.dev/networking/pkg/config/zz_generated.deepcopy.go similarity index 99% rename from vendor/knative.dev/networking/pkg/zz_generated.deepcopy.go rename to vendor/knative.dev/networking/pkg/config/zz_generated.deepcopy.go index 1d2fd6640..276a4b9f8 100644 --- a/vendor/knative.dev/networking/pkg/zz_generated.deepcopy.go +++ b/vendor/knative.dev/networking/pkg/config/zz_generated.deepcopy.go @@ -19,7 +19,7 @@ limitations under the License. // Code generated by deepcopy-gen. DO NOT EDIT. -package pkg +package config import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" diff --git a/vendor/knative.dev/networking/pkg/deprecated_config.go b/vendor/knative.dev/networking/pkg/deprecated_config.go new file mode 100644 index 000000000..50c322d45 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/deprecated_config.go @@ -0,0 +1,213 @@ +/* +Copyright 2022 The Knative 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 pkg + +import ( + corev1 "k8s.io/api/core/v1" + "knative.dev/networking/pkg/config" +) + +const ( + // ConfigName is the name of the configmap containing all + // customizations for networking features. + // + // Deprecated: use knative.dev/networking/pkg/config.ConfigMapName + ConfigName = config.ConfigMapName + + // DefaultDomainTemplate is the default golang template to use when + // constructing the Knative Route's Domain(host) + // + // Deprecated: use knative.dev/networking/pkg/config.DefaultDomainTemplate + DefaultDomainTemplate = config.DefaultDomainTemplate + + // DefaultTagTemplate is the default golang template to use when + // constructing the Knative Route's tag names. + // + // Deprecated: use knative.dev/networking/pkg/config.DefaultTagTemplate + DefaultTagTemplate = config.DefaultTagTemplate + + // DefaultIngressClassKey is the name of the configuration entry + // that specifies the default Ingress. + // + // Deprecated: use knative.dev/networking/pkg/config.DefaultIngressClassKey + DefaultIngressClassKey = config.DefaultIngressClassKey + + // DefaultCertificateClassKey is the name of the configuration entry + // that specifies the default Certificate. + // + // Deprecated: use knative.dev/networking/pkg/config.DefaultCertificateClassKey + DefaultCertificateClassKey = config.DefaultCertificateClassKey + + // IstioIngressClassName value for specifying knative's Istio + // Ingress reconciler. + // + // Deprecated: use knative.dev/networking/pkg/config.IstioIngressClassName + IstioIngressClassName = config.IstioIngressClassName + + // CertManagerCertificateClassName value for specifying Knative's Cert-Manager + // Certificate reconciler. + // + // Deprecated: use knative.dev/networking/pkg/config.CertManagerCertificateClassName + CertManagerCertificateClassName = config.CertManagerCertificateClassName + + // DomainTemplateKey is the name of the configuration entry that + // specifies the golang template string to use to construct the + // Knative service's DNS name. + // + // Deprecated: use knative.dev/networking/pkg/config.DomainTemplateKey + DomainTemplateKey = config.DomainTemplateKey + + // TagTemplateKey is the name of the configuration entry that + // specifies the golang template string to use to construct the + // hostname for a Route's tag. + // + // Deprecated: use knative.dev/networking/pkg/config.TagTemplateKey + TagTemplateKey = config.TagTemplateKey + + // RolloutDurationKey is the name of the configuration entry + // that specifies the default duration of the configuration rollout. + // + // Deprecated: use knative.dev/networking/pkg/config.RolloutDurationKey + RolloutDurationKey = config.RolloutDurationKey + + // NamespaceWildcardCertSelectorKey is the name of the configuration + // entry that specifies a LabelSelector to control which namespaces + // have a wildcard certificate provisioned for them. + // + // Deprecated: use knative.dev/networking/pkg/config.NamespaceWildcardCertSelectorKey + NamespaceWildcardCertSelectorKey = config.NamespaceWildcardCertSelectorKey + + // AutocreateClusterDomainClaimsKey is the key for the + // AutocreateClusterDomainClaims property. + // + // Deprecated: use knative.dev/networking/pkg/config.AutocreateClusterDomainClaimsKey + AutocreateClusterDomainClaimsKey = config.AutocreateClusterDomainClaimsKey + + // AutoTLSKey is the name of the configuration entry + // that specifies enabling auto-TLS or not. + // + // Deprecated: use knative.dev/networking/pkg/config.AutoTLSKey + AutoTLSKey = config.AutoTLSKey + + // HTTPProtocolKey is the name of the configuration entry that + // specifies the HTTP endpoint behavior of Knative ingress. + // + // Deprecated: use knative.dev/networking/pkg/config.HTTPProtocolKey + HTTPProtocolKey = config.HTTPProtocolKey + + // EnableMeshPodAddressabilityKey is the config for enabling pod addressability in mesh. + // + // Deprecated: use knative.dev/networking/pkg/config.EnableMeshPodAddressabilityKey + EnableMeshPodAddressabilityKey = config.EnableMeshPodAddressabilityKey + + // MeshCompatibilityModeKey is the config for selecting the mesh compatibility mode. + // + // Deprecated: use knative.dev/networking/pkg/config.MeshCompatibilityModeKey + MeshCompatibilityModeKey = config.MeshCompatibilityModeKey + + // DefaultExternalSchemeKey is the config for defining the scheme of external URLs. + // + // Deprecated: use knative.dev/networking/pkg/config.DefaultExternalSchemeKey + DefaultExternalSchemeKey = config.DefaultExternalSchemeKey +) + +// DomainTemplateValues are the available properties people can choose from +// in their Route's "DomainTemplate" golang template sting. +// We could add more over time - e.g. RevisionName if we thought that +// might be of interest to people. +// +// Deprecated: use knative.dev/networking/pkg/config.DomainTemplateValues +type DomainTemplateValues = config.DomainTemplateValues + +// TagTemplateValues are the available properties people can choose from +// in their Route's "TagTemplate" golang template sting. +// +// Deprecated: use knative.dev/networking/pkg/config.TagTemplateValues +type TagTemplateValues = config.TagTemplateValues + +// Config contains the networking configuration defined in the +// network config map. +// +// Deprecated: use knative.dev/networking/pkg/config.Config +type Config = config.Config + +// HTTPProtocol indicates a type of HTTP endpoint behavior +// that Knative ingress could take. +// +// Deprecated: use knative.dev/networking/pkg/config.HTTPProtocol +type HTTPProtocol = config.HTTPProtocol + +const ( + // HTTPEnabled represents HTTP protocol is enabled in Knative ingress. + // + // Deprecated: use knative.dev/networking/pkg/config.HTTPEnabled + HTTPEnabled HTTPProtocol = config.HTTPEnabled + + // HTTPDisabled represents HTTP protocol is disabled in Knative ingress. + // + // Deprecated: use knative.dev/networking/pkg/config.HTTPDisabled + HTTPDisabled HTTPProtocol = config.HTTPDisabled + + // HTTPRedirected represents HTTP connection is redirected to HTTPS in Knative ingress. + // + // Deprecated: use knative.dev/networking/pkg/config.HTTPRedirected + HTTPRedirected HTTPProtocol = config.HTTPRedirected +) + +// MeshCompatibilityMode is one of enabled (always use ClusterIP), disabled +// (always use Pod IP), or auto (try PodIP, and fall back to ClusterIP if mesh +// is detected). +// +// Deprecated: use knative.dev/networking/pkg/config.MeshCompatibilityMode +type MeshCompatibilityMode = config.MeshCompatibilityMode + +const ( + // MeshCompatibilityModeEnabled instructs consumers of network plugins, such as + // Knative Serving, to use ClusterIP when connecting to pods. This is + // required when mesh is enabled (unless EnableMeshPodAddressability is set), + // but is less efficient. + // + // Deprecated: Use knative.dev/networking/pkg/config/MeshCompatibilityModeEnabled + MeshCompatibilityModeEnabled MeshCompatibilityMode = config.MeshCompatibilityModeEnabled + + // MeshCompatibilityModeDisabled instructs consumers of network plugins, such as + // Knative Serving, to connect to individual Pod IPs. This is most efficient, + // but will only work with mesh enabled when EnableMeshPodAddressability is + // used. + // + // Deprecated: Use knative.dev/networking/pkg/config/MeshCompatibilityModeDisabled + MeshCompatibilityModeDisabled MeshCompatibilityMode = config.MeshCompatibilityModeDisabled + + // MeshCompatibilityModeAuto instructs consumers of network plugins, such as + // Knative Serving, to heuristically determine whether to connect using the + // Cluster IP, or to ocnnect to individual Pod IPs. This is most efficient, + // determine whether mesh is enabled, and fall back from Direct Pod IP + // communication to Cluster IP as needed. + // + // Deprecated: Use knative.dev/networking/pkg/config/MeshCompatibilityModeAuto + MeshCompatibilityModeAuto MeshCompatibilityMode = config.MeshCompatibilityModeAuto +) + +// NewConfigFromConfigMap creates a Config from the supplied ConfigMap +func NewConfigFromConfigMap(configMap *corev1.ConfigMap) (*Config, error) { + return NewConfigFromMap(configMap.Data) +} + +// NewConfigFromMap creates a Config from the supplied data. +// +// Deprecated: Use knative.dev/networking/pkg/config/NewConfigFromMap +var NewConfigFromMap = config.NewConfigFromMap diff --git a/vendor/knative.dev/networking/pkg/deprecated_header.go b/vendor/knative.dev/networking/pkg/deprecated_header.go new file mode 100644 index 000000000..c2e98c2c3 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/deprecated_header.go @@ -0,0 +1,167 @@ +/* +Copyright 2022 The Knative 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 pkg + +import ( + "knative.dev/networking/pkg/http/header" +) + +const ( + // ProbeHeaderName is the name of a header that can be added to + // requests to probe the knative networking layer. Requests + // with this header will not be passed to the user container or + // included in request metrics. + // + // Deprecated: use knative.dev/networking/pkg/http/header.ProbeKey + ProbeHeaderName = header.ProbeKey + + // ProxyHeaderName is the name of an internal header that activator + // uses to mark requests going through it. + // + // Deprecated: use knative.dev/networking/pkg/http/header.ProxyKey + ProxyHeaderName = header.ProxyKey + + // HashHeaderName is the name of an internal header that Ingress controller + // uses to find out which version of the networking config is deployed. + // + // Deprecated: use knative.dev/networking/pkg/http/header.HashKey + HashHeaderName = header.HashKey + + // HashHeaderValue is the value that must appear in the HashHeaderName + // header in order for our network hash to be injected. + // + // Deprecated: use knative.dev/networking/pkg/http/header.HashValueOverride + HashHeaderValue = header.HashValueOverride + + // OriginalHostHeader is used to avoid Istio host based routing rules + // in Activator. + // The header contains the original Host value that can be rewritten + // at the Queue proxy level back to be a host header. + // + // Deprecated: use knative.dev/networking/pkg/http/header.OriginalHostKey + OriginalHostHeader = header.OriginalHostKey + + // KubeProbeUAPrefix is the user agent prefix of the probe. + // Since K8s 1.8, prober requests have + // User-Agent = "kube-probe/{major-version}.{minor-version}". + // + // Deprecated: use knative.dev/networking/pkg/http/header.KubeProbeUAPrefix + KubeProbeUAPrefix = header.KubeProbeUAPrefix + + // KubeletProbeHeaderName is the name of the header supplied by kubelet + // probes. Istio with mTLS rewrites probes, but their probes pass a + // different user-agent. So we augment the probes with this header. + // + // Deprecated: use knative.dev/networking/pkg/http/header.KubeletProbeKey + KubeletProbeHeaderName = header.KubeletProbeKey + + // UserAgentKey is the constant for header "User-Agent". + // + // Deprecated: use knative.dev/networking/pkg/http/header.UserAgentKey + UserAgentKey = header.UserAgentKey + + // ActivatorUserAgent is the user-agent header value set in probe requests sent + // from activator. + // + // Deprecated: use knative.dev/networking/pkg/http/header.ActivatorUserAgent + ActivatorUserAgent = header.ActivatorUserAgent + + // QueueProxyUserAgent is the user-agent header value set in probe requests sent + // from queue-proxy. + // + // Deprecated: use knative.dev/networking/pkg/http/header.QueueProxyUserAgent + QueueProxyUserAgent = header.QueueProxyUserAgent + + // IngressReadinessUserAgent is the user-agent header value + // set in probe requests for Ingress status. + // + // Deprecated: use knative.dev/networking/pkg/http/header.IngressReadinessUserAgent + IngressReadinessUserAgent = header.IngressReadinessUserAgent + + // AutoscalingUserAgent is the user-agent header value set in probe + // requests sent by autoscaling implementations. + // + // Deprecated: use knative.dev/networking/pkg/http/header.AutoscalingUserAgent + AutoscalingUserAgent = header.AutoscalingUserAgent + + // TagHeaderName is the name of the header entry which has a tag name as value. + // The tag name specifies which route was expected to be chosen by Ingress. + // + // Deprecated: use knative.dev/networking/pkg/http/header.RouteTagKey + TagHeaderName = header.RouteTagKey + + // DefaultRouteHeaderName is the name of the header entry + // identifying whether a request is routed via the default route or not. + // It has one of the string value "true" or "false". + // + // Deprecated: use knative.dev/networking/pkg/http/header.DefaultRouteKey + DefaultRouteHeaderName = header.DefaultRouteKey + + // PassthroughLoadbalancingHeaderName is the name of the header that directs + // load balancers to not load balance the respective request but to + // send it to the request's target directly. + // + // Deprecated: use knative.dev/networking/pkg/http/header.PassthroughLoadbalancingKey + PassthroughLoadbalancingHeaderName = header.PassthroughLoadbalancingKey + + // ProtoAcceptContent is the content type to be used when autoscaler scrapes metrics from the QP + // + // Deprecated: use knative.dev/networking/pkg/http/header.ProtobufMIMEType + ProtoAcceptContent = header.ProtobufMIMEType + + // ProbeHeaderValue is the value used in 'K-Network-Probe' + // + // Deprecated: use knative.dev/networking/pkg/http/header.ProbeValue + ProbeHeaderValue = header.ProbeValue +) + +// IsKubeletProbe returns true if the request is a Kubernetes probe. +// +// Deprecated: use knative.dev/networking/pkg/http/header.IsKubeletProbe +var IsKubeletProbe = header.IsKubeletProbe + +// KnativeProbeHeader returns the value for key ProbeHeaderName in request headers. +// +// Deprecated: use knative.dev/networking/pkg/http/header.GetKnativeProbeValue +var KnativeProbeHeader = header.GetKnativeProbeValue + +// KnativeProxyHeader returns the value for key ProxyHeaderName in request headers. +// +// Deprecated: use knative.dev/networking/pkg/http/header.GetKnativeProxyValue +var KnativeProxyHeader = header.GetKnativeProxyValue + +// IsProbe returns true if the request is a Kubernetes probe or a Knative probe, +// i.e. non-empty ProbeHeaderName header. +// +// Deprecated: use knative.dev/networking/pkg/http/header.IsProbe +var IsProbe = header.IsProbe + +// RewriteHostIn removes the `Host` header from the inbound (server) request +// and replaces it with our custom header. +// This is done to avoid Istio Host based routing, see #3870. +// Queue-Proxy will execute the reverse process. +// +// Deprecated: use knative.dev/networking/pkg/http/header.RewriteHostIn +var RewriteHostIn = header.RewriteHostIn + +// RewriteHostOut undoes the `RewriteHostIn` action. +// RewriteHostOut checks if network.OriginalHostHeader was set and if it was, +// then uses that as the r.Host (which takes priority over Request.Header["Host"]). +// If the request did not have the OriginalHostHeader header set, the request is untouched. +// +// Deprecated: use knative.dev/networking/pkg/http/header.RewriteHostOut +var RewriteHostOut = header.RewriteHostOut diff --git a/vendor/knative.dev/networking/pkg/deprecated_http.go b/vendor/knative.dev/networking/pkg/deprecated_http.go new file mode 100644 index 000000000..ad4000526 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/deprecated_http.go @@ -0,0 +1,116 @@ +/* +Copyright 2018 The Knative 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 pkg + +import ( + "knative.dev/networking/pkg/http" + "knative.dev/networking/pkg/http/probe" + "knative.dev/networking/pkg/http/proxy" + "knative.dev/networking/pkg/http/stats" +) + +const ( + // ProbePath is the name of a path that activator, autoscaler and + // prober(used by KIngress generally) use for health check. + // + // Deprecated: use knative.dev/networking/pkg/http.HealthCheckPath + ProbePath = http.HealthCheckPath + + // FlushInterval controls the time when we flush the connection in the + // reverse proxies (Activator, QP). + // As of go1.16, a FlushInterval of 0 (the default) still flushes immediately + // when Content-Length is -1, which means the default works properly for + // streaming/websockets, without flushing more often than necessary for + // non-streaming requests. + // + // Deprecated: use knative.dev/networking/pkg/http/proxy.FlushInterval + FlushInterval = proxy.FlushInterval +) + +type ( + // ReqEvent represents either an incoming or closed request. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ReqEvent + ReqEvent = stats.ReqEvent + + // ReqEventType denotes the type (incoming/closed) of a ReqEvent. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ReqEventType + ReqEventType = stats.ReqEventType + + // RequestStats collects statistics about requests as they flow in and out of the system. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.RequestStats + RequestStats = stats.RequestStats + + // RequestStatsReport are the metrics reported from the the request stats collector + // at a given time. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.RequestStatsReport + RequestStatsReport = stats.RequestStatsReport +) + +const ( + // ReqIn represents an incoming request + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ReqIn + ReqIn = stats.ReqIn + + // ReqOut represents a finished request + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ReqOut + ReqOut = stats.ReqOut + + // ProxiedIn represents an incoming request through a proxy. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ProxiedIn + ProxiedIn = stats.ProxiedIn + + // ProxiedOut represents a finished proxied request. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.ProxiedOut + ProxiedOut = stats.ProxiedOut +) + +var ( + // NewRequestStats builds a RequestStats instance, started at the given time. + // + // Deprecated: use knative.dev/networking/pkg/http/stats.NewRequestStats + NewRequestStats = stats.NewRequestStats + + // NewBufferPool creates a new BufferPool. This is only safe to use in the context + // of a httputil.ReverseProxy, as the buffers returned via Put are not cleaned + // explicitly. + // + // Deprecated: use knative.dev/networking/pkg/http/proxy.NewBufferPool + NewBufferPool = proxy.NewBufferPool + + // NewProbeHandler wraps a HTTP handler handling probing requests around the provided HTTP handler + // + // Deprecated: use knative.dev/networking/pkg/http/probe.NewHandler + NewProbeHandler = probe.NewHandler + + // IsPotentialMeshErrorResponse returns whether the HTTP response is compatible + // with having been caused by attempting direct connection when mesh was + // enabled. For example if we get a HTTP 404 status code it's safe to assume + // mesh is not enabled even if a probe was otherwise unsuccessful. This is + // useful to avoid falling back to ClusterIP when we see errors which are + // unrelated to mesh being enabled. + // + // Deprecated: use knative.dev/networking/pkg/http.IsPotentialMeshErrorResponse + IsPotentialMeshErrorResponse = http.IsPotentialMeshErrorResponse +) diff --git a/vendor/knative.dev/networking/pkg/deprecated_labels.go b/vendor/knative.dev/networking/pkg/deprecated_labels.go new file mode 100644 index 000000000..0a70ca18b --- /dev/null +++ b/vendor/knative.dev/networking/pkg/deprecated_labels.go @@ -0,0 +1,29 @@ +/* +Copyright 2022 The Knative 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 pkg + +import "knative.dev/networking/pkg/apis/networking" + +const ( + // VisibilityLabelKey is the label to indicate visibility of Route + // and KServices. It can be an annotation too but since users are + // already using labels for domain, it probably best to keep this + // consistent. + // + // Deprecated: use knative.dev/networking/pkg/apis/networking.VisibilityLabelKey + VisibilityLabelKey = networking.VisibilityLabelKey +) diff --git a/vendor/knative.dev/networking/pkg/deprecated_port.go b/vendor/knative.dev/networking/pkg/deprecated_port.go new file mode 100644 index 000000000..8b218289c --- /dev/null +++ b/vendor/knative.dev/networking/pkg/deprecated_port.go @@ -0,0 +1,29 @@ +/* +Copyright 2022 The Knative 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 pkg + +import "knative.dev/networking/pkg/k8s" + +// NameForPortNumber finds the name for a given port as defined by a Service. +// +// Deprecated: use knative.dev/networking/pkg/k8s.NameForPortNumber +var NameForPortNumber = k8s.NameForPortNumber + +// PortNumberForName resolves a given name to a portNumber as defined by an EndpointSubset. +// +// Deprecated: use knative.dev/networking/pkg/k8s.PortNumberForName +var PortNumberForName = k8s.PortNumberForName diff --git a/vendor/knative.dev/networking/pkg/http/constants.go b/vendor/knative.dev/networking/pkg/http/constants.go new file mode 100644 index 000000000..4012153de --- /dev/null +++ b/vendor/knative.dev/networking/pkg/http/constants.go @@ -0,0 +1,23 @@ +/* +Copyright 2022 The Knative 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 http + +const ( + // HealthCheckPath is the name of a path that activator, autoscaler and + // prober(used by KIngress generally) use for health check. + HealthCheckPath = "/healthz" +) diff --git a/vendor/knative.dev/networking/pkg/http/error.go b/vendor/knative.dev/networking/pkg/http/error.go new file mode 100644 index 000000000..93878f330 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/http/error.go @@ -0,0 +1,29 @@ +/* +Copyright 2022 The Knative 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 http + +import "net/http" + +// IsPotentialMeshErrorResponse returns whether the HTTP response is compatible +// with having been caused by attempting direct connection when mesh was +// enabled. For example if we get a HTTP 404 status code it's safe to assume +// mesh is not enabled even if a probe was otherwise unsuccessful. This is +// useful to avoid falling back to ClusterIP when we see errors which are +// unrelated to mesh being enabled. +func IsPotentialMeshErrorResponse(resp *http.Response) bool { + return resp.StatusCode == http.StatusServiceUnavailable || resp.StatusCode == http.StatusBadGateway +} diff --git a/vendor/knative.dev/networking/pkg/http/header/header.go b/vendor/knative.dev/networking/pkg/http/header/header.go new file mode 100644 index 000000000..158fb0620 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/http/header/header.go @@ -0,0 +1,157 @@ +/* +Copyright 2022 The Knative 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 header + +import ( + "net/http" + "strings" +) + +// HashKey & Values +const ( + // HashKey is the name of an internal header that Ingress controller + // uses to find out which version of the networking config is deployed. + HashKey = "K-Network-Hash" + + // HashValueOverride is the value that must appear in the HashHeaderKey + // header in order for our network hash to be injected. + HashValueOverride = "override" +) + +// ProbeKey & Values +const ( + // ProbeKey is the name of a header that can be added to + // requests to probe the knative networking layer. Requests + // with this header will not be passed to the user container or + // included in request metrics. + ProbeKey = "K-Network-Probe" + + // ProbeValue is the value used in 'K-Network-Probe' + ProbeValue = "probe" +) + +const ( + // ProxyKey is the name of an internal header that activator + // uses to mark requests going through it. + ProxyKey = "K-Proxy-Request" + + // OriginalHostKey is used to avoid Istio host based routing rules + // in Activator. + // The header contains the original Host value that can be rewritten + // at the Queue proxy level back to be a host header. + OriginalHostKey = "K-Original-Host" + + // KubeletProbeKey is the name of the header supplied by kubelet + // probes. Istio with mTLS rewrites probes, but their probes pass a + // different user-agent. So we augment the probes with this header. + KubeletProbeKey = "K-Kubelet-Probe" + + // RouteTagKey is the name of the header entry which has a tag name as value. + // The tag name specifies which route was expected to be chosen by Ingress. + RouteTagKey = "Knative-Serving-Tag" + + // DefaultRouteKey is the name of the header entry + // identifying whether a request is routed via the default route or not. + // It has one of the string value "true" or "false". + DefaultRouteKey = "Knative-Serving-Default-Route" + + // PassthroughLoadbalancingKey is the name of the header that directs + // load balancers to not load balance the respective request but to + // send it to the request's target directly. + PassthroughLoadbalancingKey = "K-Passthrough-Lb" +) + +// User Agent Key & Values +const ( + // UserAgentKey is the constant for header "User-Agent". + UserAgentKey = "User-Agent" + + // KubeProbeUAPrefix is the user agent prefix of the probe. + // Since K8s 1.8, prober requests have + // User-Agent = "kube-probe/{major-version}.{minor-version}". + KubeProbeUAPrefix = "kube-probe/" + + // ActivatorUserAgent is the user-agent header value set in probe requests sent + // from activator. + ActivatorUserAgent = "Knative-Activator-Probe" + + // QueueProxyUserAgent is the user-agent header value set in probe requests sent + // from queue-proxy. + QueueProxyUserAgent = "Knative-Queue-Proxy-Probe" + + // IngressReadinessUserAgent is the user-agent header value + // set in probe requests for Ingress status. + IngressReadinessUserAgent = "Knative-Ingress-Probe" + + // AutoscalingUserAgent is the user-agent header value set in probe + // requests sent by autoscaling implementations. + AutoscalingUserAgent = "Knative-Autoscaling-Probe" +) + +// Accept Content Values +const ( + // ProtobufMIMEType is a content type to be used when autoscaler scrapes metrics from the QP + ProtobufMIMEType = "application/protobuf" +) + +// KnativeProbeHeader returns the value for key ProbeHeaderName in request headers. +func GetKnativeProbeValue(r *http.Request) string { + return r.Header.Get(ProbeKey) +} + +// KnativeProxyHeader returns the value for key ProxyHeaderName in request headers. +func GetKnativeProxyValue(r *http.Request) string { + return r.Header.Get(ProxyKey) +} + +// IsProbe returns true if the request is a Kubernetes probe or a Knative probe, +// i.e. non-empty ProbeHeaderName header. +func IsProbe(r *http.Request) bool { + return IsKubeletProbe(r) || GetKnativeProbeValue(r) != "" +} + +// IsKubeletProbe returns true if the request is a Kubernetes probe. +func IsKubeletProbe(r *http.Request) bool { + return strings.HasPrefix(r.Header.Get("User-Agent"), KubeProbeUAPrefix) || + r.Header.Get(KubeletProbeKey) != "" +} + +// RewriteHostIn removes the `Host` header from the inbound (server) request +// and replaces it with our custom header. +// This is done to avoid Istio Host based routing, see #3870. +// Queue-Proxy will execute the reverse process. +func RewriteHostIn(r *http.Request) { + h := r.Host + r.Host = "" + r.Header.Del("Host") + // Don't overwrite an existing OriginalHostHeader. + if r.Header.Get(OriginalHostKey) == "" { + r.Header.Set(OriginalHostKey, h) + } +} + +// RewriteHostOut undoes the `RewriteHostIn` action. +// RewriteHostOut checks if network.OriginalHostHeader was set and if it was, +// then uses that as the r.Host (which takes priority over Request.Header["Host"]). +// If the request did not have the OriginalHostHeader header set, the request is untouched. +func RewriteHostOut(r *http.Request) { + if ohh := r.Header.Get(OriginalHostKey); ohh != "" { + r.Host = ohh + r.Header.Del("Host") + r.Header.Del(OriginalHostKey) + } +} diff --git a/vendor/knative.dev/networking/pkg/probe_handler.go b/vendor/knative.dev/networking/pkg/http/probe/handler.go similarity index 63% rename from vendor/knative.dev/networking/pkg/probe_handler.go rename to vendor/knative.dev/networking/pkg/http/probe/handler.go index 3283ef197..c1d86b93a 100644 --- a/vendor/knative.dev/networking/pkg/probe_handler.go +++ b/vendor/knative.dev/networking/pkg/http/probe/handler.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2022 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,39 +14,38 @@ See the License for the specific language governing permissions and limitations under the License. */ -package pkg +package probe import ( "fmt" "net/http" -) -// ProbeHeaderValue is the value used in 'K-Network-Probe' -var ProbeHeaderValue = "probe" + "knative.dev/networking/pkg/http/header" +) type handler struct { next http.Handler } -// NewProbeHandler wraps a HTTP handler handling probing requests around the provided HTTP handler -func NewProbeHandler(next http.Handler) http.Handler { +// NewHandler wraps a HTTP handler handling probing requests around the provided HTTP handler +func NewHandler(next http.Handler) http.Handler { return &handler{next: next} } // ServeHTTP handles probing requests func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - if ph := r.Header.Get(ProbeHeaderName); ph != ProbeHeaderValue { - r.Header.Del(HashHeaderName) + if ph := r.Header.Get(header.ProbeKey); ph != header.ProbeValue { + r.Header.Del(header.HashKey) h.next.ServeHTTP(w, r) return } - hh := r.Header.Get(HashHeaderName) + hh := r.Header.Get(header.HashKey) if hh == "" { - http.Error(w, fmt.Sprintf("a probe request must contain a non-empty %q header", HashHeaderName), http.StatusBadRequest) + http.Error(w, fmt.Sprintf("a probe request must contain a non-empty %q header", header.HashKey), http.StatusBadRequest) return } - w.Header().Set(HashHeaderName, hh) + w.Header().Set(header.HashKey, hh) w.WriteHeader(http.StatusOK) } diff --git a/vendor/knative.dev/networking/pkg/bufferpool.go b/vendor/knative.dev/networking/pkg/http/proxy/bufferpool.go similarity index 96% rename from vendor/knative.dev/networking/pkg/bufferpool.go rename to vendor/knative.dev/networking/pkg/http/proxy/bufferpool.go index de257f059..80d81f5da 100644 --- a/vendor/knative.dev/networking/pkg/bufferpool.go +++ b/vendor/knative.dev/networking/pkg/http/proxy/bufferpool.go @@ -5,7 +5,7 @@ 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 - https://www.apache.org/licenses/LICENSE-2.0 + 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, @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package pkg +package proxy import ( "net/http/httputil" diff --git a/vendor/knative.dev/networking/pkg/http/proxy/constants.go b/vendor/knative.dev/networking/pkg/http/proxy/constants.go new file mode 100644 index 000000000..8d43e4425 --- /dev/null +++ b/vendor/knative.dev/networking/pkg/http/proxy/constants.go @@ -0,0 +1,28 @@ +/* +Copyright 2022 The Knative 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 proxy + +const ( + + // FlushInterval controls the time when we flush the connection in the + // reverse proxies (Activator, QP). + // As of go1.16, a FlushInterval of 0 (the default) still flushes immediately + // when Content-Length is -1, which means the default works properly for + // streaming/websockets, without flushing more often than necessary for + // non-streaming requests. + FlushInterval = 0 +) diff --git a/vendor/knative.dev/networking/pkg/stats.go b/vendor/knative.dev/networking/pkg/http/stats/request.go similarity index 97% rename from vendor/knative.dev/networking/pkg/stats.go rename to vendor/knative.dev/networking/pkg/http/stats/request.go index a42515ffc..0fee36177 100644 --- a/vendor/knative.dev/networking/pkg/stats.go +++ b/vendor/knative.dev/networking/pkg/http/stats/request.go @@ -5,7 +5,7 @@ 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 - https://www.apache.org/licenses/LICENSE-2.0 + 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, @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package pkg +package stats import ( "sync" @@ -24,7 +24,6 @@ import ( ) // ReqEvent represents either an incoming or closed request. -// +k8s:deepcopy-gen=false type ReqEvent struct { // Time is the time the request event happened. Time time.Time @@ -55,7 +54,6 @@ func NewRequestStats(startedAt time.Time) *RequestStats { } // RequestStats collects statistics about requests as they flow in and out of the system. -// +k8s:deepcopy-gen=false type RequestStats struct { mux sync.Mutex @@ -72,7 +70,6 @@ type RequestStats struct { // RequestStatsReport are the metrics reported from the the request stats collector // at a given time. -// +k8s:deepcopy-gen=false type RequestStatsReport struct { // AverageConcurrency is the average concurrency over the reporting timeframe. // This is calculated via the utilization at a given concurrency. For example: diff --git a/vendor/knative.dev/networking/pkg/ingress/ingress.go b/vendor/knative.dev/networking/pkg/ingress/ingress.go index 843f8c7c7..e0a946694 100644 --- a/vendor/knative.dev/networking/pkg/ingress/ingress.go +++ b/vendor/knative.dev/networking/pkg/ingress/ingress.go @@ -23,8 +23,8 @@ import ( "strings" "k8s.io/apimachinery/pkg/util/sets" - net "knative.dev/networking/pkg" "knative.dev/networking/pkg/apis/networking/v1alpha1" + "knative.dev/networking/pkg/http/header" "knative.dev/pkg/network" ) @@ -61,8 +61,8 @@ func InsertProbe(ing *v1alpha1.Ingress) (string, error) { if elt.Headers == nil { elt.Headers = make(map[string]v1alpha1.HeaderMatch, 1) } - elt.Headers[net.HashHeaderName] = v1alpha1.HeaderMatch{Exact: net.HashHeaderValue} - elt.AppendHeaders[net.HashHeaderName] = hash + elt.Headers[header.HashKey] = v1alpha1.HeaderMatch{Exact: header.HashValueOverride} + elt.AppendHeaders[header.HashKey] = hash probePaths = append(probePaths, *elt) } rule.HTTP.Paths = append(probePaths, rule.HTTP.Paths...) diff --git a/vendor/knative.dev/networking/pkg/k8s/ports.go b/vendor/knative.dev/networking/pkg/k8s/ports.go new file mode 100644 index 000000000..265a6b86b --- /dev/null +++ b/vendor/knative.dev/networking/pkg/k8s/ports.go @@ -0,0 +1,43 @@ +/* +Copyright 2022 The Knative 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 k8s + +import ( + "fmt" + + corev1 "k8s.io/api/core/v1" +) + +// NameForPortNumber finds the name for a given port as defined by a Service. +func NameForPortNumber(svc *corev1.Service, portNumber int32) (string, error) { + for _, port := range svc.Spec.Ports { + if port.Port == portNumber { + return port.Name, nil + } + } + return "", fmt.Errorf("no port with number %d found", portNumber) +} + +// PortNumberForName resolves a given name to a portNumber as defined by an EndpointSubset. +func PortNumberForName(sub corev1.EndpointSubset, portName string) (int32, error) { + for _, subPort := range sub.Ports { + if subPort.Name == portName { + return subPort.Port, nil + } + } + return 0, fmt.Errorf("no port for name %q found", portName) +} diff --git a/vendor/knative.dev/networking/pkg/status/status.go b/vendor/knative.dev/networking/pkg/status/status.go index 1084444f5..815382a90 100644 --- a/vendor/knative.dev/networking/pkg/status/status.go +++ b/vendor/knative.dev/networking/pkg/status/status.go @@ -37,8 +37,9 @@ import ( "k8s.io/apimachinery/pkg/util/sets" "k8s.io/client-go/util/workqueue" - network "knative.dev/networking/pkg" "knative.dev/networking/pkg/apis/networking/v1alpha1" + nethttp "knative.dev/networking/pkg/http" + "knative.dev/networking/pkg/http/header" "knative.dev/networking/pkg/ingress" "knative.dev/networking/pkg/prober" "knative.dev/pkg/kmeta" @@ -376,7 +377,7 @@ func (m *Prober) processWorkItem() bool { } probeURL := deepCopy(item.url) - probeURL.Path = path.Join(probeURL.Path, network.ProbePath) + probeURL.Path = path.Join(probeURL.Path, nethttp.HealthCheckPath) ctx, cancel := context.WithTimeout(item.context, probeTimeout) defer cancel() @@ -384,9 +385,9 @@ func (m *Prober) processWorkItem() bool { ctx, transport, probeURL.String(), - prober.WithHeader(network.UserAgentKey, network.IngressReadinessUserAgent), - prober.WithHeader(network.ProbeHeaderName, network.ProbeHeaderValue), - prober.WithHeader(network.HashHeaderName, network.HashHeaderValue), + prober.WithHeader(header.UserAgentKey, header.IngressReadinessUserAgent), + prober.WithHeader(header.ProbeKey, header.ProbeValue), + prober.WithHeader(header.HashKey, header.HashValueOverride), m.probeVerifier(item)) // In case of cancellation, drop the work item @@ -452,11 +453,11 @@ func (m *Prober) probeVerifier(item *workItem) prober.Verifier { // actually is Ready than never marking it as Ready. It is best effort. switch r.StatusCode { case http.StatusOK: - hash := r.Header.Get(network.HashHeaderName) + hash := r.Header.Get(header.HashKey) switch hash { case "": item.logger.Errorf("Probing of %s abandoned, IP: %s:%s: the response doesn't contain the %q header", - item.url, item.podIP, item.podPort, network.HashHeaderName) + item.url, item.podIP, item.podPort, header.HashKey) return true, nil case item.ingressState.hash: return true, nil diff --git a/vendor/knative.dev/networking/test/conformance/ingress/headers.go b/vendor/knative.dev/networking/test/conformance/ingress/headers.go index aed710eea..148bb1fbc 100644 --- a/vendor/knative.dev/networking/test/conformance/ingress/headers.go +++ b/vendor/knative.dev/networking/test/conformance/ingress/headers.go @@ -25,9 +25,9 @@ import ( "github.com/google/go-cmp/cmp" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/apimachinery/pkg/util/sets" - network "knative.dev/networking/pkg" "knative.dev/networking/pkg/apis/networking" "knative.dev/networking/pkg/apis/networking/v1alpha1" + "knative.dev/networking/pkg/http/header" "knative.dev/networking/pkg/ingress" "knative.dev/networking/test" "knative.dev/pkg/ptr" @@ -70,7 +70,7 @@ func TestProbeHeaders(t *testing.T) { want string }{{ name: "kingress generates hash", - req: network.HashHeaderValue, + req: header.HashValueOverride, want: fmt.Sprintf("%x", bytes), }, { name: "request overrides hash", @@ -87,8 +87,8 @@ func TestProbeHeaders(t *testing.T) { ros = append(ros, func(r *http.Request) { // Add the header to indicate this is a probe request. - r.Header.Set(network.ProbeHeaderName, network.ProbeHeaderValue) - r.Header.Set(network.HashHeaderName, tt.req) + r.Header.Set(header.ProbeKey, header.ProbeValue) + r.Header.Set(header.HashKey, tt.req) }) ri := RuntimeRequest(ctx, t, client, "http://"+name+".example.com", ros...) @@ -97,8 +97,8 @@ func TestProbeHeaders(t *testing.T) { return } - if got, want := ri.Request.Headers.Get(network.HashHeaderName), tt.want; got != want { - t.Errorf("Header[%q] = %q, wanted %q", network.HashHeaderName, got, want) + if got, want := ri.Request.Headers.Get(header.HashKey), tt.want; got != want { + t.Errorf("Header[%q] = %q, wanted %q", header.HashKey, got, want) } }) } @@ -129,7 +129,7 @@ func TestTagHeaders(t *testing.T) { HTTP: &v1alpha1.HTTPIngressRuleValue{ Paths: []v1alpha1.HTTPIngressPath{{ Headers: map[string]v1alpha1.HeaderMatch{ - network.TagHeaderName: { + header.RouteTagKey: { Exact: tagName, }, }, @@ -191,7 +191,7 @@ func TestTagHeaders(t *testing.T) { if tt.TagHeader != nil { ros = append(ros, func(r *http.Request) { - r.Header.Set(network.TagHeaderName, *tt.TagHeader) + r.Header.Set(header.RouteTagKey, *tt.TagHeader) }) } diff --git a/vendor/knative.dev/networking/test/conformance/ingress/util.go b/vendor/knative.dev/networking/test/conformance/ingress/util.go index e7b5ed868..c99dc90fe 100644 --- a/vendor/knative.dev/networking/test/conformance/ingress/util.go +++ b/vendor/knative.dev/networking/test/conformance/ingress/util.go @@ -985,7 +985,8 @@ func CreateTLSSecret(ctx context.Context, t *testing.T, clients *test.Clients, h Name: name, Namespace: test.ServingNamespace, Labels: map[string]string{ - "test-secret": name, + "test-secret": name, + networking.CertificateUIDLabelKey: "test-uid", }, }, Type: corev1.SecretTypeTLS, diff --git a/vendor/knative.dev/networking/test/e2e_flags.go b/vendor/knative.dev/networking/test/e2e_flags.go index 4030c1428..ac8f144e4 100644 --- a/vendor/knative.dev/networking/test/e2e_flags.go +++ b/vendor/knative.dev/networking/test/e2e_flags.go @@ -22,7 +22,7 @@ package test import ( "flag" - network "knative.dev/networking/pkg" + "knative.dev/networking/pkg/config" ) // NetworkingFlags holds the flags or defaults for knative/networking settings in the user's environment. @@ -62,12 +62,12 @@ func initializeNetworkingFlags() *NetworkingEnvironmentFlags { flag.StringVar(&f.IngressClass, "ingressClass", - network.IstioIngressClassName, + config.IstioIngressClassName, "Set this flag to the ingress class to test against.") flag.StringVar(&f.CertificateClass, "certificateClass", - network.CertManagerCertificateClassName, + config.CertManagerCertificateClassName, "Set this flag to the certificate class to test against.") flag.IntVar(&f.Buckets, diff --git a/vendor/knative.dev/networking/test/test_images/grpc-ping/main.go b/vendor/knative.dev/networking/test/test_images/grpc-ping/main.go index d3faa7874..aba0f237b 100644 --- a/vendor/knative.dev/networking/test/test_images/grpc-ping/main.go +++ b/vendor/knative.dev/networking/test/test_images/grpc-ping/main.go @@ -28,7 +28,7 @@ import ( "google.golang.org/grpc" - networkingpkg "knative.dev/networking/pkg" + "knative.dev/networking/pkg/http/probe" ping "knative.dev/networking/test/test_images/grpc-ping/proto" "knative.dev/pkg/network" ) @@ -82,7 +82,7 @@ func (s *server) PingStream(stream ping.PingService_PingStreamServer) error { } func httpWrapper(g *grpc.Server) http.Handler { - return networkingpkg.NewProbeHandler( + return probe.NewHandler( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.ProtoMajor == 2 && r.Header.Get("Content-Type") == "application/grpc" { g.ServeHTTP(w, r) diff --git a/vendor/knative.dev/networking/test/test_images/httpproxy/httpproxy.go b/vendor/knative.dev/networking/test/test_images/httpproxy/httpproxy.go index 08b0c247f..db25c2c87 100644 --- a/vendor/knative.dev/networking/test/test_images/httpproxy/httpproxy.go +++ b/vendor/knative.dev/networking/test/test_images/httpproxy/httpproxy.go @@ -28,7 +28,7 @@ import ( "net/url" "github.com/rs/dnscache" - network "knative.dev/networking/pkg" + "knative.dev/networking/pkg/http/probe" "knative.dev/networking/test" ) @@ -85,7 +85,7 @@ func main() { proxy.ServeHTTP(w, r) }) // Handle forwarding requests which uses "K-Network-Hash" header. - handler = network.NewProbeHandler(handler).ServeHTTP + handler = probe.NewHandler(handler).ServeHTTP address := ":" + port diff --git a/vendor/knative.dev/networking/test/test_images/retry/main.go b/vendor/knative.dev/networking/test/test_images/retry/main.go index 263ff97e5..1d32aef72 100644 --- a/vendor/knative.dev/networking/test/test_images/retry/main.go +++ b/vendor/knative.dev/networking/test/test_images/retry/main.go @@ -22,7 +22,7 @@ import ( "net/http" "os" - network "knative.dev/networking/pkg" + "knative.dev/networking/pkg/http/probe" "knative.dev/networking/test" ) @@ -38,7 +38,7 @@ func handler(w http.ResponseWriter, r *http.Request) { } func main() { - h := network.NewProbeHandler(http.HandlerFunc(handler)) + h := probe.NewHandler(http.HandlerFunc(handler)) port := os.Getenv("PORT") if cert, key := os.Getenv("CERT"), os.Getenv("KEY"); cert != "" && key != "" { log.Print("Server starting on port with TLS ", port) diff --git a/vendor/knative.dev/networking/test/test_images/runtime/handlers/handler.go b/vendor/knative.dev/networking/test/test_images/runtime/handlers/handler.go index 9189b96a5..9c96b9ede 100644 --- a/vendor/knative.dev/networking/test/test_images/runtime/handlers/handler.go +++ b/vendor/knative.dev/networking/test/test_images/runtime/handlers/handler.go @@ -23,15 +23,17 @@ import ( "net/http/httputil" "strings" - network "knative.dev/networking/pkg" + nethttp "knative.dev/networking/pkg/http" + "knative.dev/networking/pkg/http/probe" + "knative.dev/pkg/network" ) // InitHandlers initializes all handlers. func InitHandlers(mux *http.ServeMux) { mux.HandleFunc("/", withHeaders(withRequestLog(runtimeHandler))) - h := network.NewProbeHandler(withRequestLog(withKubeletProbeHeaderCheck)) - mux.HandleFunc(network.ProbePath, h.ServeHTTP) + h := probe.NewHandler(withRequestLog(withKubeletProbeHeaderCheck)) + mux.HandleFunc(nethttp.HealthCheckPath, h.ServeHTTP) } // withRequestLog logs each request before handling it. diff --git a/vendor/knative.dev/networking/test/test_images/timeout/timeout.go b/vendor/knative.dev/networking/test/test_images/timeout/timeout.go index 6505f1273..35a6a37bb 100644 --- a/vendor/knative.dev/networking/test/test_images/timeout/timeout.go +++ b/vendor/knative.dev/networking/test/test_images/timeout/timeout.go @@ -24,7 +24,7 @@ import ( "strconv" "time" - network "knative.dev/networking/pkg" + "knative.dev/networking/pkg/http/probe" "knative.dev/networking/test" ) @@ -51,7 +51,7 @@ func handler(w http.ResponseWriter, r *http.Request) { } func main() { - h := network.NewProbeHandler(http.HandlerFunc(handler)) + h := probe.NewHandler(http.HandlerFunc(handler)) port := os.Getenv("PORT") if cert, key := os.Getenv("CERT"), os.Getenv("KEY"); cert != "" && key != "" { log.Print("Server starting on port with TLS ", port) diff --git a/vendor/knative.dev/networking/test/test_images/wsserver/echo.go b/vendor/knative.dev/networking/test/test_images/wsserver/echo.go index be87938d8..36f3382f0 100644 --- a/vendor/knative.dev/networking/test/test_images/wsserver/echo.go +++ b/vendor/knative.dev/networking/test/test_images/wsserver/echo.go @@ -22,7 +22,8 @@ import ( "os" "github.com/gorilla/websocket" - network "knative.dev/networking/pkg" + "knative.dev/networking/pkg/http/header" + "knative.dev/networking/pkg/http/probe" "knative.dev/networking/test" ) @@ -45,7 +46,7 @@ var upgrader = websocket.Upgrader{ } func handler(w http.ResponseWriter, r *http.Request) { - if network.IsKubeletProbe(r) { + if header.IsKubeletProbe(r) { w.WriteHeader(http.StatusOK) return } @@ -85,7 +86,7 @@ func handler(w http.ResponseWriter, r *http.Request) { func main() { flag.Parse() log.SetFlags(0) - h := network.NewProbeHandler(http.HandlerFunc(handler)) + h := probe.NewHandler(http.HandlerFunc(handler)) port := os.Getenv("PORT") if cert, key := os.Getenv("CERT"), os.Getenv("KEY"); cert != "" && key != "" { log.Print("Server starting on port with TLS ", port) diff --git a/vendor/modules.txt b/vendor/modules.txt index c1e7fdd11..a5bc26f5e 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -141,7 +141,7 @@ github.com/grpc-ecosystem/grpc-gateway/utilities # github.com/hashicorp/golang-lru v0.5.4 github.com/hashicorp/golang-lru github.com/hashicorp/golang-lru/simplelru -# github.com/imdario/mergo v0.3.5 +# github.com/imdario/mergo v0.3.9 github.com/imdario/mergo # github.com/josharian/intern v1.0.0 github.com/josharian/intern @@ -860,14 +860,19 @@ k8s.io/utils/buffer k8s.io/utils/clock k8s.io/utils/clock/testing k8s.io/utils/integer +k8s.io/utils/internal/third_party/forked/golang/golang-lru k8s.io/utils/internal/third_party/forked/golang/net +k8s.io/utils/lru k8s.io/utils/net k8s.io/utils/pointer k8s.io/utils/trace -# knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c +# knative.dev/control-protocol v0.0.0-20220610133426-4a1c8e84039f +## explicit +knative.dev/control-protocol/pkg/certificates +# knative.dev/hack v0.0.0-20220610014127-dc6c287516dc => knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c ## explicit knative.dev/hack -# knative.dev/networking v0.0.0-20220412163509-1145ec58c8be +# knative.dev/networking v0.0.0-20220614203516-07c9d7614c61 ## explicit knative.dev/networking/config knative.dev/networking/pkg @@ -885,7 +890,14 @@ knative.dev/networking/pkg/client/injection/informers/factory knative.dev/networking/pkg/client/injection/informers/networking/v1alpha1/ingress knative.dev/networking/pkg/client/injection/reconciler/networking/v1alpha1/ingress knative.dev/networking/pkg/client/listers/networking/v1alpha1 +knative.dev/networking/pkg/config +knative.dev/networking/pkg/http +knative.dev/networking/pkg/http/header +knative.dev/networking/pkg/http/probe +knative.dev/networking/pkg/http/proxy +knative.dev/networking/pkg/http/stats knative.dev/networking/pkg/ingress +knative.dev/networking/pkg/k8s knative.dev/networking/pkg/prober knative.dev/networking/pkg/status knative.dev/networking/test @@ -900,7 +912,7 @@ knative.dev/networking/test/test_images/runtime/handlers knative.dev/networking/test/test_images/timeout knative.dev/networking/test/test_images/wsserver knative.dev/networking/test/types -# knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 +# knative.dev/pkg v0.0.0-20220610014025-7d607d643ee2 => knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 ## explicit knative.dev/pkg/apis knative.dev/pkg/apis/duck @@ -976,3 +988,5 @@ sigs.k8s.io/structured-merge-diff/v4/typed sigs.k8s.io/structured-merge-diff/v4/value # sigs.k8s.io/yaml v1.3.0 sigs.k8s.io/yaml +# knative.dev/hack => knative.dev/hack v0.0.0-20220411131823-6ffd8417de7c +# knative.dev/pkg => knative.dev/pkg v0.0.0-20220412134708-e325df66cb51 From 3f803a1b6195c17d0c99925acbe27668287db21e Mon Sep 17 00:00:00 2001 From: Kenjiro Nakayama Date: Thu, 28 Jul 2022 12:33:22 +0900 Subject: [PATCH 2/2] Add patch to manifest --- openshift/patches/001-kourier-cert.patch | 20 ++++++++++++++++++++ openshift/release/artifacts/0-kourier.yaml | 12 ++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 openshift/patches/001-kourier-cert.patch diff --git a/openshift/patches/001-kourier-cert.patch b/openshift/patches/001-kourier-cert.patch new file mode 100644 index 000000000..8bd4cf75a --- /dev/null +++ b/openshift/patches/001-kourier-cert.patch @@ -0,0 +1,20 @@ +diff --git a/openshift/release/artifacts/0-kourier.yaml b/openshift/release/artifacts/0-kourier.yaml +index bdb44db0..77ca06f0 100644 +--- a/openshift/release/artifacts/0-kourier.yaml ++++ b/openshift/release/artifacts/0-kourier.yaml +@@ -503,3 +503,15 @@ spec: + type: ClusterIP + + --- ++apiVersion: v1 ++kind: Secret ++metadata: ++ name: knative-serving-certs ++ namespace: kourier-system ++ labels: ++ networking.knative.dev/ingress-provider: kourier ++ app.kubernetes.io/component: net-kourier ++ app.kubernetes.io/name: knative-serving ++ serving-certs-ctrl: "data-plane" ++ networking.internal.knative.dev/certificate-uid: "serving-ingress-certs" ++# The data is populated when internal-encryption is enabled. diff --git a/openshift/release/artifacts/0-kourier.yaml b/openshift/release/artifacts/0-kourier.yaml index bdb44db0b..77ca06f0a 100644 --- a/openshift/release/artifacts/0-kourier.yaml +++ b/openshift/release/artifacts/0-kourier.yaml @@ -503,3 +503,15 @@ spec: type: ClusterIP --- +apiVersion: v1 +kind: Secret +metadata: + name: knative-serving-certs + namespace: kourier-system + labels: + networking.knative.dev/ingress-provider: kourier + app.kubernetes.io/component: net-kourier + app.kubernetes.io/name: knative-serving + serving-certs-ctrl: "data-plane" + networking.internal.knative.dev/certificate-uid: "serving-ingress-certs" +# The data is populated when internal-encryption is enabled.