From fe529590051b6f10ff2ffe5a7bf21f05855431f9 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Mon, 16 Nov 2026 20:23:49 -0800 Subject: [PATCH] feat(ingress-controller): issue the webhook certificate with cert-manager The chart generates the webhook CA and certificate with genCA/genSignedCert and keeps the live ones with lookup. Tools that render offline, like Argo CD, can't run lookup, so every render produced new certificates and a new caBundle, leaving the app OutOfSync and rotating the webhook trust chain on each automated sync. Add webhook.certManager. When enabled the chart renders a cert-manager Certificate (and a self-signed Issuer unless issuerRef is set), annotates the ValidatingWebhookConfiguration with cert-manager.io/inject-ca-from and leaves caBundle to the cainjector, so repeated renders are identical. It can't be combined with certificate.provided. Default behavior is unchanged. Refs #993 Signed-off-by: Srinivas Chippagiri --- .github/workflows/ci.yaml | 43 +++++ charts/apisix-ingress-controller/Chart.yaml | 2 +- charts/apisix-ingress-controller/README.md | 3 + .../templates/_helpers.tpl | 7 + .../templates/webhook.yaml | 110 ++++++++++--- charts/apisix-ingress-controller/values.yaml | 7 + test/e2e/webhook-cert-manager.sh | 154 ++++++++++++++++++ test/render/webhook-cert-manager.sh | 149 +++++++++++++++++ 8 files changed, 447 insertions(+), 28 deletions(-) create mode 100755 test/e2e/webhook-cert-manager.sh create mode 100755 test/render/webhook-cert-manager.sh diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index e2c768e0..43e58f66 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -182,3 +182,46 @@ jobs: - name: End-to-end tests run: test/e2e/data-encryption.sh + + webhook-cert-manager: + name: Webhook certificate (Helm ${{ matrix.helm }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - helm: v3.22.1 + sha256: 896cf63684a42a723d61c980369d6e588330927deb13676ca0d85006dd6da0ea + - helm: v4.2.4 + sha256: c306b46f719b0a4da32d0f78ee21bf90ce8d602f15b22ab753f0674d1670a7f3 + steps: + + - name: Checkout + uses: actions/checkout@v2 + with: + submodules: recursive + + - name: Install Helm ${{ matrix.helm }} + run: | + curl -fsSLO https://get.helm.sh/helm-${{ matrix.helm }}-linux-amd64.tar.gz + echo "${{ matrix.sha256 }} helm-${{ matrix.helm }}-linux-amd64.tar.gz" | sha256sum -c + mkdir -p "$RUNNER_TEMP/helm" + tar -xzf helm-${{ matrix.helm }}-linux-amd64.tar.gz -C "$RUNNER_TEMP/helm" + echo "HELM=$RUNNER_TEMP/helm/linux-amd64/helm" >> "$GITHUB_ENV" + "$RUNNER_TEMP/helm/linux-amd64/helm" version --short + + - name: Build chart dependencies + run: | + "$HELM" dependency build charts/apisix-ingress-controller + + - name: Render tests + run: test/render/webhook-cert-manager.sh + + - name: Create Kubernetes cluster + uses: ./.github/actions/setup-kind + with: + version: v0.33.0 + image: kindest/node:v1.37.0@sha256:a1ed56cfb0e7b93589bdf97c8cd566405a265939e3620fc4f5de89adff580ae5 + + - name: End-to-end tests + run: test/e2e/webhook-cert-manager.sh diff --git a/charts/apisix-ingress-controller/Chart.yaml b/charts/apisix-ingress-controller/Chart.yaml index ca699297..60714cc6 100644 --- a/charts/apisix-ingress-controller/Chart.yaml +++ b/charts/apisix-ingress-controller/Chart.yaml @@ -24,7 +24,7 @@ keywords: - nginx - crd type: application -version: 1.5.0 +version: 1.6.0 appVersion: 2.2.0 sources: - https://github.com/apache/apisix-helm-chart diff --git a/charts/apisix-ingress-controller/README.md b/charts/apisix-ingress-controller/README.md index cf37bec1..385611db 100644 --- a/charts/apisix-ingress-controller/README.md +++ b/charts/apisix-ingress-controller/README.md @@ -175,6 +175,9 @@ The same for container level, you need to set: | serviceMonitor.metricRelabelings | object | `{}` | @param serviceMonitor.metricRelabelings MetricRelabelConfigs to apply to samples before ingestion. ref: https://prometheus.io/docs/prometheus/latest/configuration/configuration/#metric_relabel_configs | | serviceMonitor.namespace | string | `"monitoring"` | @param serviceMonitor.namespace Namespace in which to create the ServiceMonitor | | webhook.annotations | object | `{}` | Annotations for the ValidatingWebhookConfiguration, e.g. `cert-manager.io/inject-ca-from: /` so cert-manager's cainjector maintains the webhook caBundle. Only use CA injection with `certificate.provided: true` and `certificate.caBundle` unset; otherwise the injected CA replaces the chart-generated one and the webhook TLS handshake fails. | +| webhook.certManager.duration | string | `"8760h"` | Lifetime of the webhook certificate. cert-manager renews it before it expires. | +| webhook.certManager.enabled | bool | `false` | Use cert-manager to issue the webhook certificate and inject its CA into the webhook configuration. The chart then renders the same manifests every time instead of generating a certificate at render time, which keeps GitOps tools such as Argo CD in sync. Requires cert-manager in the cluster. Cannot be combined with `certificate.provided`. | +| webhook.certManager.issuerRef | object | `{}` | Issuer for the webhook certificate, e.g. `{name: my-issuer, kind: ClusterIssuer}`. When empty, the chart creates a self-signed Issuer. | | webhook.certificate.provided | bool | `false` | Set to true if you want to provide your own certificate | | webhook.enabled | bool | `true` | Enable or disable admission webhook | | webhook.failurePolicy | string | `"Ignore"` | Failure policy for the webhook (Fail or Ignore) | diff --git a/charts/apisix-ingress-controller/templates/_helpers.tpl b/charts/apisix-ingress-controller/templates/_helpers.tpl index 5855e642..3e792d8a 100644 --- a/charts/apisix-ingress-controller/templates/_helpers.tpl +++ b/charts/apisix-ingress-controller/templates/_helpers.tpl @@ -81,6 +81,13 @@ Webhook service name - ensure it stays within 63 character limit {{/* Webhook secret name - use value from values.yaml if provided, otherwise generate one */}} +{{- define "apisix-ingress-controller-manager.webhook.issuerName" -}} +{{- $suffix := "-webhook-issuer" -}} +{{- $maxLen := sub 63 (len $suffix) | int -}} +{{- $baseName := include "apisix-ingress-controller-manager.name.fullname" . | trunc $maxLen | trimSuffix "-" -}} +{{- printf "%s%s" $baseName $suffix -}} +{{- end }} + {{- define "apisix-ingress-controller-manager.webhook.secretName" -}} {{- if and .Values.webhook.certificate.provided .Values.webhook.certificate.secretName -}} {{- .Values.webhook.certificate.secretName -}} diff --git a/charts/apisix-ingress-controller/templates/webhook.yaml b/charts/apisix-ingress-controller/templates/webhook.yaml index d1bc479b..8bec568c 100644 --- a/charts/apisix-ingress-controller/templates/webhook.yaml +++ b/charts/apisix-ingress-controller/templates/webhook.yaml @@ -15,10 +15,19 @@ # limitations under the License. # {{- if .Values.webhook.enabled }} +{{- /* webhook.certManager is missing from the values of chart versions before 1.6.0, which + helm upgrade --reuse-values renders with */}} +{{- $certManager := .Values.webhook.certManager | default dict -}} +{{- $certManagerEnabled := $certManager.enabled | default false -}} +{{- if and $certManagerEnabled .Values.webhook.certificate.provided }} +{{- fail "webhook.certManager.enabled and webhook.certificate.provided cannot both be true" }} +{{- end }} +{{- /* the chart only generates a certificate when neither the user nor cert-manager provides one */}} +{{- $generateCert := and (not .Values.webhook.certificate.provided) (not $certManagerEnabled) -}} {{- $certCert := "" -}} {{- $certKey := "" -}} {{- $caCert := "" -}} -{{- if not .Values.webhook.certificate.provided }} +{{- if $generateCert }} {{- $cn := printf "%s.%s.svc" (include "apisix-ingress-controller-manager.webhook.serviceName" .) .Release.Namespace -}} {{- $ca := genCA "apisix-ingress-webhook-ca" 3650 -}} {{- $cert := genSignedCert $cn nil (list $cn) 3650 $ca -}} @@ -39,7 +48,11 @@ apiVersion: admissionregistration.k8s.io/v1 kind: ValidatingWebhookConfiguration metadata: name: {{ include "apisix-ingress-controller-manager.name.fullname" . }}-webhook - {{- with .Values.webhook.annotations }} + {{- $annotations := deepCopy (.Values.webhook.annotations | default dict) }} + {{- if $certManagerEnabled }} + {{- $_ := set $annotations "cert-manager.io/inject-ca-from" (printf "%s/%s" .Release.Namespace (include "apisix-ingress-controller-manager.webhook.secretName" .)) }} + {{- end }} + {{- with $annotations }} annotations: {{- toYaml . | nindent 4 }} {{- end }} @@ -49,9 +62,9 @@ webhooks: - name: vapisixroute-v2.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -71,9 +84,9 @@ webhooks: - name: vapisixconsumer-v2.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -93,9 +106,9 @@ webhooks: - name: vapisixtls-v2.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -115,9 +128,9 @@ webhooks: - name: vconsumer-v1alpha1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -137,9 +150,9 @@ webhooks: - name: vgatewayproxy-v1alpha1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -159,9 +172,9 @@ webhooks: - name: vingress-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -181,9 +194,9 @@ webhooks: - name: vingressclass-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -203,9 +216,9 @@ webhooks: - name: vgateway-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -225,9 +238,9 @@ webhooks: - name: vgrpcroute-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -247,9 +260,9 @@ webhooks: - name: vhttproute-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -269,9 +282,9 @@ webhooks: - name: vtcproute-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -291,9 +304,9 @@ webhooks: - name: vudproute-v1.kb.io admissionReviewVersions: ["v1"] clientConfig: - {{- if not .Values.webhook.certificate.provided }} + {{- if $generateCert }} caBundle: {{ b64enc $caCert }} - {{- else }} + {{- else if not $certManagerEnabled }} caBundle: {{ .Values.webhook.certificate.caBundle }} {{- end }} service: @@ -328,7 +341,7 @@ spec: selector: {{- include "apisix-ingress-controller-manager.selectorLabels" . | nindent 4 }} -{{- if not .Values.webhook.certificate.provided }} +{{- if $generateCert }} --- apiVersion: v1 kind: Secret @@ -343,4 +356,47 @@ data: tls.key: {{ b64enc $certKey }} ca.crt: {{ b64enc $caCert }} {{- end }} +{{- if $certManagerEnabled }} +{{- $issuerRef := $certManager.issuerRef | default dict }} +{{- if not $issuerRef.name }} +--- +apiVersion: cert-manager.io/v1 +kind: Issuer +metadata: + name: {{ include "apisix-ingress-controller-manager.webhook.issuerName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "apisix-ingress-controller-manager.labels" . | nindent 4 }} +spec: + selfSigned: {} +{{- end }} +--- +apiVersion: cert-manager.io/v1 +kind: Certificate +metadata: + name: {{ include "apisix-ingress-controller-manager.webhook.secretName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "apisix-ingress-controller-manager.labels" . | nindent 4 }} +spec: + secretName: {{ include "apisix-ingress-controller-manager.webhook.secretName" . }} + {{- with $certManager.duration }} + duration: {{ . }} + {{- end }} + commonName: apisix-ingress-webhook + dnsNames: + - {{ include "apisix-ingress-controller-manager.webhook.serviceName" . }} + - {{ include "apisix-ingress-controller-manager.webhook.serviceName" . }}.{{ .Release.Namespace }} + - {{ include "apisix-ingress-controller-manager.webhook.serviceName" . }}.{{ .Release.Namespace }}.svc + issuerRef: + {{- if $issuerRef.name }} + name: {{ $issuerRef.name }} + kind: {{ $issuerRef.kind | default "Issuer" }} + group: {{ $issuerRef.group | default "cert-manager.io" }} + {{- else }} + name: {{ include "apisix-ingress-controller-manager.webhook.issuerName" . }} + kind: Issuer + group: cert-manager.io + {{- end }} +{{- end }} {{- end }} diff --git a/charts/apisix-ingress-controller/values.yaml b/charts/apisix-ingress-controller/values.yaml index a4109ae0..88119628 100644 --- a/charts/apisix-ingress-controller/values.yaml +++ b/charts/apisix-ingress-controller/values.yaml @@ -119,6 +119,13 @@ webhook: failurePolicy: Ignore # -- Timeout in seconds for the webhook timeoutSeconds: 10 + certManager: + # -- Use cert-manager to issue the webhook certificate and inject its CA into the webhook configuration. The chart then renders the same manifests every time instead of generating a certificate at render time, which keeps GitOps tools such as Argo CD in sync. Requires cert-manager in the cluster. Cannot be combined with `certificate.provided`. + enabled: false + # -- Issuer for the webhook certificate, e.g. `{name: my-issuer, kind: ClusterIssuer}`. When empty, the chart creates a self-signed Issuer. + issuerRef: {} + # -- Lifetime of the webhook certificate. cert-manager renews it before it expires. + duration: 8760h certificate: # -- Set to true if you want to provide your own certificate provided: false diff --git a/test/e2e/webhook-cert-manager.sh b/test/e2e/webhook-cert-manager.sh new file mode 100755 index 00000000..6b415df5 --- /dev/null +++ b/test/e2e/webhook-cert-manager.sh @@ -0,0 +1,154 @@ +#!/usr/bin/env bash +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# +# End-to-end tests for the webhook certificate that cert-manager issues for the +# ingress controller chart: issuance, injection of the CA into the webhook +# configuration, renewal, and the upgrade from a release that generated the +# certificate itself. They install cert-manager into the cluster and do not +# need the controller pods to become ready. Needs kubectl, helm and curl. Run +# from the repository root. +# +# CERT_MANAGER_VERSION cert-manager chart version to install (default v1.17.2) +# OLD_CHART_VERSION released chart version to upgrade from (default 1.5.0) +# KEEP_NAMESPACES=1 keep the test namespaces for debugging + +set -uo pipefail + +HELM=${HELM:-helm} +CHART=${CHART:-charts/apisix-ingress-controller} +CERT_MANAGER_VERSION=${CERT_MANAGER_VERSION:-v1.17.2} +OLD_CHART_VERSION=${OLD_CHART_VERSION:-1.5.0} +NS=webhook-cm-e2e +NS_UPGRADE=webhook-cm-e2e-upgrade +NAMESPACES=("$NS" "$NS_UPGRADE") +# the ValidatingWebhookConfiguration and the IngressClass are cluster-scoped, so the second +# release needs a name and an ingress class of its own +FIRST_RELEASE=ingress +UPGRADE_RELEASE=ingress-upgrade +RELEASE=$FIRST_RELEASE +UPGRADE_CLASS=apisix-upgrade + +passed=0 +failed=0 + +cleanup() { + if [ "${KEEP_NAMESPACES:-}" != 1 ]; then + for ns in "${NAMESPACES[@]}"; do + $HELM uninstall --namespace "$ns" "$FIRST_RELEASE" >/dev/null 2>&1 + $HELM uninstall --namespace "$ns" "$UPGRADE_RELEASE" >/dev/null 2>&1 + kubectl delete namespace "$ns" --wait=false >/dev/null 2>&1 + done + fi +} +trap cleanup EXIT + +check() { # check + local desc=$1; shift + if "$@"; then + echo "ok - $desc"; passed=$((passed + 1)) + else + echo "FAIL - $desc"; failed=$((failed + 1)) + fi +} + +is() { [ "$1" = "$2" ] || { echo " expected '$2', got '$1'" >&2; return 1; }; } + +wait_for() { # wait_for : retry until the command succeeds + local deadline=$((SECONDS + $1)); shift + until "$@" >/dev/null 2>&1; do + [ "$SECONDS" -ge "$deadline" ] && return 1 + sleep 2 + done +} + +webhook_name() { kubectl get validatingwebhookconfiguration -l app.kubernetes.io/instance="$RELEASE" -o jsonpath='{.items[0].metadata.name}'; } +# the caBundle of the first webhook, as base64 +ca_bundle() { kubectl get validatingwebhookconfiguration "$(webhook_name)" -o jsonpath='{.webhooks[0].clientConfig.caBundle}'; } +secret_name() { kubectl --namespace "$1" get certificate -o jsonpath='{.items[0].spec.secretName}'; } +secret_ca() { # secret_ca : the ca.crt of the Secret, as base64 + kubectl --namespace "$1" get secret "$2" -o jsonpath='{.data.ca\.crt}' +} +certificate_ready() { [ "$(kubectl --namespace "$1" get certificate -o jsonpath='{.items[0].status.conditions[?(@.type=="Ready")].status}')" = True ]; } +# the caBundle of every webhook equals the given one +all_bundles_are() { + local bundles + bundles=$(kubectl get validatingwebhookconfiguration "$(webhook_name)" -o jsonpath='{range .webhooks[*]}{.clientConfig.caBundle}{"\n"}{end}' | sort -u) + [ "$bundles" = "$1" ] +} +injected() { # injected : the CA of the issued Secret is in every webhook + local ca; ca=$(secret_ca "$1" "$(secret_name "$1")") + [ -n "$ca" ] && all_bundles_are "$ca" +} +cert_serial() { # the serial number of the certificate in the Secret + kubectl --namespace "$1" get secret "$(secret_name "$1")" -o jsonpath='{.data.tls\.crt}' | base64 -d | openssl x509 -noout -serial +} + +echo "# install cert-manager" +$HELM repo add jetstack https://charts.jetstack.io >/dev/null 2>&1 +$HELM repo update jetstack >/dev/null 2>&1 +$HELM upgrade --install cert-manager jetstack/cert-manager --namespace cert-manager --create-namespace \ + --version "$CERT_MANAGER_VERSION" --set crds.enabled=true --wait --timeout 5m >/dev/null || + { echo "could not install cert-manager" >&2; exit 1; } + +echo "# cert-manager issues the certificate and injects its CA" +kubectl create namespace "$NS" >/dev/null +$HELM install "$RELEASE" "$CHART" --namespace "$NS" --set webhook.certManager.enabled=true >/dev/null || + { echo "could not install the chart" >&2; exit 1; } +check "the Certificate becomes ready" wait_for 180 certificate_ready "$NS" +check "the CA of the issued Secret is injected into every webhook" wait_for 120 injected "$NS" + +echo "# renewal" +BEFORE_SERIAL=$(cert_serial "$NS") +BEFORE_CA=$(ca_bundle) +# deleting the Secret makes cert-manager issue the certificate again, with a new key and CA +kubectl --namespace "$NS" delete secret "$(secret_name "$NS")" >/dev/null +check "a new certificate is issued" wait_for 180 bash -c \ + "[ \"\$(kubectl --namespace $NS get secret $(secret_name "$NS") -o name 2>/dev/null)\" != '' ]" +check "the new certificate has another serial number" wait_for 120 bash -c \ + "s=\$(kubectl --namespace $NS get secret $(secret_name "$NS") -o jsonpath='{.data.tls\\.crt}' | base64 -d | openssl x509 -noout -serial); [ \"\$s\" != '$BEFORE_SERIAL' ]" +check "the new CA is injected into every webhook" wait_for 120 injected "$NS" +check "the injected CA changed" bash -c "[ '$(ca_bundle)' != '$BEFORE_CA' ]" + +echo "# a helm upgrade does not change the certificate" +SERIAL=$(cert_serial "$NS") +check "a helm upgrade succeeds" $HELM upgrade "$RELEASE" "$CHART" --namespace "$NS" --set webhook.certManager.enabled=true +check "the upgrade keeps the certificate" is "$(cert_serial "$NS")" "$SERIAL" +check "the upgrade keeps the injected CA" injected "$NS" + +echo "# upgrade from a release that generated the certificate itself" +$HELM repo add apisix https://apache.github.io/apisix-helm-chart >/dev/null 2>&1 +$HELM repo update apisix >/dev/null 2>&1 +kubectl create namespace "$NS_UPGRADE" >/dev/null +RELEASE=$UPGRADE_RELEASE +if $HELM install "$RELEASE" apisix/apisix-ingress-controller --version "$OLD_CHART_VERSION" --namespace "$NS_UPGRADE" \ + --set config.kubernetes.ingressClass="$UPGRADE_CLASS" >/dev/null; then + OLD_CA=$(ca_bundle) + check "the old release has a generated CA" bash -c "[ -n '$OLD_CA' ]" + check "upgrading with --reuse-values renders the chart, which the old values know nothing about" \ + $HELM upgrade "$RELEASE" "$CHART" --namespace "$NS_UPGRADE" --reuse-values + check "the generated certificate stays after that upgrade" is "$(ca_bundle)" "$OLD_CA" + check "switching to cert-manager works" $HELM upgrade "$RELEASE" "$CHART" --namespace "$NS_UPGRADE" \ + --reset-then-reuse-values --set webhook.certManager.enabled=true + check "the Certificate becomes ready" wait_for 180 certificate_ready "$NS_UPGRADE" + check "cert-manager's CA replaces the generated one in every webhook" wait_for 120 injected "$NS_UPGRADE" +else + echo "FAIL - could not install chart $OLD_CHART_VERSION"; failed=$((failed + 1)) +fi + +echo +echo "passed: $passed, failed: $failed" +[ "$failed" -eq 0 ] diff --git a/test/render/webhook-cert-manager.sh b/test/render/webhook-cert-manager.sh new file mode 100755 index 00000000..884a8dd1 --- /dev/null +++ b/test/render/webhook-cert-manager.sh @@ -0,0 +1,149 @@ +#!/usr/bin/env bash +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# +# Render tests for the webhook certificate of the ingress controller chart: the +# default one that the chart generates, the one that cert-manager issues, and +# the values of chart versions that know nothing about cert-manager. Needs helm +# and yq (https://github.com/mikefarah/yq, v4). Run from the repository root. +# Set HELM to use another helm binary. + +set -uo pipefail + +HELM=${HELM:-helm} +for tool in "${HELM%% *}" yq; do + command -v "$tool" >/dev/null || { echo "missing required tool: $tool" >&2; exit 2; } +done +CHART=charts/apisix-ingress-controller + +passed=0 +failed=0 +OUT="" +ERR="" + +check() { # check + local desc=$1; shift + if "$@"; then + echo "ok - $desc"; passed=$((passed + 1)) + else + echo "FAIL - $desc"; failed=$((failed + 1)) + fi +} + +render() { # render [helm args...]; sets OUT and ERR, returns helm's exit code + local errfile rc + errfile=$(mktemp) + OUT=$($HELM template demo "$CHART" --namespace demo "$@" 2>"$errfile") + rc=$? + ERR=$(cat "$errfile"); rm -f "$errfile" + [ $rc -eq 0 ] || echo " $ERR" >&2 + return $rc +} + +is() { [ "$1" = "$2" ] || { echo " expected '$2', got '$1'" >&2; return 1; }; } +fails_with() { # fails_with [helm args...] + local text=$1; shift + if render "$@" 2>/dev/null; then echo " rendered without an error" >&2; return 1; fi + grep -qF -- "$text" <<<"$ERR" || { echo " error was: $ERR" >&2; return 1; } +} +count_kind() { yq "select(.kind == \"$1\") | .kind" <<<"$OUT" | grep -c .; } +webhook_config() { yq 'select(.kind == "ValidatingWebhookConfiguration")' <<<"$OUT"; } +ca_bundles() { # the distinct, non-empty caBundle values of the webhooks + webhook_config | yq '[.webhooks[].clientConfig.caBundle | select(. != null and . != "")] | unique | length' +} +with_values() { # with_values : run the command on a copy of the chart whose values.yaml is edited + local expr=$1 dir rc saved=$CHART; shift + dir=$(mktemp -d) + cp -R "$CHART" "$dir/chart" && yq -i "$expr" "$dir/chart/values.yaml" || { rm -rf "$dir"; return 1; } + CHART="$dir/chart"; "$@"; rc=$?; CHART=$saved + rm -rf "$dir" + return $rc +} +same_twice() { # the output of two renders is identical + local first + render "$@" || return 1 + first=$OUT + render "$@" || return 1 + [ "$first" = "$OUT" ] || { echo " the two renders differ" >&2; return 1; } +} + +# --- the default: the chart generates the certificate ------------------------------ + +check "default: renders" render +check "default: the chart renders the Secret with the certificate" is "$(count_kind Secret)" 1 +check "default: no cert-manager resources" is "$(( $(count_kind Certificate) + $(count_kind Issuer) ))" 0 +check "default: no inject-ca-from annotation" is "$(webhook_config | yq '.metadata.annotations["cert-manager.io/inject-ca-from"]')" null +check "default: the webhooks carry the generated CA" is "$(ca_bundles)" 1 + +# --- cert-manager issues the certificate ---------------------------------------------- + +CM=(--set webhook.certManager.enabled=true) +check "cert-manager: renders" render "${CM[@]}" +check "cert-manager: two renders are identical" same_twice "${CM[@]}" +check "cert-manager: the chart renders no Secret" is "$(count_kind Secret)" 0 +check "cert-manager: no webhook has a caBundle of its own" is "$(ca_bundles)" 0 +check "cert-manager: the webhook configuration asks cainjector for the CA of the Certificate" is \ + "$(webhook_config | yq '.metadata.annotations["cert-manager.io/inject-ca-from"]')" \ + "demo/$(yq 'select(.kind == "Certificate") | .metadata.name' <<<"$OUT")" +check "cert-manager: the Certificate writes the Secret that the controller mounts" is \ + "$(yq 'select(.kind == "Certificate") | .spec.secretName' <<<"$OUT")" \ + "$(yq 'select(.kind == "Deployment") | .spec.template.spec.volumes[] | select(.secret) | .secret.secretName' <<<"$OUT" | head -1)" +check "cert-manager: the Certificate covers the webhook Service" is \ + "$(yq 'select(.kind == "Certificate") | .spec.dnsNames | contains(["'"$(yq 'select(.kind == "Service" and .spec.ports[0].name == "webhook") | .metadata.name' <<<"$OUT")"'.demo.svc"])' <<<"$OUT")" true +check "cert-manager: the Certificate has a short subject, so the self-signed Issuer has no empty DN" is \ + "$(yq 'select(.kind == "Certificate") | .spec.commonName' <<<"$OUT")" apisix-ingress-webhook +check "cert-manager: a self-signed Issuer is created" is "$(count_kind Issuer)" 1 +check "cert-manager: the Certificate refers to that Issuer" is \ + "$(yq 'select(.kind == "Certificate") | .spec.issuerRef.name' <<<"$OUT")" \ + "$(yq 'select(.kind == "Issuer") | .metadata.name' <<<"$OUT")" + +check "cert-manager with an issuerRef: renders" render "${CM[@]}" \ + --set webhook.certManager.issuerRef.name=my-issuer --set webhook.certManager.issuerRef.kind=ClusterIssuer +check "cert-manager with an issuerRef: no Issuer is created" is "$(count_kind Issuer)" 0 +check "cert-manager with an issuerRef: the Certificate uses it" is \ + "$(yq 'select(.kind == "Certificate") | .spec.issuerRef | .name + "/" + .kind' <<<"$OUT")" my-issuer/ClusterIssuer +check "cert-manager with a duration: renders" render "${CM[@]}" --set webhook.certManager.duration=720h +check "cert-manager with a duration: the Certificate has it" is "$(yq 'select(.kind == "Certificate") | .spec.duration' <<<"$OUT")" 720h +check "cert-manager with annotations of its own: renders" render "${CM[@]}" --set-string webhook.annotations.team=gateway +check "cert-manager with annotations of its own: both are kept" is \ + "$(webhook_config | yq '.metadata.annotations | keys | join(",")')" "cert-manager.io/inject-ca-from,team" + +check "cert-manager together with a provided certificate: fails" fails_with \ + "webhook.certManager.enabled and webhook.certificate.provided cannot both be true" "${CM[@]}" \ + --set webhook.certificate.provided=true --set webhook.certificate.secretName=mine +check "webhook turned off: renders without any of it" render "${CM[@]}" --set webhook.enabled=false +check "webhook turned off: no Certificate" is "$(count_kind Certificate)" 0 + +# --- the provided certificate keeps working -------------------------------------------- + +check "provided certificate: renders" render --set webhook.certificate.provided=true \ + --set webhook.certificate.secretName=mine --set webhook.certificate.caBundle=Q0E= +check "provided certificate: the webhooks carry the given caBundle" is "$(ca_bundles)" 1 +check "provided certificate: no Secret and no cert-manager resources" is \ + "$(( $(count_kind Secret) + $(count_kind Certificate) + $(count_kind Issuer) ))" 0 + +# --- helm upgrade --reuse-values renders with the values of the chart version it upgrades from, +# --- which have no webhook.certManager + +NO_CM='del(.webhook.certManager)' +generated_secret() { render && [ "$(count_kind Secret)" -eq 1 ] && [ "$(ca_bundles)" -eq 1 ]; } +check "values without webhook.certManager: render as before" with_values "$NO_CM" render +check "values without webhook.certManager: the chart still generates the certificate" with_values "$NO_CM" generated_secret +check "values without webhook.certManager: a provided certificate still works" with_values "$NO_CM" render --set webhook.certificate.provided=true --set webhook.certificate.secretName=mine --set webhook.certificate.caBundle=Q0E= + +echo +echo "passed: $passed, failed: $failed" +[ "$failed" -eq 0 ]