From c82cb69b59cb8350fa0070b9f3cd4e90c3deeea5 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Mon, 23 Nov 2026 03:28:40 -0800 Subject: [PATCH 1/3] feat(secret): add a file-based secret manager Reads $secret://file// from /, for secrets mounted as files like a Kubernetes Secret volume. Keys can't be absolute or contain '..' segments, and one trailing newline is dropped. Signed-off-by: Srinivas Chippagiri --- apisix/secret/file.lua | 79 ++++++ docs/en/latest/admin-api.json | 65 ++++- docs/en/latest/terminology/secret.md | 68 +++++ .../components/parameters/SecretType.yaml | 1 + .../SecretUpsertPatchCollection.yaml | 4 + .../SecretUpsertPutCollection.yaml | 4 + .../components/schemas/FileSecret.yaml | 26 ++ .../admin-api/components/schemas/Secret.yaml | 1 + .../components/schemas/SecretPatch.yaml | 10 + docs/openapi/admin-api/openapi.yaml | 2 + ...rets-by-secret-type-by-id-by-sub-path.yaml | 1 + .../paths/secrets-by-secret-type-by-id.yaml | 4 + .../paths/secrets-by-secret-type.yaml | 2 +- docs/zh/latest/terminology/secret.md | 68 +++++ t/openapi/test_validator.py | 7 +- t/secret/file.t | 262 ++++++++++++++++++ 16 files changed, 593 insertions(+), 11 deletions(-) create mode 100644 apisix/secret/file.lua create mode 100644 docs/openapi/admin-api/components/schemas/FileSecret.yaml create mode 100644 t/secret/file.t diff --git a/apisix/secret/file.lua b/apisix/secret/file.lua new file mode 100644 index 000000000000..a5037b83f72e --- /dev/null +++ b/apisix/secret/file.lua @@ -0,0 +1,79 @@ +-- +-- 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. +-- + +--- Read secrets from files on the local file system, such as Kubernetes +--- Secrets mounted as a volume. +local core = require("apisix.core") + +local sub = core.string.sub +local find = core.string.find + +local schema = { + type = "object", + properties = { + base_path = { + type = "string", + description = "absolute path of the directory that holds the secret files", + pattern = [[^/]], + }, + }, + required = {"base_path"}, +} + +local _M = { + schema = schema +} + + +-- key is the path of the secret file, relative to base_path. For a mounted +-- Kubernetes Secret this is the key of the Secret, e.g. "password". A single +-- trailing newline is removed from the content, as most tools add one when +-- writing a file. +function _M.get(conf, key) + core.log.info("fetching data from file for key: ", key) + + if key == "" or find(key, "/") == 1 then + return nil, "can't find main key, key: " .. key + end + + -- keep the key inside base_path + if find("/" .. key .. "/", "/../") then + return nil, "key must not contain '..' segments, key: " .. key + end + + local base_path = conf.base_path + if sub(base_path, -1) ~= "/" then + base_path = base_path .. "/" + end + + local path = base_path .. key + local content, err = core.io.get_file(path) + if not content then + return nil, "failed to read secret file: " .. (err or path .. ": no content") + end + + if sub(content, -2) == "\r\n" then + content = sub(content, 1, -3) + elseif sub(content, -1) == "\n" then + content = sub(content, 1, -2) + end + + return content +end + + +return _M diff --git a/docs/en/latest/admin-api.json b/docs/en/latest/admin-api.json index 773a4580dc3d..037e1a55c7a3 100644 --- a/docs/en/latest/admin-api.json +++ b/docs/en/latest/admin-api.json @@ -6987,7 +6987,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] } }, @@ -7107,7 +7108,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] } }, @@ -7228,7 +7230,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] } }, @@ -7348,7 +7351,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] } }, @@ -8077,7 +8081,7 @@ ], "operationId": "listSecretsByType", "summary": "List secrets of a single secret-manager type", - "description": "Returns secrets registered under the given manager (`vault`, `aws`, or `gcp`). For listing across all managers, use `GET /apisix/admin/secrets`.", + "description": "Returns secrets registered under the given manager (`vault`, `aws`, `gcp`, or `file`). For listing across all managers, use `GET /apisix/admin/secrets`.", "parameters": [], "responses": { "200": { @@ -8122,7 +8126,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] }, "description": "Secret manager backend.", @@ -18448,6 +18453,21 @@ ], "x-source": "apisix/secret/gcp.lua" }, + "FileSecret": { + "type": "object", + "description": "File-based secret manager configuration. Secrets are read from files under `base_path`, such as a mounted Kubernetes Secret.", + "properties": { + "base_path": { + "type": "string", + "pattern": "^/", + "description": "Absolute path of the directory that holds the secret files." + } + }, + "required": [ + "base_path" + ], + "x-source": "apisix/secret/file.lua" + }, "Secret": { "description": "Secret-manager configuration. The body must match the manager selected by the `secret_type` path parameter.", "anyOf": [ @@ -18459,6 +18479,9 @@ }, { "$ref": "#/components/schemas/GcpSecret" + }, + { + "$ref": "#/components/schemas/FileSecret" } ] }, @@ -18830,6 +18853,21 @@ "description": "Path to a Google service-account JSON file." } } + }, + { + "type": "object", + "title": "Files", + "description": "File-based secret manager configuration.", + "properties": { + "base_path": { + "type": [ + "string", + "null" + ], + "pattern": "^/", + "description": "Absolute path of the directory that holds the secret files." + } + } } ] }, @@ -20647,7 +20685,8 @@ "enum": [ "vault", "aws", - "gcp" + "gcp", + "file" ] }, "description": "Secret manager backend.", @@ -21878,6 +21917,12 @@ "auth_file": "/etc/apisix/gcp-service-account.json", "ssl_verify": true } + }, + "file": { + "summary": "Files, such as a mounted Kubernetes Secret", + "value": { + "base_path": "/etc/apisix/secrets" + } } } } @@ -21909,6 +21954,12 @@ "value": { "ssl_verify": false } + }, + "fileBasePath": { + "summary": "Move file secrets to another directory", + "value": { + "base_path": "/var/run/secrets/apisix" + } } } } diff --git a/docs/en/latest/terminology/secret.md b/docs/en/latest/terminology/secret.md index 0ee4d913fa8a..62dc2dddb5d3 100644 --- a/docs/en/latest/terminology/secret.md +++ b/docs/en/latest/terminology/secret.md @@ -41,6 +41,7 @@ APISIX currently supports storing secrets in the following ways: - [HashiCorp Vault](#use-hashicorp-vault-to-manage-secrets) - [AWS Secrets Manager](#use-aws-secrets-manager-to-manage-secrets) - [GCP Secrets Manager](#use-gcp-secrets-manager-to-manage-secrets) +- [Files](#use-files-to-manage-secrets) You can use APISIX Secret functions by specifying format variables in the consumer configuration or the plugin configuration of any plugin, as well as in SSL certificate configurations. @@ -365,3 +366,70 @@ curl http://127.0.0.1:9180/apisix/admin/secrets/gcp/1 \ }' ``` + +## Use files to manage secrets + +Using files to manage secrets means APISIX reads the secret from a file on the local file system. This fits secrets that are mounted into the APISIX container as files, such as a Kubernetes Secret mounted as a volume, without exposing them as environment variables. + +### Reference Format + +``` +$secret://file/$id/$key +``` + +- id: APISIX Secrets resource ID, which needs to be consistent with the one specified when adding the APISIX Secrets resource +- key: path of the secret file, relative to `base_path`. It can contain `/` for files in subdirectories, but must not start with `/` or contain `..` segments. + +The value is the whole content of the file. A single trailing newline (` +` or ` +`) is removed, since most tools add one when writing a file. + +### Required Parameters + +| Name | Required | Default | Description | +|-----------|----------|---------|-----------------------------------------------------------------| +| base_path | True | | Absolute path of the directory that holds the secret files. | + +The files must be readable by the APISIX worker processes. + +### Example: use in key-auth plugin + +Mount the Kubernetes Secret `jack` into the APISIX pod, so that its key `auth-key` is available as the file `/etc/apisix/secrets/jack/auth-key`: + +```yaml +volumes: + - name: jack + secret: + secretName: jack +containers: + - name: apisix + volumeMounts: + - name: jack + mountPath: /etc/apisix/secrets/jack + readOnly: true +``` + +Add the APISIX Secrets resource: + +```shell +curl http://127.0.0.1:9180/apisix/admin/secrets/file/1 -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "base_path": "/etc/apisix/secrets" +}' +``` + +Reference the file in the consumer: + +```shell +curl http://127.0.0.1:9180/apisix/admin/consumers -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "username": "jack", + "plugins": { + "key-auth": { + "key": "$secret://file/1/jack/auth-key" + } + } +}' +``` + +Resolved values are cached like the values from other secret managers, see `apisix.lru.secret` in `config.yaml`. When the mounted Secret is updated, APISIX picks up the new value once the cached one expires, without a restart. diff --git a/docs/openapi/admin-api/components/parameters/SecretType.yaml b/docs/openapi/admin-api/components/parameters/SecretType.yaml index ad2d71fe34ea..f8055f0b1ba5 100644 --- a/docs/openapi/admin-api/components/parameters/SecretType.yaml +++ b/docs/openapi/admin-api/components/parameters/SecretType.yaml @@ -23,5 +23,6 @@ schema: - vault - aws - gcp + - file description: Secret manager backend. example: vault diff --git a/docs/openapi/admin-api/components/requestBodies/SecretUpsertPatchCollection.yaml b/docs/openapi/admin-api/components/requestBodies/SecretUpsertPatchCollection.yaml index a10585163aca..03abfc08dcc5 100644 --- a/docs/openapi/admin-api/components/requestBodies/SecretUpsertPatchCollection.yaml +++ b/docs/openapi/admin-api/components/requestBodies/SecretUpsertPatchCollection.yaml @@ -33,3 +33,7 @@ content: summary: Disable GCP endpoint verification value: ssl_verify: false + fileBasePath: + summary: Move file secrets to another directory + value: + base_path: /var/run/secrets/apisix diff --git a/docs/openapi/admin-api/components/requestBodies/SecretUpsertPutCollection.yaml b/docs/openapi/admin-api/components/requestBodies/SecretUpsertPutCollection.yaml index 0bb082077c84..8c2a7a6be1c4 100644 --- a/docs/openapi/admin-api/components/requestBodies/SecretUpsertPutCollection.yaml +++ b/docs/openapi/admin-api/components/requestBodies/SecretUpsertPutCollection.yaml @@ -47,3 +47,7 @@ content: value: auth_file: /etc/apisix/gcp-service-account.json ssl_verify: true + file: + summary: Files, such as a mounted Kubernetes Secret + value: + base_path: /etc/apisix/secrets diff --git a/docs/openapi/admin-api/components/schemas/FileSecret.yaml b/docs/openapi/admin-api/components/schemas/FileSecret.yaml new file mode 100644 index 000000000000..4bdf54641dc0 --- /dev/null +++ b/docs/openapi/admin-api/components/schemas/FileSecret.yaml @@ -0,0 +1,26 @@ +# +# 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. +# +type: object +description: File-based secret manager configuration. Secrets are read from files under `base_path`, such as a mounted Kubernetes Secret. +properties: + base_path: + type: string + pattern: ^/ + description: Absolute path of the directory that holds the secret files. +required: + - base_path +x-source: apisix/secret/file.lua diff --git a/docs/openapi/admin-api/components/schemas/Secret.yaml b/docs/openapi/admin-api/components/schemas/Secret.yaml index 0822a4caaba3..167dad501972 100644 --- a/docs/openapi/admin-api/components/schemas/Secret.yaml +++ b/docs/openapi/admin-api/components/schemas/Secret.yaml @@ -19,3 +19,4 @@ anyOf: - $ref: ./VaultSecret.yaml - $ref: ./AwsSecret.yaml - $ref: ./GcpSecret.yaml + - $ref: ./FileSecret.yaml diff --git a/docs/openapi/admin-api/components/schemas/SecretPatch.yaml b/docs/openapi/admin-api/components/schemas/SecretPatch.yaml index 4b85c02e6f70..3fc71287e3a1 100644 --- a/docs/openapi/admin-api/components/schemas/SecretPatch.yaml +++ b/docs/openapi/admin-api/components/schemas/SecretPatch.yaml @@ -121,3 +121,13 @@ anyOf: - string - "null" description: Path to a Google service-account JSON file. + - type: object + title: Files + description: File-based secret manager configuration. + properties: + base_path: + type: + - string + - "null" + pattern: ^/ + description: Absolute path of the directory that holds the secret files. diff --git a/docs/openapi/admin-api/openapi.yaml b/docs/openapi/admin-api/openapi.yaml index 1ee1b1176f8d..addcec19de75 100644 --- a/docs/openapi/admin-api/openapi.yaml +++ b/docs/openapi/admin-api/openapi.yaml @@ -438,6 +438,8 @@ components: $ref: ./components/schemas/AwsSecret.yaml GcpSecret: $ref: ./components/schemas/GcpSecret.yaml + FileSecret: + $ref: ./components/schemas/FileSecret.yaml Secret: $ref: ./components/schemas/Secret.yaml SSLPatch: diff --git a/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id-by-sub-path.yaml b/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id-by-sub-path.yaml index 6581fad6718e..2d5637a19a7d 100644 --- a/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id-by-sub-path.yaml +++ b/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id-by-sub-path.yaml @@ -24,6 +24,7 @@ parameters: - vault - aws - gcp + - file description: Secret manager backend. example: gcp - $ref: ../components/parameters/IdInPath.yaml diff --git a/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id.yaml b/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id.yaml index 638e72b14c4c..921583311b85 100644 --- a/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id.yaml +++ b/docs/openapi/admin-api/paths/secrets-by-secret-type-by-id.yaml @@ -31,6 +31,7 @@ get: - vault - aws - gcp + - file - name: id in: path description: Unique identifier of the resource. Can be a string (alphanumeric, `-`, `_`, `.`) or a positive integer. @@ -117,6 +118,7 @@ put: - vault - aws - gcp + - file - name: id in: path description: Unique identifier of the resource. Can be a string (alphanumeric, `-`, `_`, `.`) or a positive integer. @@ -202,6 +204,7 @@ patch: - vault - aws - gcp + - file - name: id in: path description: Unique identifier of the resource. Can be a string (alphanumeric, `-`, `_`, `.`) or a positive integer. @@ -286,6 +289,7 @@ delete: - vault - aws - gcp + - file - name: id in: path description: Unique identifier of the resource. Can be a string (alphanumeric, `-`, `_`, `.`) or a positive integer. diff --git a/docs/openapi/admin-api/paths/secrets-by-secret-type.yaml b/docs/openapi/admin-api/paths/secrets-by-secret-type.yaml index ed64b80bb09d..f2a88e3906e9 100644 --- a/docs/openapi/admin-api/paths/secrets-by-secret-type.yaml +++ b/docs/openapi/admin-api/paths/secrets-by-secret-type.yaml @@ -21,7 +21,7 @@ get: - Secrets operationId: listSecretsByType summary: List secrets of a single secret-manager type - description: Returns secrets registered under the given manager (`vault`, `aws`, or `gcp`). For listing across all managers, use `GET /apisix/admin/secrets`. + description: Returns secrets registered under the given manager (`vault`, `aws`, `gcp`, or `file`). For listing across all managers, use `GET /apisix/admin/secrets`. parameters: [] responses: "200": diff --git a/docs/zh/latest/terminology/secret.md b/docs/zh/latest/terminology/secret.md index bf06b3885524..afe0cb8c1514 100644 --- a/docs/zh/latest/terminology/secret.md +++ b/docs/zh/latest/terminology/secret.md @@ -41,6 +41,7 @@ APISIX 目前支持通过以下方式存储密钥: - [HashiCorp Vault](#使用-vault-管理密钥) - [AWS Secrets Manager](#使用-aws-secrets-manager-管理密钥) - [GCP Secrets Manager](#使用-gcp-secrets-manager-管理密钥) +- [文件](#使用文件管理密钥) 你可以在消费者配置或任何插件的配置中通过指定格式的变量来使用 APISIX Secret 功能,SSL 证书配置中同样支持。 @@ -367,3 +368,70 @@ curl http://127.0.0.1:9180/apisix/admin/secrets/gcp/1 \ }' ``` + +## 使用文件管理密钥 + +使用文件管理密钥意味着 APISIX 从本地文件系统中的文件读取密钥。这适用于以文件形式挂载到 APISIX 容器中的密钥,例如以卷的方式挂载的 Kubernetes Secret,而无需将其暴露为环境变量。 + +### 引用方式 + +``` +$secret://file/$id/$key +``` + +- id:APISIX Secrets 资源 ID,需要与添加 APISIX Secrets 资源时指定的 ID 保持一致 +- key:密钥文件相对于 `base_path` 的路径。可以包含 `/` 以引用子目录中的文件,但不能以 `/` 开头,也不能包含 `..` 路径段。 + +取到的值是文件的全部内容。由于大多数工具在写入文件时会添加换行符,末尾的一个换行符(` +` 或 ` +`)会被去掉。 + +### 必需参数 + +| 名称 | 必选项 | 默认值 | 描述 | +|-----------|--------|--------|------------------------------------| +| base_path | 是 | | 存放密钥文件的目录的绝对路径。 | + +APISIX 的 worker 进程需要有读取这些文件的权限。 + +### 示例:在 key-auth 插件中使用 + +将 Kubernetes Secret `jack` 挂载到 APISIX Pod 中,使其 `auth-key` 以文件 `/etc/apisix/secrets/jack/auth-key` 的形式存在: + +```yaml +volumes: + - name: jack + secret: + secretName: jack +containers: + - name: apisix + volumeMounts: + - name: jack + mountPath: /etc/apisix/secrets/jack + readOnly: true +``` + +添加 APISIX Secrets 资源: + +```shell +curl http://127.0.0.1:9180/apisix/admin/secrets/file/1 -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "base_path": "/etc/apisix/secrets" +}' +``` + +在消费者中引用该文件: + +```shell +curl http://127.0.0.1:9180/apisix/admin/consumers -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "username": "jack", + "plugins": { + "key-auth": { + "key": "$secret://file/1/jack/auth-key" + } + } +}' +``` + +与其他密钥管理服务一样,解析出的值会被缓存,参见 `config.yaml` 中的 `apisix.lru.secret`。挂载的 Secret 更新后,缓存过期时 APISIX 会读取到新的值,无需重启。 diff --git a/t/openapi/test_validator.py b/t/openapi/test_validator.py index 52c0f337a1b6..fbddf47d6fd4 100644 --- a/t/openapi/test_validator.py +++ b/t/openapi/test_validator.py @@ -114,16 +114,17 @@ def test_admin_reference_metadata(self): ) secret_patch = schemas['SecretPatch'] - self.assertEqual(3, len(secret_patch['anyOf'])) + self.assertEqual(4, len(secret_patch['anyOf'])) self.assertEqual( {'HashiCorp Vault', 'AWS Secrets Manager', - 'Google Cloud Secret Manager'}, + 'Google Cloud Secret Manager', 'Files'}, {branch['title'] for branch in secret_patch['anyOf']}, ) for value in ( {'token': None}, {'session_token': None}, - {'auth_config': {'client_email': None}}): + {'auth_config': {'client_email': None}}, + {'base_path': '/etc/apisix/secrets'}): errors = validator.Draft202012Validator(secret_patch).iter_errors(value) self.assertFalse(list(errors)) diff --git a/t/secret/file.t b/t/secret/file.t new file mode 100644 index 000000000000..187b2e6f0052 --- /dev/null +++ b/t/secret/file.t @@ -0,0 +1,262 @@ +# +# 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. +# + +use t::APISIX 'no_plan'; + +repeat_each(1); +no_long_string(); +no_root_location(); +log_level("info"); + +add_block_preprocessor(sub { + my ($block) = @_; + + if (!$block->request) { + $block->set_value("request", "GET /t"); + } +}); + +run_tests; + +__DATA__ + +=== TEST 1: validate schema +--- config + location /t { + content_by_lua_block { + local test_case = { + {}, + {base_path = 123}, + {base_path = "secrets"}, + {base_path = "/etc/secrets"}, + } + local file = require("apisix.secret.file") + local core = require("apisix.core") + + for _, conf in ipairs(test_case) do + local ok, err = core.schema.check(file.schema, conf) + ngx.say(ok and "done" or err) + end + } + } +--- response_body +property "base_path" is required +property "base_path" validation failed: wrong type: expected string, got number +property "base_path" validation failed: failed to match pattern "^/" with "secrets" +done + + + +=== TEST 2: reject keys that are empty, absolute or leave base_path +--- config + location /t { + content_by_lua_block { + local file = require("apisix.secret.file") + local conf = {base_path = ngx.config.prefix() .. "conf/secrets"} + + for _, key in ipairs({"", "/etc/passwd", "..", "../apisix.yaml", + "db/../../apisix.yaml", "db/.."}) do + local value, err = file.get(conf, key) + ngx.say(value or err) + end + } + } +--- response_body +can't find main key, key: +can't find main key, key: /etc/passwd +key must not contain '..' segments, key: .. +key must not contain '..' segments, key: ../apisix.yaml +key must not contain '..' segments, key: db/../../apisix.yaml +key must not contain '..' segments, key: db/.. + + + +=== TEST 3: read secret files +--- user_files +>>> ../conf/secrets/password +s3cr3t +>>> ../conf/secrets/db/user +admin +>>> ../conf/secrets/..data +not-a-traversal +--- config + location /t { + content_by_lua_block { + local file = require("apisix.secret.file") + local prefix = ngx.config.prefix() + + for _, base_path in ipairs({prefix .. "conf/secrets", prefix .. "conf/secrets/"}) do + local conf = {base_path = base_path} + for _, key in ipairs({"password", "db/user", "..data"}) do + local value, err = file.get(conf, key) + ngx.say(key, ": ", value or err) + end + end + + local value, err = file.get({base_path = prefix .. "conf/secrets"}, "missing") + ngx.say("missing: ", value or (err:find("No such file", 1, true) and "no such file" or err)) + } + } +--- response_body +password: s3cr3t +db/user: admin +..data: not-a-traversal +password: s3cr3t +db/user: admin +..data: not-a-traversal +missing: no such file + + + +=== TEST 4: only one trailing newline is removed +--- config + location /t { + content_by_lua_block { + local file = require("apisix.secret.file") + local dir = ngx.config.prefix() .. "conf/" + local cases = { + {"no-newline", "abc"}, + {"lf", "abc\n"}, + {"crlf", "abc\r\n"}, + {"two-lf", "abc\n\n"}, + {"multi-line", "line1\nline2\n"}, + } + for _, c in ipairs(cases) do + local f = assert(io.open(dir .. c[1], "w")) + f:write(c[2]) + f:close() + local value = file.get({base_path = dir}, c[1]) + ngx.say(c[1], ": ", ngx.encode_base64(value)) + end + } + } +--- response_body +no-newline: YWJj +lf: YWJj +crlf: YWJj +two-lf: YWJjCg== +multi-line: bGluZTEKbGluZTI= + + + +=== TEST 5: fetch a secret by uri +--- user_files +>>> ../conf/secrets/jack-key +jack-key-value +--- config + location /t { + content_by_lua_block { + local core = require("apisix.core") + local t = require("lib.test_admin").test + local code, body = t('/apisix/admin/secrets/file/mysecret', + ngx.HTTP_PUT, + core.json.encode({base_path = ngx.config.prefix() .. "conf/secrets"}) + ) + if code >= 300 then + ngx.status = code + return ngx.say(body) + end + + local secret = require("apisix.secret") + local value, err = secret.fetch_by_uri("$secret://file/mysecret/jack-key") + ngx.say("secret value: ", value or err) + + value, err = secret.fetch_by_uri("$secret://file/mysecret/../jack-key") + ngx.say(value or err) + + code, body = t('/apisix/admin/secrets/file/mysecret', ngx.HTTP_DELETE) + if code >= 300 then + ngx.status = code + return ngx.say(body) + end + } + } +--- response_body +secret value: jack-key-value +key must not contain '..' segments, key: ../jack-key + + + +=== TEST 6: use a file secret in key-auth +--- user_files +>>> ../conf/secrets/jack-key +jack-key-value +--- config + location /t { + content_by_lua_block { + local core = require("apisix.core") + local t = require("lib.test_admin").test + local code, body = t('/apisix/admin/secrets/file/mysecret', + ngx.HTTP_PUT, + core.json.encode({base_path = ngx.config.prefix() .. "conf/secrets"}) + ) + if code >= 300 then + ngx.status = code + return ngx.say(body) + end + + code, body = t('/apisix/admin/consumers', + ngx.HTTP_PUT, + [[{ + "username": "jack", + "plugins": { + "key-auth": { + "key": "$secret://file/mysecret/jack-key" + } + } + }]] + ) + if code >= 300 then + ngx.status = code + return ngx.say(body) + end + + code, body = t('/apisix/admin/routes/1', + ngx.HTTP_PUT, + [[{ + "uri": "/hello", + "plugins": { + "key-auth": {} + }, + "upstream": { + "nodes": {"127.0.0.1:1980": 1}, + "type": "roundrobin" + } + }]] + ) + if code >= 300 then + ngx.status = code + return ngx.say(body) + end + ngx.say("passed") + } + } +--- response_body +passed + + + +=== TEST 7: request with the key from the file +--- user_files +>>> ../conf/secrets/jack-key +jack-key-value +--- request +GET /hello +--- more_headers +apikey: jack-key-value +--- response_body +hello world From b6335776186c7577e4f4fc6a7c22e3064e007f23 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 00:43:01 -0800 Subject: [PATCH 2/3] docs(secret): name the file manager in the zh list Signed-off-by: Srinivas Chippagiri --- docs/zh/latest/terminology/secret.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/zh/latest/terminology/secret.md b/docs/zh/latest/terminology/secret.md index afe0cb8c1514..4ffefbf1248d 100644 --- a/docs/zh/latest/terminology/secret.md +++ b/docs/zh/latest/terminology/secret.md @@ -41,7 +41,7 @@ APISIX 目前支持通过以下方式存储密钥: - [HashiCorp Vault](#使用-vault-管理密钥) - [AWS Secrets Manager](#使用-aws-secrets-manager-管理密钥) - [GCP Secrets Manager](#使用-gcp-secrets-manager-管理密钥) -- [文件](#使用文件管理密钥) +- [File Secrets Manager](#使用文件管理密钥) 你可以在消费者配置或任何插件的配置中通过指定格式的变量来使用 APISIX Secret 功能,SSL 证书配置中同样支持。 From 500cad956311a7d288cba8a3e3e6f18e1d3c63b8 Mon Sep 17 00:00:00 2001 From: Srinivas Chippagiri Date: Wed, 25 Nov 2026 13:31:37 -0800 Subject: [PATCH 3/3] fix(secret): reject an empty secret file, test empty files, symlinks and directories Signed-off-by: Srinivas Chippagiri --- apisix/secret/file.lua | 4 ++++ t/secret/file.t | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/apisix/secret/file.lua b/apisix/secret/file.lua index a5037b83f72e..056b85ec58f4 100644 --- a/apisix/secret/file.lua +++ b/apisix/secret/file.lua @@ -72,6 +72,10 @@ function _M.get(conf, key) content = sub(content, 1, -2) end + if content == "" then + return nil, "secret file is empty: " .. path + end + return content end diff --git a/t/secret/file.t b/t/secret/file.t index 187b2e6f0052..ff886037194d 100644 --- a/t/secret/file.t +++ b/t/secret/file.t @@ -153,6 +153,44 @@ multi-line: bGluZTEKbGluZTI= +=== TEST 4b: empty files, directories and symlinks like those of a mounted Kubernetes Secret +--- config + location /t { + content_by_lua_block { + local file = require("apisix.secret.file") + local dir = ngx.config.prefix() .. "conf/k8s/" + os.execute("rm -rf " .. dir .. " && mkdir -p " .. dir .. "data-v1 " .. dir .. "subdir") + + local f = assert(io.open(dir .. "data-v1/password", "w")) + f:write("s3cr3t" .. "\n") + f:close() + os.execute("ln -s data-v1 " .. dir .. "..data") + os.execute("ln -s ..data/password " .. dir .. "password") + + f = assert(io.open(dir .. "empty", "w")) + f:close() + f = assert(io.open(dir .. "only-newline", "w")) + f:write("\n") + f:close() + + local conf = {base_path = dir} + ngx.say("symlink: ", file.get(conf, "password")) + for _, key in ipairs({"empty", "only-newline"}) do + local value, err = file.get(conf, key) + ngx.say(key, ": ", value == nil and err:find("secret file is empty: ", 1, true) == 1) + end + local value, err = file.get(conf, "subdir") + ngx.say("directory: ", value == nil and err:find("failed to read secret file", 1, true) ~= nil) + } + } +--- response_body +symlink: s3cr3t +empty: true +only-newline: true +directory: true + + + === TEST 5: fetch a secret by uri --- user_files >>> ../conf/secrets/jack-key