This is an automated email from the ASF dual-hosted git repository.

moonming pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/apisix-helm-chart.git


The following commit(s) were added to refs/heads/master by this push:
     new 9ce262dd feat(apisix): configure data encryption keyrings (#1052)
9ce262dd is described below

commit 9ce262dda4bf03d9384d1f2e40327646ccefd2c3
Author: Ming Wen <[email protected]>
AuthorDate: Fri Nov 20 16:31:07 2026 +0800

    feat(apisix): configure data encryption keyrings (#1052)
---
 .github/workflows/ci.yaml                |  45 +++++
 charts/apisix-dashboard/Chart.yaml       |   2 +-
 charts/apisix-dashboard/README.md        |   7 +
 charts/apisix-dashboard/README.md.gotmpl |   7 +
 charts/apisix/README.md                  | 162 ++++++++++++++++
 charts/apisix/README.md.gotmpl           | 158 +++++++++++++++
 charts/apisix/templates/NOTES.txt        |  13 ++
 charts/apisix/templates/_helpers.tpl     |  56 ++++++
 charts/apisix/templates/configmap.yaml   |  16 ++
 charts/apisix/templates/deployment.yaml  |  11 ++
 charts/apisix/values.yaml                |  15 ++
 test/e2e/data-encryption.sh              | 324 +++++++++++++++++++++++++++++++
 test/render/data-encryption.sh           | 205 +++++++++++++++++++
 13 files changed, 1020 insertions(+), 1 deletion(-)

diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 21b4deb9..e2c768e0 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -137,3 +137,48 @@ jobs:
 
       - name: End-to-end tests (etcd access)
         run: test/e2e/etcd-access.sh
+
+  data-encryption:
+    name: Data encryption (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" repo add bitnami https://charts.bitnami.com/bitnami
+          "$HELM" repo add apisix https://apache.github.io/apisix-helm-chart
+          "$HELM" dependency build charts/apisix
+
+      - name: Render tests
+        run: test/render/data-encryption.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/data-encryption.sh
diff --git a/charts/apisix-dashboard/Chart.yaml 
b/charts/apisix-dashboard/Chart.yaml
index eb5dbe86..bd450c5a 100644
--- a/charts/apisix-dashboard/Chart.yaml
+++ b/charts/apisix-dashboard/Chart.yaml
@@ -45,7 +45,7 @@ type: application
 # This is the chart version. This version number should be incremented each 
time you make changes
 # to the chart and its templates, including the app version.
 # Versions are expected to follow Semantic Versioning (https://semver.org/)
-version: 0.8.3
+version: 0.8.4
 
 # This is the version number of the application being deployed. This version 
number should be
 # incremented each time you make changes to the application. Versions are not 
expected to
diff --git a/charts/apisix-dashboard/README.md 
b/charts/apisix-dashboard/README.md
index 1654dbe2..ce4a8b33 100644
--- a/charts/apisix-dashboard/README.md
+++ b/charts/apisix-dashboard/README.md
@@ -38,6 +38,13 @@ helm install [RELEASE_NAME] apisix/apisix-dashboard 
--namespace ingress-apisix -
 
 The command deploys apisix-dashboard on the Kubernetes cluster in the default 
configuration.
 
+> [!WARNING]
+> The default configuration signs login tokens with the secret `secret` and
+> creates the user `admin` with the password `admin`. These values are public,
+> so anyone who can reach the dashboard can log in. Set
+> `config.authentication.secret` and `config.authentication.users` to your own
+> values when you install the chart.
+
 _See [configuration](#configuration) below._
 
 _See [helm install](https://helm.sh/docs/helm/helm_install/) for command 
documentation._
diff --git a/charts/apisix-dashboard/README.md.gotmpl 
b/charts/apisix-dashboard/README.md.gotmpl
index fc84c85a..8357866a 100644
--- a/charts/apisix-dashboard/README.md.gotmpl
+++ b/charts/apisix-dashboard/README.md.gotmpl
@@ -38,6 +38,13 @@ helm install [RELEASE_NAME] apisix/apisix-dashboard 
--namespace ingress-apisix -
 
 The command deploys apisix-dashboard on the Kubernetes cluster in the default 
configuration.
 
+> [!WARNING]
+> The default configuration signs login tokens with the secret `secret` and
+> creates the user `admin` with the password `admin`. These values are public,
+> so anyone who can reach the dashboard can log in. Set
+> `config.authentication.secret` and `config.authentication.users` to your own
+> values when you install the chart.
+
 _See [configuration](#configuration) below._
 
 _See [helm install](https://helm.sh/docs/helm/helm_install/) for command 
documentation._
diff --git a/charts/apisix/README.md b/charts/apisix/README.md
index b5280789..5c463869 100644
--- a/charts/apisix/README.md
+++ b/charts/apisix/README.md
@@ -444,6 +444,164 @@ With `etcd.auth.tls.enabled: false`, the APISIX etcd TLS 
settings and
 client-certificate mount are omitted as before. This flag does not rewrite
 external endpoint URLs; use `http://` endpoints for HTTP connections.
 
+## Data encryption
+
+APISIX encrypts the private keys of SSL objects and of upstream client
+certificates (`tls.client_key`), and sensitive plugin fields such as the
+credentials of authentication plugins, before it stores them in etcd. It
+encrypts with the first key of `apisix.dataEncryption.keyring` and tries every
+key when it decrypts. Each key is 16 or 32 bytes long (AES-128 or AES-256), for
+example 16 or 32 ASCII letters, and is used as its own IV. With
+`apisix.dataEncryption.enableEncryptFields: false`, plugin fields are stored in
+plain text; private keys are still encrypted with the keyring.
+
+When no keyring is set, APISIX uses its built-in keyring, `qeddd145sfvddff3`
+and `edd1c9f0985e76a2`. These keys are published in the APISIX source code, so
+anyone who can read etcd can decrypt the data. Set your own keyring, preferably
+in an existing Secret: keys set in the values are stored in plain text in the
+APISIX ConfigMap, which the Kubernetes `view` role can read, and in every
+revision of the Helm release. For a release that stores no encrypted data yet:
+
+```shell
+kubectl create secret generic apisix-keyring \
+  --from-literal=key1="$(LC_ALL=C tr -dc 'A-Za-z' </dev/urandom | head -c 16)"
+```
+
+```yaml
+apisix:
+  dataEncryption:
+    secretName: apisix-keyring
+    secretKeys:
+      - key1
+```
+
+The chart passes each key to APISIX as an environment variable,
+`APISIX_DATA_ENCRYPTION_KEY_1` for the first one and so on, and APISIX reads
+them when a pod starts: after you change the keys in the Secret, restart the
+APISIX pods. With `apisix.fullCustomConfig`, the chart does not render
+`data_encryption`; refer to these variables in your own configuration instead.
+The chart renders `apisix.fullCustomConfig.config` as a template, so escape the
+braces:
+
+```yaml
+apisix:
+  dataEncryption:
+    secretName: apisix-keyring
+  fullCustomConfig:
+    enabled: true
+    config:
+      apisix:
+        data_encryption:
+          keyring:
+            - '${{ "{{" }}APISIX_DATA_ENCRYPTION_KEY_1{{ "}}" }}'
+```
+
+Until [apache/apisix#14178](https://github.com/apache/apisix/issues/14178) is
+fixed in the APISIX version you run, use keys that do not look like a number,
+such as keys made of letters: APISIX turns a value from an environment variable
+that looks like a number into a number, whether it is quoted or not, and then
+refuses to start.
+
+The chart fails to render when the first key is one of the built-in keys, or
+when a key is not 16 or 32 bytes long. It cannot check keys in a Secret.
+APISIX 3.20.0 validates those keys after resolving the environment variables
+and rejects invalid key lengths during startup.
+
+Use the same keyring for every release that reads the same etcd, for example
+the control plane and the data plane of a decoupled deployment. Encryption only
+applies when APISIX reads its configuration from etcd.
+
+### Changing the keyring of an existing release
+
+Data can only be decrypted with the key that encrypted it, and three more
+things make a change of the keyring delicate:
+
+- APISIX tries the keys in order, and about one value in 256 passes the check
+  of AES-CBC decryption with a wrong key. APISIX then uses garbage for that
+  value: the gateway rejects the credential, APISIX cannot load such an SSL
+  object, and a GET returns the garbage, which a PUT would store for good.
+- A pod that does not have a key cannot read what other pods encrypt with it.
+- The Admin API does not return SSL private keys, so they cannot be read back
+  and saved again.
+
+To move an existing release off the built-in keyring, or to rotate your own
+key:
+
+1. Back up etcd, for example with `etcdctl snapshot save`.
+2. Pause all other Admin API writers, including ingress controllers, before
+   collecting the resource bodies, and keep them paused until step 4 is 
complete.
+   Otherwise, restoring a saved body can overwrite a change made after it was
+   collected. While the release still runs with its current keyring, GET each
+   resource that configures a plugin with encrypted fields, for example each
+   consumer and its credentials, and keep the bodies. Remove their 
`create_time` and
+   `update_time` fields, which a PUT rejects. The bodies hold the secrets in
+   plain text, so keep them safe and delete them at the end. For a consumer:
+
+   ```shell
+   curl -s "http://127.0.0.1:9180/apisix/admin/consumers/$CONSUMER"; -H 
"X-API-KEY: $ADMIN_KEY" |
+     jq '.value | del(.create_time, .update_time)' >"consumer-$CONSUMER.json"
+   ```
+
+3. Upgrade with the new key first and the current keys after it:
+
+   ```yaml
+   apisix:
+     dataEncryption:
+       keyring:
+         - "<new key>"
+         - qeddd145sfvddff3
+         - edd1c9f0985e76a2
+   ```
+
+   With a Secret, put the current keys in it after the new one:
+
+   ```shell
+   kubectl create secret generic apisix-keyring \
+     --from-literal=key1="<new key>" \
+     --from-literal=key2=qeddd145sfvddff3 \
+     --from-literal=key3=edd1c9f0985e76a2
+   ```
+
+   ```yaml
+   apisix:
+     dataEncryption:
+       secretName: apisix-keyring
+       secretKeys: [key1, key2, key3]
+   ```
+
+   In a decoupled deployment, upgrade the data planes before the control plane.
+   When rotating your own key, first adding the new key after the current one
+   and moving it to the front in a second upgrade lets all pods learn the new
+   key before it is used to encrypt data. This does not remove the need to 
pause
+   other writers from step 2 until step 4 is complete.
+
+4. PUT the bodies from step 2, not the result of a new GET:
+
+   ```shell
+   curl -s -X PUT http://127.0.0.1:9180/apisix/admin/consumers -H "X-API-KEY: 
$ADMIN_KEY" -d @"consumer-$CONSUMER.json"
+   ```
+
+   Then upload each SSL object, and each upstream, HTTP route, stream route
+   and service whose upstream configuration sets `tls.client_key`, again with
+   its PEM key, for example from the Kubernetes Secret it came from: the Admin
+   API cannot re-encrypt them from what it stores.
+   Until this step is done, the gateway can reject some of the credentials 
stored
+   before step 3, and APISIX cannot load about one SSL object in 256 (its log
+   says `failed to parse key`), so TLS handshakes for that object's SNIs fail.
+   Private keys that are still encrypted with the built-in keys can be read by
+   anyone who can read etcd. Resume other configuration writers only after
+   every resource in this step has been restored.
+
+5. You can keep the old keys after the new one; that does not weaken the new
+   key. Remove them only after step 4 is done for every resource: APISIX cannot
+   decrypt anything that is still encrypted with a key that is no longer in the
+   keyring.
+
+A rollback to a revision from before the change, with `helm rollback` or by
+reverting the values, removes the new key, and APISIX can no longer read what 
was
+encrypted with it. Undo other changes with an upgrade that keeps the current
+keyring.
+
 ## Parameters
 
 ## Values
@@ -480,6 +638,10 @@ external endpoint URLs; use `http://` endpoints for HTTP 
connections.
 | apisix.customPlugins.plugins[0].configMap | object | 
`{"mounts":[{"key":"the-file-name","path":"mount-path"}],"name":"configmap-name"}`
 | plugin codes can be saved inside configmap object. |
 | apisix.customPlugins.plugins[0].configMap.mounts | list | 
`[{"key":"the-file-name","path":"mount-path"}]` | since keys in configmap is 
flat, mountPath allows to define the mount path, so that plugin codes can be 
mounted hierarchically. |
 | apisix.customPlugins.plugins[0].configMap.name | string | `"configmap-name"` 
| name of configmap. |
+| apisix.dataEncryption.enableEncryptFields | bool | `true` | Encrypt 
sensitive plugin fields before storing them in etcd. APISIX encrypts SSL 
private keys with the keyring either way |
+| apisix.dataEncryption.keyring | list | `[]` | Keys that encrypt and decrypt, 
each 16 or 32 bytes long, for example ASCII letters. APISIX encrypts with the 
first key and tries every key when decrypting. When this and `secretName` are 
both empty, APISIX uses its built-in keyring, which is public. Keys set here 
are stored in plain text in the APISIX ConfigMap; prefer `secretName` |
+| apisix.dataEncryption.secretKeys | list | `["key1"]` | Keys of the Secret 
`secretName` that hold the keyring, in keyring order |
+| apisix.dataEncryption.secretName | string | `""` | Name of an existing 
Secret that holds the keyring. Use it instead of `keyring` |
 | apisix.deleteURITailSlash | bool | `false` | Delete the '/' at the end of 
the URI |
 | apisix.deployment.mode | string | `"traditional"` | Apache APISIX deployment 
mode Optional: traditional, decoupled, standalone standalone is file-driven 
standalone: rules are read from the mounted apisix.yaml, and the default 
traditional role is rendered as data_plane. For API-driven standalone, keep 
mode traditional and set role_traditional.config_provider to yaml.  ref: 
https://apisix.apache.org/docs/apisix/deployment-modes/ |
 | apisix.deployment.role | string | `"traditional"` | Deployment role 
Optional: traditional, data_plane, control_plane  ref: 
https://apisix.apache.org/docs/apisix/deployment-modes/ |
diff --git a/charts/apisix/README.md.gotmpl b/charts/apisix/README.md.gotmpl
index 6242b6bb..eeca33a4 100644
--- a/charts/apisix/README.md.gotmpl
+++ b/charts/apisix/README.md.gotmpl
@@ -444,6 +444,164 @@ With `etcd.auth.tls.enabled: false`, the APISIX etcd TLS 
settings and
 client-certificate mount are omitted as before. This flag does not rewrite
 external endpoint URLs; use `http://` endpoints for HTTP connections.
 
+## Data encryption
+
+APISIX encrypts the private keys of SSL objects and of upstream client
+certificates (`tls.client_key`), and sensitive plugin fields such as the
+credentials of authentication plugins, before it stores them in etcd. It
+encrypts with the first key of `apisix.dataEncryption.keyring` and tries every
+key when it decrypts. Each key is 16 or 32 bytes long (AES-128 or AES-256), for
+example 16 or 32 ASCII letters, and is used as its own IV. With
+`apisix.dataEncryption.enableEncryptFields: false`, plugin fields are stored in
+plain text; private keys are still encrypted with the keyring.
+
+When no keyring is set, APISIX uses its built-in keyring, `qeddd145sfvddff3`
+and `edd1c9f0985e76a2`. These keys are published in the APISIX source code, so
+anyone who can read etcd can decrypt the data. Set your own keyring, preferably
+in an existing Secret: keys set in the values are stored in plain text in the
+APISIX ConfigMap, which the Kubernetes `view` role can read, and in every
+revision of the Helm release. For a release that stores no encrypted data yet:
+
+```shell
+kubectl create secret generic apisix-keyring \
+  --from-literal=key1="$(LC_ALL=C tr -dc 'A-Za-z' </dev/urandom | head -c 16)"
+```
+
+```yaml
+apisix:
+  dataEncryption:
+    secretName: apisix-keyring
+    secretKeys:
+      - key1
+```
+
+The chart passes each key to APISIX as an environment variable,
+`APISIX_DATA_ENCRYPTION_KEY_1` for the first one and so on, and APISIX reads
+them when a pod starts: after you change the keys in the Secret, restart the
+APISIX pods. With `apisix.fullCustomConfig`, the chart does not render
+`data_encryption`; refer to these variables in your own configuration instead.
+The chart renders `apisix.fullCustomConfig.config` as a template, so escape the
+braces:
+
+```yaml
+apisix:
+  dataEncryption:
+    secretName: apisix-keyring
+  fullCustomConfig:
+    enabled: true
+    config:
+      apisix:
+        data_encryption:
+          keyring:
+            - {{ `'${{ "{{" }}APISIX_DATA_ENCRYPTION_KEY_1{{ "}}" }}'` }}
+```
+
+Until [apache/apisix#14178](https://github.com/apache/apisix/issues/14178) is
+fixed in the APISIX version you run, use keys that do not look like a number,
+such as keys made of letters: APISIX turns a value from an environment variable
+that looks like a number into a number, whether it is quoted or not, and then
+refuses to start.
+
+The chart fails to render when the first key is one of the built-in keys, or
+when a key is not 16 or 32 bytes long. It cannot check keys in a Secret.
+APISIX 3.20.0 validates those keys after resolving the environment variables
+and rejects invalid key lengths during startup.
+
+Use the same keyring for every release that reads the same etcd, for example
+the control plane and the data plane of a decoupled deployment. Encryption only
+applies when APISIX reads its configuration from etcd.
+
+### Changing the keyring of an existing release
+
+Data can only be decrypted with the key that encrypted it, and three more
+things make a change of the keyring delicate:
+
+- APISIX tries the keys in order, and about one value in 256 passes the check
+  of AES-CBC decryption with a wrong key. APISIX then uses garbage for that
+  value: the gateway rejects the credential, APISIX cannot load such an SSL
+  object, and a GET returns the garbage, which a PUT would store for good.
+- A pod that does not have a key cannot read what other pods encrypt with it.
+- The Admin API does not return SSL private keys, so they cannot be read back
+  and saved again.
+
+To move an existing release off the built-in keyring, or to rotate your own
+key:
+
+1. Back up etcd, for example with `etcdctl snapshot save`.
+2. Pause all other Admin API writers, including ingress controllers, before
+   collecting the resource bodies, and keep them paused until step 4 is 
complete.
+   Otherwise, restoring a saved body can overwrite a change made after it was
+   collected. While the release still runs with its current keyring, GET each
+   resource that configures a plugin with encrypted fields, for example each
+   consumer and its credentials, and keep the bodies. Remove their 
`create_time` and
+   `update_time` fields, which a PUT rejects. The bodies hold the secrets in
+   plain text, so keep them safe and delete them at the end. For a consumer:
+
+   ```shell
+   curl -s "http://127.0.0.1:9180/apisix/admin/consumers/$CONSUMER"; -H 
"X-API-KEY: $ADMIN_KEY" |
+     jq '.value | del(.create_time, .update_time)' >"consumer-$CONSUMER.json"
+   ```
+
+3. Upgrade with the new key first and the current keys after it:
+
+   ```yaml
+   apisix:
+     dataEncryption:
+       keyring:
+         - "<new key>"
+         - qeddd145sfvddff3
+         - edd1c9f0985e76a2
+   ```
+
+   With a Secret, put the current keys in it after the new one:
+
+   ```shell
+   kubectl create secret generic apisix-keyring \
+     --from-literal=key1="<new key>" \
+     --from-literal=key2=qeddd145sfvddff3 \
+     --from-literal=key3=edd1c9f0985e76a2
+   ```
+
+   ```yaml
+   apisix:
+     dataEncryption:
+       secretName: apisix-keyring
+       secretKeys: [key1, key2, key3]
+   ```
+
+   In a decoupled deployment, upgrade the data planes before the control plane.
+   When rotating your own key, first adding the new key after the current one
+   and moving it to the front in a second upgrade lets all pods learn the new
+   key before it is used to encrypt data. This does not remove the need to 
pause
+   other writers from step 2 until step 4 is complete.
+
+4. PUT the bodies from step 2, not the result of a new GET:
+
+   ```shell
+   curl -s -X PUT http://127.0.0.1:9180/apisix/admin/consumers -H "X-API-KEY: 
$ADMIN_KEY" -d @"consumer-$CONSUMER.json"
+   ```
+
+   Then upload each SSL object, and each upstream, HTTP route, stream route
+   and service whose upstream configuration sets `tls.client_key`, again with
+   its PEM key, for example from the Kubernetes Secret it came from: the Admin
+   API cannot re-encrypt them from what it stores.
+   Until this step is done, the gateway can reject some of the credentials 
stored
+   before step 3, and APISIX cannot load about one SSL object in 256 (its log
+   says `failed to parse key`), so TLS handshakes for that object's SNIs fail.
+   Private keys that are still encrypted with the built-in keys can be read by
+   anyone who can read etcd. Resume other configuration writers only after
+   every resource in this step has been restored.
+
+5. You can keep the old keys after the new one; that does not weaken the new
+   key. Remove them only after step 4 is done for every resource: APISIX cannot
+   decrypt anything that is still encrypted with a key that is no longer in the
+   keyring.
+
+A rollback to a revision from before the change, with `helm rollback` or by
+reverting the values, removes the new key, and APISIX can no longer read what 
was
+encrypted with it. Undo other changes with an upgrade that keeps the current
+keyring.
+
 ## Parameters
 
 {{ template "chart.valuesSection" . }}
diff --git a/charts/apisix/templates/NOTES.txt 
b/charts/apisix/templates/NOTES.txt
index fbb7e1fd..cabd38e6 100644
--- a/charts/apisix/templates/NOTES.txt
+++ b/charts/apisix/templates/NOTES.txt
@@ -38,3 +38,16 @@
   APISIX uses the keys set in apisix.admin.credentials.
 {{- end }}
 {{- end }}
+{{- $encryption := mergeOverwrite (dict "enableEncryptFields" true 
"secretKeys" (list "key1")) (.Values.apisix.dataEncryption | default dict) }}
+{{- if and (not .Values.apisix.fullCustomConfig.enabled) (not 
$encryption.keyring) (not $encryption.secretName) (eq (include 
"apisix.deployment.configProvider" .) "etcd") }}
+
+WARNING: APISIX encrypts SSL private keys and sensitive plugin fields, such as
+consumer credentials, with its built-in keyring, which is public. Set
+apisix.dataEncryption.secretName or apisix.dataEncryption.keyring. If this
+release already stores encrypted data, follow "Changing the keyring of an
+existing release" in the chart README; otherwise APISIX can lose that data.
+{{- end }}
+{{- if hasKey .Values.apisix "data_encryption" }}
+
+WARNING: apisix.data_encryption is not read by this chart. Use 
apisix.dataEncryption.
+{{- end }}
diff --git a/charts/apisix/templates/_helpers.tpl 
b/charts/apisix/templates/_helpers.tpl
index 7f15ed90..b9b3c1eb 100644
--- a/charts/apisix/templates/_helpers.tpl
+++ b/charts/apisix/templates/_helpers.tpl
@@ -531,3 +531,59 @@ needs etcd and cannot run standalone.
 {{- end -}}
 {{- $role -}}
 {{- end -}}
+
+{{/*
+The config provider APISIX runs with, following the config_provider values
+that configmap.yaml renders for each role.
+*/}}
+{{- define "apisix.deployment.configProvider" -}}
+{{- $role := include "apisix.deployment.role" . -}}
+{{- if eq $role "traditional" -}}
+{{- default "etcd" .Values.apisix.deployment.role_traditional.config_provider 
-}}
+{{- else if eq $role "data_plane" -}}
+{{- eq .Values.apisix.deployment.mode "standalone" | ternary "yaml" "etcd" -}}
+{{- else -}}
+{{- "etcd" -}}
+{{- end -}}
+{{- end -}}
+
+{{/*
+The keys of the keyring that APISIX uses when none is configured. They are
+published in the APISIX source code, so data encrypted with them is not
+protected.
+*/}}
+{{- define "apisix.dataEncryption.publicKeys" -}}
+{{- list "qeddd145sfvddff3" "edd1c9f0985e76a2" | toJson -}}
+{{- end -}}
+
+{{/*
+Fail on apisix.dataEncryption values that cannot work. APISIX encrypts with the
+first key of the keyring, so that key must not be a public one. The public keys
+may follow it, so that data encrypted with them can still be decrypted.
+*/}}
+{{- define "apisix.dataEncryption.validate" -}}
+{{- $encryption := mergeOverwrite (dict "enableEncryptFields" true 
"secretKeys" (list "key1")) (.Values.apisix.dataEncryption | default dict) -}}
+{{- if and $encryption.secretName $encryption.keyring -}}
+{{- fail "apisix.dataEncryption: set either keyring or secretName, not both" 
-}}
+{{- end -}}
+{{- if and $encryption.secretName (not $encryption.secretKeys) -}}
+{{- fail "apisix.dataEncryption.secretKeys must list the keys of the Secret 
that hold the keyring" -}}
+{{- end -}}
+{{- if and $encryption.keyring .Values.apisix.fullCustomConfig.enabled -}}
+{{- fail "apisix.dataEncryption.keyring is not used with 
apisix.fullCustomConfig: set data_encryption in apisix.fullCustomConfig.config, 
or use secretName and refer to the APISIX_DATA_ENCRYPTION_KEY_<n> variables 
there" -}}
+{{- end -}}
+{{- if and $encryption.keyring (not (kindIs "slice" $encryption.keyring)) -}}
+{{- fail "apisix.dataEncryption.keyring must be a list of keys" -}}
+{{- end -}}
+{{- range $index, $key := $encryption.keyring -}}
+{{- if not (kindIs "string" $key) -}}
+{{- fail (printf "apisix.dataEncryption.keyring: entry %d is not a string. 
Quote it, so that YAML keeps the key exactly as written" (add1 $index)) -}}
+{{- end -}}
+{{- if not (has (len $key) (list 16 32)) -}}
+{{- fail (printf "apisix.dataEncryption.keyring: entry %d is %d bytes long; 
APISIX accepts keys of 16 or 32 bytes" (add1 $index) (len $key)) -}}
+{{- end -}}
+{{- end -}}
+{{- if and $encryption.keyring (has (first $encryption.keyring) (include 
"apisix.dataEncryption.publicKeys" . | fromJsonArray)) -}}
+{{- fail "apisix.dataEncryption.keyring: the first key, which APISIX encrypts 
with, is one of the built-in keys of APISIX. They are public and do not protect 
the data. Put a new key first; you can keep the built-in keys after it to 
decrypt the data stored so far" -}}
+{{- end -}}
+{{- end -}}
diff --git a/charts/apisix/templates/configmap.yaml 
b/charts/apisix/templates/configmap.yaml
index 4f59d8af..3a4f2110 100644
--- a/charts/apisix/templates/configmap.yaml
+++ b/charts/apisix/templates/configmap.yaml
@@ -14,6 +14,8 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 
+{{- $encryption := mergeOverwrite (dict "enableEncryptFields" true 
"secretKeys" (list "key1")) (.Values.apisix.dataEncryption | default dict) }}
+{{- include "apisix.dataEncryption.validate" . }}
 {{- include "apisix.admin.credentials.validate" . }}
 {{- include "apisix.ingressController.validate" . }}
 apiVersion: v1
@@ -114,6 +116,20 @@ data:
           neg_ttl: {{ .Values.apisix.lru.secret.neg_ttl }}
           neg_count: {{ .Values.apisix.lru.secret.neg_count }}
 
+      data_encryption:      # encryption of sensitive plugin fields stored in 
etcd
+        enable_encrypt_fields: {{ $encryption.enableEncryptFields }}
+        {{- if $encryption.secretName }}
+        keyring:
+          {{- range $index, $_ := $encryption.secretKeys }}
+          - ${{"{{"}}APISIX_DATA_ENCRYPTION_KEY_{{ add1 $index }}{{"}}"}}
+          {{- end }}
+        {{- else if $encryption.keyring }}
+        keyring:
+          {{- range $encryption.keyring }}
+          - {{ . | quote }}
+          {{- end }}
+        {{- end }}
+
       tracing: {{ .Values.apisix.tracing }}    # Enable comprehensive request 
lifecycle tracing (SSL/SNI, rewrite, access, header_filter, body_filter, and 
log).
                                                # When disabled, OpenTelemetry 
collects only a single span per request.
 
diff --git a/charts/apisix/templates/deployment.yaml 
b/charts/apisix/templates/deployment.yaml
index ef0db41c..885290f9 100644
--- a/charts/apisix/templates/deployment.yaml
+++ b/charts/apisix/templates/deployment.yaml
@@ -13,6 +13,7 @@
 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 # See the License for the specific language governing permissions and
 # limitations under the License.
+{{- $encryption := mergeOverwrite (dict "enableEncryptFields" true 
"secretKeys" (list "key1")) (.Values.apisix.dataEncryption | default dict) }}
 apiVersion: apps/v1
 kind: {{ ternary "DaemonSet" "Deployment" .Values.useDaemonSet }}
 metadata:
@@ -122,6 +123,16 @@ spec:
           {{- end }}
           {{- end }}
 
+          {{- if $encryption.secretName }}
+          {{- range $index, $key := $encryption.secretKeys }}
+            - name: APISIX_DATA_ENCRYPTION_KEY_{{ add1 $index }}
+              valueFrom:
+                secretKeyRef:
+                  name: {{ $encryption.secretName | quote }}
+                  key: {{ $key | quote }}
+          {{- end }}
+          {{- end }}
+
           {{- if or (and .Values.etcd.enabled .Values.etcd.auth.rbac.create) 
(and (not .Values.etcd.enabled) .Values.externalEtcd.user) }}
             - name: APISIX_ETCD_PASSWORD
               valueFrom:
diff --git a/charts/apisix/values.yaml b/charts/apisix/values.yaml
index 3814c833..4f3ca527 100644
--- a/charts/apisix/values.yaml
+++ b/charts/apisix/values.yaml
@@ -410,6 +410,21 @@ apisix:
       # -- Maximum number of cached negative (failed lookup) results
       neg_count: 512
 
+  # Encryption of SSL private keys and of sensitive plugin fields, such as the
+  # credentials of authentication plugins, before they are stored in etcd. Read
+  # "Changing the keyring of an existing release" in the README before you 
change
+  # the keyring of an existing installation.
+  dataEncryption:
+    # -- Encrypt sensitive plugin fields before storing them in etcd. APISIX 
encrypts SSL private keys with the keyring either way
+    enableEncryptFields: true
+    # -- Keys that encrypt and decrypt, each 16 or 32 bytes long, for example 
ASCII letters. APISIX encrypts with the first key and tries every key when 
decrypting. When this and `secretName` are both empty, APISIX uses its built-in 
keyring, which is public. Keys set here are stored in plain text in the APISIX 
ConfigMap; prefer `secretName`
+    keyring: []
+    # -- Name of an existing Secret that holds the keyring. Use it instead of 
`keyring`
+    secretName: ""
+    # -- Keys of the Secret `secretName` that hold the keyring, in keyring 
order
+    secretKeys:
+      - key1
+
   # -- Enable comprehensive request lifecycle tracing (SSL/SNI, rewrite, 
access, header_filter, body_filter, and log).
   # When disabled, OpenTelemetry collects only a single span per request.
   tracing: false
diff --git a/test/e2e/data-encryption.sh b/test/e2e/data-encryption.sh
new file mode 100755
index 00000000..f6368858
--- /dev/null
+++ b/test/e2e/data-encryption.sh
@@ -0,0 +1,324 @@
+#!/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 apisix.dataEncryption of the apisix chart, against a
+# real cluster (for example kind) with real APISIX and etcd pods. They read
+# what APISIX stored in etcd and decrypt it with openssl, to check which key
+# encrypted it.
+# Needs kubectl, helm, curl, openssl and yq (v4). Run from the repository root
+# after `helm dependency build charts/apisix`.
+#
+#   KEEP_NAMESPACES=1  keep the test namespaces for debugging
+
+set -uo pipefail
+
+HELM=${HELM:-helm}
+CHART=${CHART:-charts/apisix}
+BUILTIN_KEY=qeddd145sfvddff3
+
+random_letters() { LC_ALL=C tr -dc 'A-Za-z' </dev/urandom | head -c "$1"; }
+ADMIN_KEY=$(random_letters 32)
+KEY_1=$(random_letters 16)
+KEY_2=$(random_letters 16)
+COMMON=(--set apisix.admin.credentials.admin="$ADMIN_KEY"
+        --set etcd.replicaCount=1
+        --wait --timeout 10m)
+
+passed=0
+failed=0
+PF_PIDS=()
+NAMESPACES=()
+ADMIN_PORT=19180
+GATEWAY_PORT=19080
+TLS_PORT=19443
+WITH_TLS=""   # set to 1 while a release serves TLS, so that connect() 
forwards its port
+
+# self-signed certificates for two SSL objects; APISIX picks the object by its
+# snis, so the certificates need no subject alternative names
+CERTS=$(mktemp -d) || exit 2
+for host in tls.test stale-tls.test; do
+  openssl req -x509 -newkey rsa:2048 -nodes -days 1 -subj "/CN=$host" \
+    -keyout "$CERTS/$host.key" -out "$CERTS/$host.crt" >/dev/null 2>&1 || { 
echo "openssl req failed" >&2; exit 2; }
+done
+# the keys as they are sent and stored, without the newline that command
+# substitution strips anyway
+TLS_KEY=$(cat "$CERTS/tls.test.key")
+STALE_TLS_KEY=$(cat "$CERTS/stale-tls.test.key")
+
+cleanup() {
+  stop_port_forwards
+  rm -rf "$CERTS"
+  if [ "${KEEP_NAMESPACES:-}" != 1 ]; then
+    for ns in "${NAMESPACES[@]:-}"; do
+      [ -n "$ns" ] || continue
+      $HELM uninstall --namespace "$ns" apisix --wait >/dev/null 2>&1
+      kubectl delete namespace "$ns" --wait=false >/dev/null 2>&1
+    done
+  fi
+}
+trap cleanup EXIT
+
+check() { # check <description> <command...>
+  local desc=$1; shift
+  if "$@"; then
+    echo "ok   - $desc"; passed=$((passed + 1))
+  else
+    echo "FAIL - $desc"; failed=$((failed + 1))
+  fi
+}
+
+wait_for() { # wait_for <seconds> <command...>: retry until the command 
succeeds
+  local deadline=$((SECONDS + $1)); shift
+  until "$@" >/dev/null 2>&1; do
+    [ "$SECONDS" -ge "$deadline" ] && return 1
+    sleep 2
+  done
+}
+
+stop_port_forwards() {
+  for pid in "${PF_PIDS[@]:-}"; do [ -n "$pid" ] && { kill "$pid" 2>/dev/null; 
wait "$pid" 2>/dev/null; }; done
+  PF_PIDS=()
+}
+
+connect() { # connect <namespace>: port-forward the Admin API and the gateway 
of a ready release
+  stop_port_forwards
+  kubectl --namespace "$1" rollout status deployment/apisix --timeout=300s 
>/dev/null
+  kubectl --namespace "$1" port-forward svc/apisix-admin "$ADMIN_PORT:9180" 
>/dev/null 2>&1 &
+  PF_PIDS+=($!)
+  kubectl --namespace "$1" port-forward svc/apisix-gateway "$GATEWAY_PORT:80" 
>/dev/null 2>&1 &
+  PF_PIDS+=($!)
+  if [ "$WITH_TLS" = 1 ]; then
+    kubectl --namespace "$1" port-forward svc/apisix-gateway "$TLS_PORT:443" 
>/dev/null 2>&1 &
+    PF_PIDS+=($!)
+  fi
+  wait_for 60 curl -s -o /dev/null "http://127.0.0.1:$ADMIN_PORT/"; &&
+    wait_for 60 curl -s -o /dev/null "http://127.0.0.1:$GATEWAY_PORT/"; &&
+    { [ "$WITH_TLS" != 1 ] || wait_for 60 tcp_open "$TLS_PORT"; }
+}
+
+tcp_open() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; }
+
+add_ssl() { # add_ssl <id> <host>: an SSL object for that SNI, with the 
certificate from $CERTS
+  local body
+  body=$(CERT="$(cat "$CERTS/$2.crt")" KEY="$(cat "$CERTS/$2.key")" HOST="$2" \
+    yq -n -o json -I0 '.cert = strenv(CERT) | .key = strenv(KEY) | .snis = 
[strenv(HOST)]')
+  created "$(admin_put "/apisix/admin/ssls/$1" "$body")"
+}
+
+tls_code() { # tls_code <host>: status code of /e2e over TLS with that SNI, 
000 when the handshake fails
+  curl -sk -o /dev/null -w '%{http_code}' --resolve "$1:$TLS_PORT:127.0.0.1" 
"https://$1:$TLS_PORT/e2e"; -H "apikey: old-key"
+}
+tls_works() { [ "$(tls_code "$1")" != 000 ]; }
+serves_tls() { wait_for 30 tls_works "$1"; }   # serves_tls <host>
+tls_fails() { is "$(tls_code "$1")" 000; }      # check only after serves_tls 
on the same pods
+
+stored_ssl_key() { # stored_ssl_key <namespace> <id>: the private key of an 
SSL object as stored in etcd
+  kubectl --namespace "$1" exec apisix-etcd-0 -- etcdctl get "/apisix/ssls/$2" 
--print-value-only |
+    yq -p json '.key'
+}
+ssl_encrypted_with() { # ssl_encrypted_with <namespace> <id> <key> <PEM key>
+  local stored
+  stored=$(stored_ssl_key "$1" "$2")
+  case "$stored" in -----BEGIN*) echo "       stored in clear text" >&2; 
return 1 ;; esac
+  [ "$(decrypt "$3" "$stored")" = "$4" ] || { echo "       the stored key does 
not decrypt with that key" >&2; return 1; }
+}
+
+admin_put() { # admin_put <path> <json>: prints the status code
+  curl -s -o /dev/null -w '%{http_code}' -X PUT 
"http://127.0.0.1:$ADMIN_PORT$1"; \
+    -H "X-API-KEY: $ADMIN_KEY" -H 'Content-Type: application/json' -d "$2"
+}
+
+created() { case "$1" in 200|201) return 0 ;; *) echo "       status $1" >&2; 
return 1 ;; esac; }
+
+add_route() { # a route that only lets consumers of key-auth through
+  created "$(admin_put /apisix/admin/routes/e2e 
'{"uri":"/e2e","plugins":{"key-auth":{},"mocking":{"response_status":200,"response_example":"ok"}}}')"
+}
+
+add_consumer() { # add_consumer <name> <key-auth key>
+  local 
body="{\"username\":\"$1\",\"plugins\":{\"key-auth\":{\"key\":\"$2\"}}}"
+  created "$(admin_put /apisix/admin/consumers "$body")"
+}
+
+consumer_body() { # consumer_body <consumer>: the body to PUT it again, as the 
README describes:
+  # the GET response without the create_time and update_time fields, which a 
PUT rejects
+  curl -s "http://127.0.0.1:$ADMIN_PORT/apisix/admin/consumers/$1"; -H 
"X-API-KEY: $ADMIN_KEY" |
+    yq -p json -o json -I0 '.value | del(.create_time, .update_time)'
+}
+
+holds_key() { # holds_key <body> <key-auth key>: the saved body has the 
decrypted key
+  is "$(yq -p json '.plugins."key-auth".key' <<<"$1")" "$2"
+}
+
+put_consumer() { created "$(admin_put /apisix/admin/consumers "$1")"; } # 
put_consumer <body>
+
+gateway_code() { # gateway_code <apikey>: status code of /e2e for that key
+  curl -s -o /dev/null -w '%{http_code}' "http://127.0.0.1:$GATEWAY_PORT/e2e"; 
-H "apikey: $1"
+}
+
+# accepts <apikey>: the gateway lets the key through. APISIX syncs from etcd in
+# the background, so wait for a consumer that was just added. Check rejects 
only
+# after an accepts on the same pods, so that the consumers are already synced.
+gateway_accepts() { [ "$(gateway_code "$1")" = 200 ]; }
+accepts() { wait_for 30 gateway_accepts "$1"; }
+rejects() { is "$(gateway_code "$1")" 401; }
+is() { [ "$1" = "$2" ] || { echo "       expected '$2', got '$1'" >&2; return 
1; }; }
+
+stored_key() { # stored_key <namespace> <consumer>: the key-auth key as stored 
in etcd
+  kubectl --namespace "$1" exec apisix-etcd-0 -- etcdctl get 
"/apisix/consumers/$2" --print-value-only |
+    yq -p json '.plugins."key-auth".key'
+}
+
+decrypt() { # decrypt <key> <stored value>: AES-128-CBC with the key as its 
IV, as APISIX does
+  local hex value=$2
+  hex=$(printf '%s' "$1" | od -An -tx1 | tr -d ' \n')
+  value=${value#'$ENC$v1$'}   # marker that newer APISIX versions put in front 
of the ciphertext
+  printf '%s' "$value" | openssl base64 -d -A 2>/dev/null |
+    openssl enc -d -aes-128-cbc -K "$hex" -iv "$hex" 2>/dev/null
+}
+
+encrypt() { # encrypt <key> <plain text>: the value APISIX 3.19 stores
+  local hex
+  hex=$(printf '%s' "$1" | od -An -tx1 | tr -d ' \n')
+  printf '%s' "$2" | openssl enc -aes-128-cbc -K "$hex" -iv "$hex" | openssl 
base64 -A
+}
+
+misreads() { # misreads <key tried first> <key that encrypted> <plain text>
+  decrypt "$1" "$(encrypt "$2" "$3")" >/dev/null
+}
+
+not_encrypted_with() { # not_encrypted_with <namespace> <consumer> <key> 
<plain text>
+  [ "$(decrypt "$3" "$(stored_key "$1" "$2")")" != "$4" ]
+}
+
+encrypted_with() { # encrypted_with <namespace> <consumer> <key> <plain text>
+  local stored
+  stored=$(stored_key "$1" "$2")
+  [ -n "$stored" ] && [ "$stored" != "$4" ] || { echo "       stored in clear 
text: '$stored'" >&2; return 1; }
+  [ "$(decrypt "$3" "$stored")" = "$4" ] || { echo "       '$stored' does not 
decrypt with that key" >&2; return 1; }
+}
+
+# A wrong key passes the padding check of AES-CBC for about one value in 256, 
and
+# APISIX then uses the garbage it decrypts (see the README). Draw keys that do 
not
+# do that to the values this test stores, so that the test does not fail at 
random.
+while misreads "$KEY_2" "$KEY_1" jack-key || misreads "$KEY_1" "$BUILTIN_KEY" 
old-key ||
+      misreads "$KEY_1" "$BUILTIN_KEY" stale-key || misreads "$KEY_1" 
"$BUILTIN_KEY" "$TLS_KEY" ||
+      misreads "$KEY_1" "$BUILTIN_KEY" "$STALE_TLS_KEY"; do
+  KEY_1=$(random_letters 16)
+  KEY_2=$(random_letters 16)
+done
+
+new_namespace() { NAMESPACES+=("$1"); kubectl create namespace "$1" 
>/dev/null; }
+
+install() { # install <namespace> [helm args...]
+  local ns=$1; shift
+  $HELM install apisix "$CHART" --namespace "$ns" "${COMMON[@]}" "$@" 
>/dev/null
+}
+
+install_previous() { # install_previous <namespace> [helm args...]
+  local ns=$1; shift
+  mkdir -p "$CERTS/previous-chart" || return 1
+  $HELM pull apisix --repo https://apache.github.io/apisix-helm-chart 
--version 3.0.0 \
+    --untar --untardir "$CERTS/previous-chart" &&
+    $HELM install apisix "$CERTS/previous-chart/apisix" --namespace "$ns" 
"${COMMON[@]}" "$@" >/dev/null
+}
+
+upgrade() { # upgrade <namespace> [helm args...]
+  local ns=$1; shift
+  $HELM upgrade apisix "$CHART" --namespace "$ns" "${COMMON[@]}" "$@" 
>/dev/null
+}
+
+# --- a keyring from an existing Secret, then a rotation 
------------------------
+
+NS=de-secret
+new_namespace "$NS"
+kubectl --namespace "$NS" create secret generic apisix-keyring 
--from-literal=key1="$KEY_1" --save-config >/dev/null
+check "secret: the release installs" install "$NS" --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "secret: connected" connect "$NS"
+check "secret: route created" add_route
+check "secret: consumer jack created" add_consumer jack jack-key
+check "secret: jack's key is stored encrypted with the key from the Secret" 
encrypted_with "$NS" jack "$KEY_1" jack-key
+check "secret: it is not encrypted with the built-in key" not_encrypted_with 
"$NS" jack "$BUILTIN_KEY" jack-key
+check "secret: the gateway accepts jack's key" accepts jack-key
+check "secret: the gateway rejects a wrong key" rejects wrong-key
+
+# rotate: put a new key first and keep the old one, so jack's key stays 
readable
+kubectl --namespace "$NS" create secret generic apisix-keyring 
--from-literal=key1="$KEY_1" --from-literal=key2="$KEY_2" \
+  --dry-run=client -o yaml | kubectl apply -f - >/dev/null
+check "rotation: the upgrade succeeds" upgrade "$NS" --set 
apisix.dataEncryption.secretName=apisix-keyring \
+  --set-json 'apisix.dataEncryption.secretKeys=["key2","key1"]'
+check "rotation: connected to the new pods" connect "$NS"
+check "rotation: jack's old key still works" accepts jack-key
+check "rotation: consumer rose created" add_consumer rose rose-key
+check "rotation: rose's key is encrypted with the new first key" 
encrypted_with "$NS" rose "$KEY_2" rose-key
+check "rotation: the gateway accepts rose's key" accepts rose-key
+
+# --- moving an existing release off the built-in keyring 
-----------------------
+
+NS=de-migrate
+new_namespace "$NS"
+WITH_TLS=1
+TLS=(--set apisix.ssl.enabled=true)
+check "built-in: chart 3.0.0 installs with its default keyring" 
install_previous "$NS" "${TLS[@]}"
+check "built-in: connected" connect "$NS"
+check "built-in: route created" add_route
+check "built-in: consumer old created" add_consumer old old-key
+check "built-in: consumer stale created" add_consumer stale stale-key
+check "built-in: SSL object for tls.test created" add_ssl 1 tls.test
+check "built-in: SSL object for stale-tls.test created" add_ssl 2 
stale-tls.test
+check "built-in: by default the data is encrypted with the public built-in 
key" encrypted_with "$NS" old "$BUILTIN_KEY" old-key
+check "built-in: and so is the SSL private key" ssl_encrypted_with "$NS" 1 
"$BUILTIN_KEY" "$TLS_KEY"
+check "built-in: TLS works" serves_tls tls.test
+OLD_BODY=$(consumer_body old)
+check "built-in: the body saved before the change holds the decrypted key" 
holds_key "$OLD_BODY" old-key
+
+# The released chart has no dataEncryption defaults. Exercise Helm's real
+# --reuse-values path before opting into the new keyring configuration.
+check "reuse-values: chart 3.0.0 upgrades without setting dataEncryption" 
upgrade "$NS" --reuse-values
+check "reuse-values: connected to the upgraded release" connect "$NS"
+check "reuse-values: the old consumer still works" accepts old-key
+check "reuse-values: TLS still works" serves_tls tls.test
+check "reuse-values: a new consumer can be created" add_consumer reused 
reused-key
+check "reuse-values: new data still uses the built-in key" encrypted_with 
"$NS" reused "$BUILTIN_KEY" reused-key
+check "reuse-values: the gateway accepts the new consumer" accepts reused-key
+check "reuse-values: the gateway rejects a wrong key" rejects wrong-key
+
+check "migration: the upgrade with a new key first and the built-in key after 
it succeeds" \
+  upgrade "$NS" "${TLS[@]}" --set-json 
"apisix.dataEncryption.keyring=[\"$KEY_1\",\"$BUILTIN_KEY\"]"
+check "migration: connected to the new pods" connect "$NS"
+check "migration: the old consumers still work" accepts old-key
+check "migration: the old consumers still work (stale)" accepts stale-key
+check "migration: TLS still works for tls.test" serves_tls tls.test
+check "migration: and for stale-tls.test" serves_tls stale-tls.test
+check "migration: consumer old saved again from the body saved before the 
change" put_consumer "$OLD_BODY"
+check "migration: old is now encrypted with the new key" encrypted_with "$NS" 
old "$KEY_1" old-key
+check "migration: the SSL object for tls.test uploaded again with its PEM key" 
add_ssl 1 tls.test
+check "migration: its private key is now encrypted with the new key" 
ssl_encrypted_with "$NS" 1 "$KEY_1" "$TLS_KEY"
+check "migration: consumer new created" add_consumer new new-key
+check "migration: new data is encrypted with the new key" encrypted_with "$NS" 
new "$KEY_1" new-key
+
+check "dropping the built-in key: the upgrade succeeds" upgrade "$NS" 
"${TLS[@]}" --set-json "apisix.dataEncryption.keyring=[\"$KEY_1\"]"
+check "dropping the built-in key: connected to the new pods" connect "$NS"
+check "dropping the built-in key: data encrypted with the new key works" 
accepts new-key
+check "dropping the built-in key: data saved again works" accepts old-key
+check "dropping the built-in key: TLS works for the SSL object uploaded again" 
serves_tls tls.test
+check "dropping the built-in key: data not saved again can no longer be read" 
rejects stale-key
+check "dropping the built-in key: TLS fails for the SSL object not uploaded 
again" tls_fails stale-tls.test
+WITH_TLS=""
+
+echo
+echo "passed: $passed, failed: $failed"
+[ "$failed" -eq 0 ]
diff --git a/test/render/data-encryption.sh b/test/render/data-encryption.sh
new file mode 100755
index 00000000..568def18
--- /dev/null
+++ b/test/render/data-encryption.sh
@@ -0,0 +1,205 @@
+#!/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 apisix.dataEncryption of the apisix chart.
+# Needs helm and yq (https://github.com/mikefarah/yq, v4). Run from the
+# repository root after `helm dependency build charts/apisix`.
+# 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
+NEW=AbCdEfGhIjKlMnOp
+BUILTIN_1=qeddd145sfvddff3
+BUILTIN_2=edd1c9f0985e76a2
+WARNING="WARNING: APISIX encrypts SSL private keys and sensitive plugin fields"
+
+passed=0
+failed=0
+OUT=""
+ERR=""
+NOTES=""
+
+check() { # check <description> <command...>
+  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 (manifests) and ERR (stderr), 
returns helm's exit code
+  local errfile rc
+  errfile=$(mktemp)
+  OUT=$($HELM template apisix "$CHART" --namespace demo "$@" 2>"$errfile")
+  rc=$?
+  ERR=$(cat "$errfile"); rm -f "$errfile"
+  return $rc
+}
+
+# NOTES.txt is not part of `helm template` output, and `helm install --dry-run`
+# needs a reachable cluster with Helm 3. So render it from a copy of the chart
+# in which a ConfigMap template carries the rendered NOTES.txt.
+NOTES_CHART=$(mktemp -d) || exit 2
+ORIGINAL_NOTES_CHART=$NOTES_CHART
+REUSED_CHART=$(mktemp -d) || { rm -rf "$NOTES_CHART"; exit 2; }
+trap 'rm -rf "$ORIGINAL_NOTES_CHART" "$REUSED_CHART"' EXIT
+cp -R "$CHART"/. "$NOTES_CHART"/
+{
+  printf '%s\n' 'apiVersion: v1' 'kind: ConfigMap' 'metadata:' '  name: 
rendered-notes' 'data:' \
+    '  notes: {{ include "test.renderedNotes" . | toJson }}' '{{- define 
"test.renderedNotes" }}'
+  cat "$CHART/templates/NOTES.txt"
+  printf '\n%s\n' '{{- end }}'
+} >"$NOTES_CHART/templates/zz-rendered-notes.yaml"
+
+notes() { # notes [helm args...]; sets NOTES to the rendered NOTES.txt
+  NOTES=$($HELM template apisix "$NOTES_CHART" --namespace demo --show-only 
templates/zz-rendered-notes.yaml "$@" 2>/dev/null |
+    yq '.data.notes')
+  [ -n "$NOTES" ] && [ "$NOTES" != null ] || { echo "       NOTES could not be 
rendered" >&2; return 1; }
+}
+
+config() { yq 'select(.kind == "ConfigMap" and .data["config.yaml"] != null) | 
.data["config.yaml"]' <<<"$OUT" | yq "$1"; }
+config_text() { yq 'select(.kind == "ConfigMap" and .data["config.yaml"] != 
null) | .data["config.yaml"]' <<<"$OUT"; }
+env_ref() { # env_ref <env name>  ->  "<secret>/<key>"
+  yq "select(.kind == \"Deployment\") | .spec.template.spec.containers[] | 
select(.name == \"apisix\") | .env[] | select(.name == \"$1\") | 
.valueFrom.secretKeyRef | .name + \"/\" + .key" <<<"$OUT"
+}
+key_envs() { # names of the keyring environment variables, one per line
+  yq 'select(.kind == "Deployment") | .spec.template.spec.containers[] | 
select(.name == "apisix") | .env[] | select(.name | 
test("^APISIX_DATA_ENCRYPTION_KEY_")) | .name' <<<"$OUT"
+}
+is() { [ "$1" = "$2" ] || { echo "       expected '$2', got '$1'" >&2; return 
1; }; }
+fails_with() { # fails_with <message part> [helm args...]
+  local text=$1; shift
+  if render "$@"; then echo "       rendered without an error" >&2; return 1; 
fi
+  grep -qF -- "$text" <<<"$ERR" || { echo "       error was: $ERR" >&2; return 
1; }
+}
+warns() { notes "$@" && grep -qF -- "$WARNING" <<<"$NOTES"; }          # warns 
[helm args...]
+does_not_warn() { notes "$@" && ! grep -qF -- "$WARNING" <<<"$NOTES"; } # 
does_not_warn [helm args...]
+notes_say() { local text=$1; shift; notes "$@" && grep -qF -- "$text" 
<<<"$NOTES"; }
+
+# --- defaults: APISIX's built-in keyring, with a warning 
------------------------
+
+check "default: renders" render
+check "default: encryption stays enabled" is "$(config 
'.apisix.data_encryption.enable_encrypt_fields')" true
+check "default: no keyring is rendered, APISIX keeps its built-in one" is 
"$(config '.apisix.data_encryption.keyring')" null
+check "default: no keyring environment variable" is "$(key_envs)" ""
+check "default: NOTES warns that the built-in keyring is public" warns
+
+# --- upgrading with chart 3.0.0 defaults 
----------------------------------------
+
+# --reuse-values replaces the new chart defaults with the previous chart's
+# coalesced values. Merely passing an old values file with -f would merge in 
the
+# new defaults and miss this regression. Remove the new map from a chart copy.
+cp -R "$NOTES_CHART"/. "$REUSED_CHART"/
+yq -i 'del(.apisix.dataEncryption)' "$REUSED_CHART/values.yaml" || exit 2
+ORIGINAL_CHART=$CHART
+CHART=$REUSED_CHART
+NOTES_CHART=$REUSED_CHART
+
+check "reuse-values: renders without the new map" render
+check "reuse-values: encryption stays enabled" is "$(config 
'.apisix.data_encryption.enable_encrypt_fields')" true
+check "reuse-values: keeps the built-in keyring" is "$(config 
'.apisix.data_encryption.keyring')" null
+check "reuse-values: no keyring environment variable" is "$(key_envs)" ""
+check "reuse-values: NOTES still warns" warns
+check "reuse-values, disabled: renders" render --set 
apisix.dataEncryption.enableEncryptFields=false
+check "reuse-values: explicit false is preserved" is "$(config 
'.apisix.data_encryption.enable_encrypt_fields')" false
+check "reuse-values, disabled: NOTES still warns for SSL keys" warns --set 
apisix.dataEncryption.enableEncryptFields=false
+check "reuse-values, secret: renders with only secretName" render --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "reuse-values, secret: defaults to key1" is "$(env_ref 
APISIX_DATA_ENCRYPTION_KEY_1)" apisix-keyring/key1
+check "reuse-values, secret: config refers to the variable" is "$(config 
'.apisix.data_encryption.keyring | join(",")')" 
'${{APISIX_DATA_ENCRYPTION_KEY_1}}'
+check "reuse-values, secret: no built-in warning" does_not_warn --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "reuse-values: explicit empty secretKeys still fails" fails_with 
"apisix.dataEncryption.secretKeys must list the keys" \
+  --set apisix.dataEncryption.secretName=apisix-keyring --set-json 
'apisix.dataEncryption.secretKeys=[]'
+check "reuse-values, inline: renders" render --set-json 
"apisix.dataEncryption.keyring=[\"$NEW\",\"$BUILTIN_1\"]"
+check "reuse-values, inline: keeps key order" is "$(config 
'.apisix.data_encryption.keyring | join(",")')" "$NEW,$BUILTIN_1"
+check "reuse-values, fullCustomConfig: renders" render --set 
apisix.fullCustomConfig.enabled=true --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "reuse-values, fullCustomConfig: still injects the Secret key" is 
"$(env_ref APISIX_DATA_ENCRYPTION_KEY_1)" apisix-keyring/key1
+
+CHART=$ORIGINAL_CHART
+NOTES_CHART=$ORIGINAL_NOTES_CHART
+
+# --- a keyring in the values 
---------------------------------------------------
+
+check "inline: renders" render --set-json 
"apisix.dataEncryption.keyring=[\"$NEW\",\"$BUILTIN_1\",\"$BUILTIN_2\"]"
+check "inline: the keyring is rendered in order" is "$(config 
'.apisix.data_encryption.keyring | join(",")')" "$NEW,$BUILTIN_1,$BUILTIN_2"
+check "inline: the keys are quoted" grep -qF -- "- \"$NEW\"" 
<<<"$(config_text)"
+check "inline: no warning about the built-in keyring" does_not_warn --set-json 
"apisix.dataEncryption.keyring=[\"$NEW\"]"
+
+check "inline, digits only: renders" render --set-json 
'apisix.dataEncryption.keyring=["1234567890123456"]'
+check "inline: a key made of digits stays a string" is "$(config 
'.apisix.data_encryption.keyring[0] | tag')" '!!str'
+
+check "disabled: renders" render --set 
apisix.dataEncryption.enableEncryptFields=false
+check "disabled: enable_encrypt_fields is rendered false" is "$(config 
'.apisix.data_encryption.enable_encrypt_fields')" false
+check "disabled: still warns, SSL private keys are encrypted with the keyring" 
warns --set apisix.dataEncryption.enableEncryptFields=false
+
+# --- a keyring in an existing Secret 
-------------------------------------------
+
+check "secret: renders" render --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "secret: one key by default" is "$(key_envs)" 
APISIX_DATA_ENCRYPTION_KEY_1
+check "secret: it reads the key key1" is "$(env_ref 
APISIX_DATA_ENCRYPTION_KEY_1)" apisix-keyring/key1
+check "secret: config.yaml refers to the variable" is "$(config 
'.apisix.data_encryption.keyring | join(",")')" 
'${{APISIX_DATA_ENCRYPTION_KEY_1}}'
+
+check "secret with two keys: renders" render --set 
apisix.dataEncryption.secretName=apisix-keyring --set-json 
'apisix.dataEncryption.secretKeys=["new","old"]'
+check "secret: one variable per key, in keyring order" is "$(env_ref 
APISIX_DATA_ENCRYPTION_KEY_1),$(env_ref APISIX_DATA_ENCRYPTION_KEY_2)" 
apisix-keyring/new,apisix-keyring/old
+check "secret: config.yaml lists the variables in the same order" is "$(config 
'.apisix.data_encryption.keyring | join(",")')" 
'${{APISIX_DATA_ENCRYPTION_KEY_1}},${{APISIX_DATA_ENCRYPTION_KEY_2}}'
+check "secret: no warning about the built-in keyring" does_not_warn --set 
apisix.dataEncryption.secretName=apisix-keyring
+
+check "secret with fullCustomConfig: renders" render --set 
apisix.fullCustomConfig.enabled=true --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "secret with fullCustomConfig: the variable is still set for the custom 
config" is "$(env_ref APISIX_DATA_ENCRYPTION_KEY_1)" apisix-keyring/key1
+
+# --- values that cannot work 
-----------------------------------------------------
+
+check "fail: the first key is the first built-in key" fails_with "the first 
key, which APISIX encrypts with, is one of the built-in keys" \
+  --set-json "apisix.dataEncryption.keyring=[\"$BUILTIN_1\",\"$NEW\"]"
+check "fail: the first key is the second built-in key" fails_with "the first 
key, which APISIX encrypts with, is one of the built-in keys" \
+  --set-json "apisix.dataEncryption.keyring=[\"$BUILTIN_2\"]"
+values=$(mktemp)
+printf 'apisix:\n  dataEncryption:\n    keyring:\n      - %s\n      - 
1234567890123456\n' "$NEW" >"$values"
+check "fail: an unquoted number in the keyring" fails_with 
"apisix.dataEncryption.keyring: entry 2 is not a string" -f "$values"
+check "fail: the error does not print the key" bash -c '! grep -qF 
1234567890123456 <<<"$1"' _ "$ERR"
+rm -f "$values"
+check "fail: a keyring given as one string" fails_with 
"apisix.dataEncryption.keyring must be a list of keys" \
+  --set apisix.dataEncryption.keyring="$NEW"
+check "fail: that error does not print the key" bash -c '! grep -qF "$2" 
<<<"$1"' _ "$ERR" "$NEW"
+check "fail: a key that is not 16 or 32 bytes long" fails_with "entry 2 is 15 
bytes long" \
+  --set-json "apisix.dataEncryption.keyring=[\"$NEW\",\"${NEW:0:15}\"]"
+check "fail: that error does not print the key" bash -c '! grep -qF "$2" 
<<<"$1"' _ "$ERR" "${NEW:0:15}"
+check "a 32-byte key: renders" render --set-json 
"apisix.dataEncryption.keyring=[\"$NEW$NEW\"]"
+check "fail: an inline keyring with fullCustomConfig" fails_with 
"apisix.dataEncryption.keyring is not used with apisix.fullCustomConfig" \
+  --set apisix.fullCustomConfig.enabled=true --set-json 
"apisix.dataEncryption.keyring=[\"$NEW\"]"
+check "fail: keyring and secretName together" fails_with "set either keyring 
or secretName, not both" \
+  --set-json "apisix.dataEncryption.keyring=[\"$NEW\"]" --set 
apisix.dataEncryption.secretName=apisix-keyring
+check "fail: secretName without secretKeys" fails_with 
"apisix.dataEncryption.secretKeys must list the keys" \
+  --set apisix.dataEncryption.secretName=apisix-keyring --set-json 
'apisix.dataEncryption.secretKeys=[]'
+
+# --- when the warning applies 
-----------------------------------------------------
+
+check "standalone (file): no warning, APISIX does not encrypt without etcd" 
does_not_warn --set apisix.deployment.mode=standalone
+check "standalone (API): no warning, APISIX does not encrypt without etcd" 
does_not_warn --set apisix.deployment.role_traditional.config_provider=yaml 
--set etcd.enabled=false
+check "fullCustomConfig: no warning, the custom config decides" does_not_warn 
--set apisix.fullCustomConfig.enabled=true
+check "decoupled data plane: warns, it decrypts with the same keyring" warns 
--set apisix.deployment.mode=decoupled --set apisix.deployment.role=data_plane
+check "decoupled control plane: warns" warns --set 
apisix.deployment.mode=decoupled --set apisix.deployment.role=control_plane
+check "the old apisix.data_encryption value: NOTES says it is not read" \
+  notes_say "apisix.data_encryption is not read by this chart" --set-json 
'apisix.data_encryption={"keyring":["AbCdEfGhIjKlMnOp"]}'
+
+echo
+echo "passed: $passed, failed: $failed"
+[ "$failed" -eq 0 ]

Reply via email to