플러그인 스키마 정의
플러그인 스키마 정의 (schema.lua)
커스텀 플러그인은 사용자마다 다른 요구에 맞출 수 있도록 설정 가능해야 해요. 플러그인 설정은 데이터 스토어에 저장되고, 플러그인이 실행될 때 handler.lua 메서드로 전달되거든요. 이 문서에서는 설정을 검증하는 schema.lua 파일의 명세와 모든 플러그인이 상속하는 기본 필드, 그리고 type이나 required 같은 속성으로 설정 스키마를 기술하는 방법을 살펴봐요
출처: 문서
본문
사용자들의 모든 요구 사항을 충족하세요. 플러그인의 설정은 데이터 스토어에 저장되고, 플러그인이 실행될 때 Kong Gateway가 이를 가져와서 여러분의 handler.lua 메서드에 전달해요.
설정은 우리가 스키마라고 부르는 Lua 테이블로 이루어져 있어요. 여기에는 사용자가 플러그인을 활성화할 때 설정하게 될 key/value 속성이 담겨 있어요. Kong Gateway는 여러분 플러그인의 사용자 설정을 검증할 수 있는 방법을 제공해요.
사용자가 플러그인을 활성화하거나 업데이트하면 플러그인의 설정은 여러분의 스키마를 기준으로 검증돼요.
예를 들어, 사용자가 다음 요청을 수행하면:
curl -X POST http://localhost:8001/services/{service-name-or-id}/plugins \
-d "name=my-custom-plugin" \
-d "config.foo=bar"
config 객체의 모든 속성이 스키마에 따라 유효하다면 API는 201 Created를 반환하고, 플러그인은 설정과 함께 데이터베이스에 저장돼요:
{
foo = "bar"
}
If the configuration is not valid, the Admin API would return 400 Bad Request
and the appropriate error messages.
schema.lua specification
This module is to return a Lua table with properties that will define how your plugins can later be configured by users. Available properties are:
name
Lua type: string
Description: Name of the plugin, for example: key-auth.
fields
Lua type: table
Description: Array of field definitions.
entity_checks
Lua type: function
Description: Array of conditional entity level validation checks.
All the plugins inherit some default fields which are:
id
Lua type: string
Description: Auto-generated plugin ID.
name
Lua type: string
Description: Name of the plugin.
created_at
Lua type: number
Description: Creation time of the plugin configuration (seconds from epoch).
route
Lua type: table
Description: Route to which plugin is bound, if any.
service
Lua type: table
Description: Service to which plugin is bound, if any.
consumer
Lua type: table
Description: Consumer to which plugin is bound when possible, if any.
protocols
Lua type: table
Description: Protocols on which the plugin will run.
enabled
Lua type: boolean
Description: Whether or not the plugin is enabled.
tags
Lua type: table
Description: Tags for the plugin.
In most of the cases you can ignore most of those and use the defaults or let the user specify value when enabling a plugin.
Here is an example of a potential schema.lua file (with some overrides applied):
local typedefs = require "kong.db.schema.typedefs"
return {
name = "<plugin-name>",
fields = {
{
-- this plugin will only be applied to Services or Routes
consumer = typedefs.no_consumer
},
{
-- this plugin will only run within Nginx HTTP module
protocols = typedefs.protocols_http
},
{
config = {
type = "record",
fields = {
-- Describe your plugin's configuration's schema here.
},
},
},
},
entity_checks = {
-- Describe your plugin's entity validation rules
},
}
Describe your configuration schema
The config.fields property of your schema.lua file describes the schema of your
plugin's configuration. It's a flexible array of field definitions where each field
is a valid configuration property for your plugin, describing the rules for that
property. For example:
{
name = "<plugin-name>",
fields = {
config = {
type = "record",
fields = {
{
some_string = {
type = "string",
required = false,
},
},
{
some_boolean = {
type = "boolean",
default = false,
},
},
{
some_array = {
type = "array",
elements = {
type = "string",
one_of = {
"GET",
"POST",
"PUT",
"DELETE",
},
},
},
},
},
},
},
}
Here is a list of commonly used rules for a property:
type
Description: The type of a property.
required
Description: Whether or not the property is required.
default
Description: The default value for the property when not specified.
elements
Description: The field definition of array or set elements.
keys
Description: The field definition of map keys.
values
Description: The field definition of map values.
fields
Description: The field definition(s) of record fields.
You can also add field validators, for example:
between
Description: Checks that the input number is between allowed values.
eq
Description: Checks the equality of the input to allowed value.
ne
Description: Checks the inequality of the input to allowed value.
gt
Description: Checks that the number is greater than given value.
len_eq
Description: Checks that the input string length is equal to the given value.
len_min
Description: Checks that the input string length is at least the given value.
len_max
Description: Checks that the input string length is at most the given value.
match
Description: Checks that the input string matches the given Lua pattern.
not_match
Description: Checks that the input string doesn't match the given Lua pattern.
match_all
Description: Checks that the input string matches all the given Lua patterns.
match_none
Description: Checks that the input string doesn't match any of the given Lua patterns.
match_any
Description: Checks that the input string matches any of the given Lua patterns.
starts_with
Description: Checks that the input string starts with a given value.
one_of
Description: Checks that the input string is one of the accepted values.
contains
Description: Checks that the input array contains the given value.
is_regex
Description: Checks that the input string is a valid regex pattern.
custom_validator
Description: A custom validation function written in Lua.
Making a field expressible v3.16+
A string, number, integer, or boolean field, or an array/map whose elements or values are one of those scalar types, can be marked expressible = true:
{
limit = {
type = "number",
gt = 0,
expressible = true,
},
},
This lets an operator pair the field with a CEL expression, evaluated per request, alongside the field's ordinary static config value.
Kong Gateway derives the paired expressions.FIELD entry from this attribute automatically.
You don't define it yourself, and you don't need any additional code in handler.lua to support it.
record fields can't be marked expressible, and neither can an array or map of them. Kong rejects this when your plugin's schema loads.
For the full mechanism, including how the static value acts as a fallback and how array fields work, see Dynamic plugin config with CEL.
Security guidance for expressible fields
Marking a field expressible has security implications the framework doesn't check for you. Before adding expressible = true to a field, review the following considerations.
Is the field's static value already safe as a fallback?
Kong Gateway falls back to a field's static config value automatically whenever its expression fails to evaluate on a CEL error, a null result, or a type or constraint mismatch.
This fallback is unconditional. A plugin can't opt out of it.
A client can trigger this fallback deliberately by sending a request shaped to make the expression error or produce the wrong type. That means a field's static value is also its worst-case runtime value once the field is expressible. If a permissive static value would be unsafe, marking the field expressible makes that value reachable from ordinary request traffic, not just from an Admin API misconfiguration.
Here are examples of a safe vs an unsafe approach:
- Safe approach: Rate Limiting Advanced's
limitfield requiresgt = 0, so a forced fallback always lands on the operator's own configured limit, never zero, negative, or unbounded. - Unsafe approach: A boolean gating field, for example
bypass_checkorskip_verification, wherefalseis the safe default andtruedisables an enforcement step. If a forced fallback could land ontrue, a client could force that fallback and skip the check the field is meant to gate. Before marking a field like this expressible, make sure every failure path lands on the restrictive value, or don't mark it expressible at all.
Before shipping, ask: if every expression on this field failed on every request, would you be comfortable with the resulting behavior as the field's permanent default? If not, fix the field's static semantics first.
Are the exposed CEL variables safe to drive this field?
An expressible field's expression can reference any of the available CEL variables, including request data such as http.headers.* and http.queries.*.
That data is controlled by the client by definition. A client can set it to anything, including a value chosen specifically to collide with, spoof, or evade another client's.
This matters most for a field that keys, identifies, or scopes something for a specific client, such as a counter key, a quota bucket, or an identity binding. If your field falls into that category, document which CEL variables are safe to reference and which aren't:
- Safe example: Authenticated, identity-derived values, such as
principal.idorprincipal.metadata.*. A client can't forge them without first compromising the authentication step itself. - Unsafe example: Raw request data, such as
http.headers.*orhttp.queries.*, used as the sole input to anything identity-related. Any client can set it to any value, including another client's.
This isn't a risk expressible fields introduce on their own. Making a field expressible just lets an operator express an unsafe choice as a formula instead of a fixed value. Document the risk the same way you would for a static field, rather than assume the operator will guess right.
Examples
This schema.lua file is for the key-auth plugin:
-- schema.lua
local typedefs = require "kong.db.schema.typedefs"
return {
name = "key-auth",
fields = {
{
consumer = typedefs.no_consumer
},
{
protocols = typedefs.protocols_http
},
{
config = {
type = "record",
fields = {
{
key_names = {
type = "array",
required = true,
elements = typedefs.header_name,
default = {
"apikey",
},
},
},
{
hide_credentials = {
type = "boolean",
default = false,
},
},
{
anonymous = {
type = "string",
uuid = true,
},
},
{
key_in_body = {
type = "boolean",
default = false,
},
},
{
run_on_preflight = {
type = "boolean",
default = true,
},
},
},
},
},
},
}
When implementing the access() function of your plugin in
handler.lua and given that the user
enabled the plugin with the default values, you'd have access to:
-- handler.lua
local CustomHandler = {
VERSION = "1.0.0",
PRIORITY = 10,
}
local kong = kong
function CustomHandler:access(config)
kong.log.inspect(config.key_names) -- { "apikey" }
kong.log.inspect(config.hide_credentials) -- false
end
return CustomHandler
The above example uses the kong.log.inspect function of the Plugin Development Kit to print out those values to the Kong Gateway logs.
A more complex example, which could be used for an eventual logging plugin:
-- schema.lua
local typedefs = require "kong.db.schema.typedefs"
return {
name = "my-custom-plugin",
fields = {
{
config = {
type = "record",
fields = {
{
environment = {
type = "string",
required = true,
one_of = {
"production",
"development",
},
},
},
{
server = {
type = "record",
fields = {
{
host = typedefs.host {
default = "example.com",
},
},
{
port = {
type = "number",
default = 80,
between = {
0,
65534
},
},
},
},
},
},
},
},
},
},
}
Such a configuration will allow a user to post the configuration to your plugin as follows:
curl -X POST http://localhost:8001/services/<service-name-or-id>/plugins \
-d "name=my-custom-plugin" \
-d "config.environment=development" \
-d "config.server.host=http://localhost"
And the following will be available in handler.lua:
-- handler.lua
local CustomHandler = {
VERSION = "1.0.0",
PRIORITY = 10,
}
local kong = kong
function CustomHandler:access(config)
kong.log.inspect(config.environment) -- "development"
kong.log.inspect(config.server.host) -- "http://localhost"
kong.log.inspect(config.server.port) -- 80
end
return CustomHandler
스키마의 실제 예시는 Key-Auth 플러그인 소스 코드에서도 볼 수 있어요.
관련 리소스
더 알아보기 (Learn more)
- schema.lua와 짝을 이루어 플러그인의 실행 로직을 작성하는 방법을 안내해요 — handler.lua
- 커스텀 플러그인 개발의 전체 과정을 소개해요 — Custom plugins
- 커스텀 플러그인 개발에 필요한 참조 자료를 한데 모아놨어요 — Custom plugins reference
- 필드를 표현식으로 만드는 expressible fields의 자세한 내용을 다뤄요 — CEL expression
- 플러그인 코드에서 활용할 수 있는 PDK 함수들을 확인할 수 있어요 — Plugin Development Kit