kong package¶
Subpackages¶
- kong.client package
- Submodules
- kong.client.tls module
- Module contents
client
client.authenticate()
client.authenticate_consumer_group_by_consumer_id()
client.get_consumer()
client.get_consumer_group()
client.get_consumer_groups()
client.get_credential()
client.get_forwarded_ip()
client.get_forwarded_port()
client.get_ip()
client.get_port()
client.get_protocol()
client.load_consumer()
client.set_authenticated_consumer_group()
client.set_authenticated_consumer_groups()
client.tls
- kong.ctx package
- kong.enterprise_edition package
- kong.nginx package
- kong.service package
Submodules¶
kong.cluster module¶
- class kong.cluster.cluster[source]¶
Bases:
object
- static get_id() Tuple[str, str] [source]¶
Returns the unique ID for this Kong cluster. If Kong is running in DB-less mode without a cluster ID explicitly defined, then this method returns nil. For hybrid mode, all control planes and data planes belonging to the same cluster return the same cluster ID. For traditional database-based deployments, all Kong nodes pointing to the same database also return the same cluster ID.
- Example:
id, err = kong.cluster.get_id()
if err:
# handle errorif not id:
# no cluster ID is available# use id here
- Returns:
The v4 UUID used by this cluster as its ID.
- Return type:
str
- Returns:
An error message.
- Return type:
str
kong.ip module¶
- class kong.ip.ip[source]¶
Bases:
object
- static is_trusted(address: str) bool [source]¶
Depending on the trusted_ips configuration property, this function returns whether a given IP is trusted or not. Both ipv4 and ipv6 are supported.
- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
if kong.ip.is_trusted(“1.1.1.1”):
kong.log(“The IP is trusted”)
- Parameters:
address (str) – A string representing an IP address.
- Returns:
true if the IP is trusted, false otherwise.
- Return type:
bool
kong.log module¶
- class kong.log.log[source]¶
Bases:
object
- static alert(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static crit(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static debug(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static deprecation(*args: Any) None [source]¶
Arguments given to this function can be of any type, but table arguments are converted to strings via tostring (thus potentially calling a table’s __tostring metamethod if set). When the last argument is a table, it is considered as a deprecation metadata. The table can include the following properties: ``` lua {
after = “2.5.0”, – deprecated after Kong version 2.5.0 (defaults to nil) removal = “3.0.0”, – about to be removed with Kong version 3.0.0 (defaults to nil) trace = true, – writes stack trace along with the deprecation message (defaults to nil)
For example, the following call:
` lua kong.log.deprecation("hello ", "world") `
would, within the core, produce a log line similar to:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
If invoked from within a plugin (for example, key-auth) it would include the namespace prefix:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
And with metatable, the following call:` lua kong.log.deprecation("hello ", "world", { after = "2.5.0", removal = "3.0.0" }) `
would, within the core, produce a log line similar to:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world (deprecated after 2.5.0, scheduled for removal in 3.0.0), client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.deprecation(“hello “, “world”)
kong.log.deprecation(“hello “, “world”, { after = “2.5.0” })
kong.log.deprecation(“hello “, “world”, { removal = “3.0.0” })
kong.log.deprecation(“hello “, “world”, { after = “2.5.0”, removal = “3.0.0” })
kong.log.deprecation(“hello “, “world”, { trace = true })
- Parameters:
*args –
all params will be concatenated and stringified before being sent to the log (if the last param is a table, it is considered as a deprecation metadata)
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static err(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static info(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static notice(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static set_serialize_value(key: str, value: Any, options: table) table [source]¶
Sets a value to be used on the serialize custom table. Logging plugins use the output of kong.log.serialize() as a base for their logs. This function lets you customize the log output. It can be used to replace existing values in the output, or to delete existing values by passing nil. Note: The type-checking of the value parameter can take some time, so it is deferred to the serialize() call, which happens in the log phase in most real-usage cases.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# Adds a new value to the serialized table
kong.log.set_serialize_value(“my_new_value”, 1)
assert(kong.log.serialize().my_new_value == 1)
# Value can be a table
kong.log.set_serialize_value(“my”, { new = { value = 2 } })
assert(kong.log.serialize().my.new.value == 2)
# It is possible to change an existing serialized value
kong.log.set_serialize_value(“my_new_value”, 3)
assert(kong.log.serialize().my_new_value == 3)
# Unset an existing value by setting it to nil
kong.log.set_serialize_value(“my_new_value”, nil)
assert(kong.log.serialize().my_new_value == nil)
# Dots in the key are interpreted as table accesses
kong.log.set_serialize_value(“my.new.value”, 4)
assert(kong.log.serialize().my.new_value == 4)
- Parameters:
key (str) – The name of the field.
value (Any) – Value to be set. When a table is used, its keys must be numbers, strings, or booleans, and its values can be numbers, strings, or other tables like itself, recursively.
options (table) – Can contain two entries: options.mode can be set (the default, always sets), add (only add if entry does not already exist) and replace (only change value if it already exists).
- Returns:
The request information table.
- Return type:
table
- static warn(*args: Any) None [source]¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
kong.node module¶
- class kong.node.node[source]¶
Bases:
object
- static get_hostname() str [source]¶
Returns the name used by the local machine.
- Example:
hostname = kong.node.get_hostname()
- Returns:
The local machine hostname.
- Return type:
str
- static get_id() str [source]¶
Returns the ID used by this node to describe itself.
- Example:
id = kong.node.get_id()
- Returns:
The v4 UUID used by this node as its ID.
- Return type:
str
- static get_memory_stats(unit: str | None, scale: number | None) table [source]¶
Returns memory usage statistics about this node.
- Example:
res = kong.node.get_memory_stats()
# res will have the following structure:
{
lua_shared_dicts = {
kong = {
allocated_slabs = 12288,
capacity = 24576
},
kong_db_cache = {
allocated_slabs = 12288,
capacity = 12288
}
},
workers_lua_vms = {
{
http_allocated_gc = 1102,
pid = 18004
},
{
http_allocated_gc = 1102,
pid = 18005
}
}
}
res = kong.node.get_memory_stats(“k”, 1)
# res will have the following structure:
{
lua_shared_dicts = {
kong = {
allocated_slabs = “12.0 KiB”,
capacity = “24.0 KiB”,
},
kong_db_cache = {
allocated_slabs = “12.0 KiB”,
capacity = “12.0 KiB”,
}
},
workers_lua_vms = {
{
http_allocated_gc = “1.1 KiB”,
pid = 18004
},
{
http_allocated_gc = “1.1 KiB”,
pid = 18005
}
}
}
- Parameters:
unit (str) – The unit that memory is reported in. Can be any of b/B, k/K, m/M, or g/G for bytes, kibibytes, mebibytes, or gibibytes, respectively. Defaults to b (bytes).
scale (number) – The number of digits to the right of the decimal point. Defaults to 2.
- Returns:
A table containing memory usage statistics for this node. If unit is b/B (the default), reported values are Lua numbers. Otherwise, reported values are strings with the unit as a suffix.
- Return type:
table
kong.plugin module¶
kong.request module¶
- class kong.request.request[source]¶
Bases:
object
- static get_body(mimetype: str | None, max_args: number | None, max_allowed_file_size: number | None) Tuple[table, str, str] [source]¶
Returns the request data as a key/value table. A high-level convenience function. The body is parsed with the most appropriate format: * If mimetype is specified, it decodes the body with the requested
content type (if supported). This takes precedence over any content type present in the request. The optional argument mimetype can be one of the following strings:
application/x-www-form-urlencoded
application/json
multipart/form-data
Whether mimetype is specified or a request content type is otherwise present in the request, each content type behaves as follows: * If the request content type is application/x-www-form-urlencoded:
Returns the body as form-encoded.
If the request content type is multipart/form-data: * Decodes the body as multipart form data
(same as multipart(kong.request.get_raw_body(), kong.request.get_header(“Content-Type”)):get_all() ).
If the request content type is application/json: * Decodes the body as JSON
(same as json.decode(kong.request.get_raw_body())).
JSON types are converted to matching Lua types.
If the request contains none of the above and the mimetype argument is not set, returns nil and an error message indicating the body could not be parsed.
The optional argument max_args can be used to set a limit on the number of form arguments parsed for application/x-www-form-urlencoded payloads, which is by default 100 (or what has been configured using lua_max_post_args). The third return value is string containing the mimetype used to parsed the body (as per the mimetype argument), allowing the caller to identify what MIME type the body was parsed as.
- Phases:
rewrite, access, response, admin_api
- Example:
body, err, mimetype = kong.request.get_body()
body.name # “John Doe”
body.age # “42”
- Parameters:
mimetype (str) – The MIME type.
max_args (number) – Sets a limit on the maximum number of parsed
max_allowed_file_size (number) – the max allowed file size to be read from arguments.
- Returns:
A table representation of the body.
- Return type:
table
- Returns:
An error message.
- Return type:
str
- Returns:
mimetype The MIME type used.
- Return type:
str
- static get_forwarded_host() str [source]¶
Returns the host component of the request’s URL or the value of the “host” header. Unlike kong.request.get_host(), this function also considers X-Forwarded-Host if it comes from a trusted source. The returned value is normalized to lowercase. Whether this function considers X-Forwarded-Host or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_host() # “example.com”
- Returns:
The forwarded host.
- Return type:
str
- static get_forwarded_path() str [source]¶
Returns the path component of the request’s URL, but also considers X-Forwarded-Path if it comes from a trusted source. The value is returned as a Lua string. Whether this function considers X-Forwarded-Path or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not do any normalization on the request path.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_path() # /path
- Returns:
The forwarded path.
- Return type:
str
- static get_forwarded_port() number [source]¶
Returns the port component of the request’s URL, but also considers X-Forwarded-Host if it comes from a trusted source. The value is returned as a Lua number. Whether this function considers X-Forwarded-Proto or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module. When running Kong behind the L4 port mapping (or forwarding), you can also configure: * [port_maps](https://docs.konghq.com/gateway/latest/reference/configuration/#port_maps) The port_maps configuration parameter enables this function to return the port to which the port Kong is listening to is mapped to (in case they differ).
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_port() # 1234
- Returns:
The forwarded port.
- Return type:
number
- static get_forwarded_prefix() str [source]¶
Returns the prefix path component of the request’s URL that Kong stripped before proxying to upstream. It also checks if X-Forwarded-Prefix comes from a trusted source, and uses it as-is when given. The value is returned as a Lua string. If a trusted X-Forwarded-Prefix is not passed, this function must be called after Kong has run its router (access phase), as the Kong router may strip the prefix of the request path. That stripped path becomes the return value of this function, unless there is already a trusted X-Forwarded-Prefix header in the request. Whether this function considers X-Forwarded-Prefix or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not do any normalization on the request path prefix.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_prefix() # /prefix
- Returns:
The forwarded path prefix or nil if the prefix was not stripped.
- Return type:
str
- static get_forwarded_scheme() str [source]¶
Returns the scheme component of the request’s URL, but also considers X-Forwarded-Proto if it comes from a trusted source. The returned value is normalized to lowercase. Whether this function considers X-Forwarded-Proto or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_scheme() # “https”
- Returns:
The forwarded scheme.
- Return type:
str
- static get_header(name: str) str [source]¶
Returns the value of the specified request header. The returned value is either a string, or can be nil if a header with name was not found in the request. If a header with the same name is present multiple times in the request, this function returns the value of the first occurrence of this header. Header names in are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request with the following headers:
# Host: foo.com
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
kong.request.get_header(“Host”) # “foo.com”
kong.request.get_header(“x-custom-header”) # “bla”
kong.request.get_header(“X-Another”) # “foo bar”
- Parameters:
name (str) – the name of the header to be returned
- Returns:
the value of the header or nil if not present
- Return type:
str
- static get_headers(max_headers: number | None) table [source]¶
Returns a Lua table holding the request headers. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header. By default, this function returns up to 100 headers (or what has been configured using lua_max_req_headers). The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and not greater than 1000.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request with the following headers:
# Host: foo.com
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
headers = kong.request.get_headers()
headers.host # “foo.com”
headers.x_custom_header # “bla”
headers.x_another[1] # “foo bar”
headers[“X-Another”][2] # “baz”
- Parameters:
max_headers (number) – Sets a limit on the maximum number of parsed headers.
- Returns:
The request headers in table form.
- Return type:
table
- static get_host() str [source]¶
Returns the host component of the request’s URL, or the value of the “Host” header. The returned value is normalized to lowercase form.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_host() # “example.com”
- Returns:
The hostname.
- Return type:
str
- static get_http_version() number [source]¶
Returns the HTTP version used by the client in the request as a Lua number, returning values such as 1, 1.1, 2.0, or nil for unrecognized values.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_http_version() # 1.1
- Returns:
The HTTP version as a Lua number.
- Return type:
number
- static get_method() str [source]¶
Returns the HTTP method of the request. The value is normalized to uppercase.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_method() # “GET”
- Returns:
The request method.
- Return type:
str
- static get_path() str [source]¶
Returns the normalized path component of the request’s URL. The return value is the same as kong.request.get_raw_path() but normalized according to RFC 3986 section 6: * Percent-encoded values of unreserved characters are decoded (%20
becomes ` `).
Percent-encoded values of reserved characters have their hexidecimal value uppercased (%2f becomes %2F).
Relative path elements (/. and /..) are dereferenced.
Duplicate slashes are consolidated (// becomes /).
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/t/Abc%20123%C3%B8%2f/parent/..//test/./
kong.request.get_path() # “/t/Abc 123ø%2F/test/”
- Returns:
the path
- Return type:
str
- static get_path_with_query() str [source]¶
Returns the path, including the query string if any. No transformations or normalizations are done.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies?movie=foo
kong.request.get_path_with_query() # “/v1/movies?movie=foo”
- Returns:
The path with the query string.
- Return type:
str
- static get_port() number [source]¶
Returns the port component of the request’s URL. The value is returned as a Lua number.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_port() # 1234
- Returns:
The port.
- Return type:
number
- static get_query(max_args: number | None) table [source]¶
Returns the table of query arguments obtained from the query string. Keys are query argument names. Values are either a string with the argument value, a boolean true if an argument was not given a value, or an array if an argument was given in the query string multiple times. Keys and values are unescaped according to URL-encoded escaping rules. Note that a query string ?foo&bar translates to two boolean true arguments, and ?foo=&bar= translates to two string arguments containing empty strings. By default, this function returns up to 100 arguments (or what has been configured using lua_max_uri_args). The optional max_args argument can be specified to customize this limit, but must be greater than 1 and not greater than 1000.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
for k, v in pairs(kong.request.get_query()) do
kong.log.inspect(k, v)# Will print
# “foo” “hello world”
# “bar” {“baz”, “bla”, true}
# “zzz” true
# “blo” “”
- Parameters:
max_args (number) – Sets a limit on the maximum number of parsed arguments.
- Returns:
A table representation of the query string.
- Return type:
table
- static get_query_arg() Any [source]¶
Returns the value of the specified argument, obtained from the query arguments of the current request. The returned value is either a string, a boolean true if an argument was not given a value, or nil if no argument with name was found. If an argument with the same name is present multiple times in the query string, this function returns the value of the first occurrence.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
kong.request.get_query_arg(“foo”) # “hello world”
kong.request.get_query_arg(“bar”) # “baz”
kong.request.get_query_arg(“zzz”) # true
kong.request.get_query_arg(“blo”) # “”
- Returns:
The value of the argument.
- Return type:
Any
- static get_raw_body() Tuple[bytes, str] [source]¶
Returns the plain request body. If the body has no size (empty), this function returns an empty string. If the size of the body is greater than the Nginx buffer size (set by client_body_buffer_size), this function fails and returns an error message explaining this limitation, unless max_allowed_file_size is set and equal to 0 or larger than the body size buffered to disk. Use of max_allowed_file_size requires Kong to read data from filesystem and has performance implications.
- Phases:
rewrite, access, response, admin_api
- Example:
# Given a body with payload “Hello, Earth!”:
kong.request.get_raw_body():gsub(“Earth”, “Mars”) # “Hello, Mars!”
- Returns:
The plain request body or nil if it does not fit into the NGINX temporary buffer.
- Return type:
bytes
- Returns:
An error message.
- Return type:
str
- static get_raw_path() str [source]¶
Returns the path component of the request’s URL. It is not normalized in any way and does not include the query string. NOTE: Using the raw path to perform string comparision during request handling (such as in routing, ACL/authorization checks, setting rate-limit keys, etc) is widely regarded as insecure, as it can leave plugin code vulnerable to path traversal attacks. Prefer kong.request.get_path() for such use cases.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/t/Abc%20123%C3%B8%2f/parent/..//test/./?movie=foo
kong.request.get_raw_path() # “/t/Abc%20123%C3%B8%2f/parent/..//test/./”
- Returns:
The path.
- Return type:
str
- static get_raw_query() str [source]¶
Returns the query component of the request’s URL. It is not normalized in any way (not even URL-decoding of special characters) and does not include the leading ? character.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/foo?msg=hello%20world&bla=&bar
kong.request.get_raw_query() # “msg=hello%20world&bla=&bar”
- Returns:
The query component of the request’s URL.
- Return type:
str
- static get_scheme() str [source]¶
Returns the scheme component of the request’s URL. The returned value is normalized to lowercase form.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_scheme() # “https”
- Returns:
A string like “http” or “https”.
- Return type:
str
- static get_start_time() number [source]¶
Returns the request start time, in Unix epoch milliseconds.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_start_time() # 1649960273000
- Returns:
The timestamp
- Return type:
number
- static get_uri_captures() table [source]¶
Returns the URI captures matched by the router.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
captures = kong.request.get_uri_captures()
for idx, value in ipairs(captures.unnamed) do
# do what you want to capturesfor name, value in pairs(captures.named) do
# do what you want to captures
- Returns:
tables containing unamed and named captures.
- Return type:
table
kong.response module¶
- class kong.response.response[source]¶
Bases:
object
- static add_header(name: str, of: table) None [source]¶
Adds a response header with the given value. Unlike kong.response.set_header(), this function does not remove any existing header with the same name. Instead, another header with the same name is added to the response. If no header with this name already exists on the response, then it is added with the given value, similarly to kong.response.set_header().
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.add_header(“Cache-Control”, “no-cache”)
kong.response.add_header(“Cache-Control”, “no-store”)
- Parameters:
name (str) – The header name.
of (table) – strings|string|number|boolean value The header value.
- Returns:
throws an error on invalid input.
- Return type:
None
- static clear_header(name: str) None [source]¶
Removes all occurrences of the specified header in the response sent to the client.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_header(“X-Foo”, “foo”)
kong.response.add_header(“X-Foo”, “bar”)
kong.response.clear_header(“X-Foo”)
# from here onwards, no X-Foo headers will exist in the response
- Parameters:
name (str) – The name of the header to be cleared
- Returns:
throws an error on invalid input.
- Return type:
None
- static error(status: number, message: str | None, headers: table | None) None [source]¶
This function interrupts the current processing and produces an error response. It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:
`lua return kong.response.error(500, "Error", {["Content-Type"] = "text/html"}) `
1. The status argument sets the status code of the response that is seen by the client. The status code must an error code, that is, greater than 399. 2. The optional message argument sets the message describing the error, which is written in the body. 3. The optional headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers().This method sends the response formatted in JSON, XML, HTML or plaintext. The actual format is determined using one of the following options, in this order: - Manually specified in the headers argument using the Content-Type header. - Conforming to the Accept header from the request. - If there is no setting in the Content-Type or Accept header, the response defaults to JSON format. Also see the Content-Length header in the produced response for convenience.
- Phases:
rewrite, access, admin_api, header_filter, only, if, body, is, nil
- Example:
return kong.response.error(403, “Access Forbidden”, {
[“Content-Type”] = “text/plain”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.error(403, “Access Forbidden”)
# -
return kong.response.error(403)
- Parameters:
status (number) – The status to be used (>399).
message (str) – The error message to be used.
headers (table) – The headers to be used.
- Returns:
throws an error on invalid input.
- Return type:
None
- static exit(status: number, body: bytes | None, headers: table | None) None [source]¶
This function interrupts the current processing and produces a response. It is typical to see plugins using it to produce a response before Kong has a chance to proxy the request (e.g. an authentication plugin rejecting a request, or a caching plugin serving a cached response). It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:
`lua return kong.response.exit(200, "Success") `
Calling kong.response.exit() interrupts the execution flow of plugins in the current phase. Subsequent phases will still be invoked. For example, if a plugin calls kong.response.exit() in the access phase, no other plugin is executed in that phase, but the header_filter, body_filter, and log phases are still executed, along with their plugins. Plugins should be programmed defensively against cases when a request is not proxied to the Service, but instead is produced by Kong itself. 1. The first argument status sets the status code of the response that is seen by the client.In L4 proxy mode, the status code provided is primarily for logging and statistical purposes, and is not visible to the client directly. In this mode, only the following status codes are supported: * 200 - OK * 400 - Bad request * 403 - Forbidden * 500 - Internal server error * 502 - Bad gateway * 503 - Service unavailable
The second, optional, body argument sets the response body. If it is a string, no special processing is done, and the body is sent as-is. It is the caller’s responsibility to set the appropriate Content-Type header via the third argument. As a convenience, body can be specified as a table. In that case, the body is JSON-encoded and has the application/json Content-Type header set. On gRPC, we cannot send the body with this function, so it sends “body” in the grpc-message header instead. * If the body is a table, it looks for the message field in the body, and uses that as a grpc-message header. * If you specify application/grpc in the Content-Type header, the body is sent without needing the grpc-message header. In L4 proxy mode, body can only be nil or a string. Automatic JSON encoding is not available. When body is provided, depending on the value of status, the following happens: * When status is 500, 502 or 503, then body is logged in the Kong error log file. * When the status is anything else, body is sent back to the L4 client.
The third, optional, headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers(). This argument is ignored in L4 proxy mode.
Unless manually specified, this method automatically sets the Content-Length header in the produced response for convenience.
- Phases:
preread, rewrite, access, admin_api, header_filter, only, if, body, is, nil
- Example:
return kong.response.exit(403, “Access Forbidden”, {
[“Content-Type”] = “text/plain”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.exit(403, [[{“message”:”Access Forbidden”}]], {
[“Content-Type”] = “application/json”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.exit(403, { message = “Access Forbidden” }, {
[“WWW-Authenticate”] = “Basic”
})
# -
# In L4 proxy mode
return kong.response.exit(200, “Success”)
- Parameters:
status (number) – The status to be used.
body (bytes) – The body to be used.
headers (table) – The headers to be used.
- Returns:
throws an error on invalid input.
- Return type:
None
- static get_header(name: str) str [source]¶
Returns the value of the specified response header, as would be seen by the client once received. The list of headers returned by this function can consist of both response headers from the proxied Service _and_ headers added by Kong (e.g. via kong.response.add_header()). The return value is either a string, or can be nil if a header with name is not found in the response. If a header with the same name is present multiple times in the request, this function returns the value of the first occurrence of this header.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
# Given a response with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
kong.response.get_header(“x-custom-header”) # “bla”
kong.response.get_header(“X-Another”) # “foo bar”
kong.response.get_header(“X-None”) # nil
- Parameters:
name (str) – The name of the header. Header names are case-insensitive and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header.
- Returns:
The value of the header.
- Return type:
str
- static get_headers(max_headers: number | None) Tuple[table, str] [source]¶
Returns a Lua table holding the response headers. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header. A response initially has no headers. Headers are added when a plugin short-circuits the proxying by producing a header (e.g. an authentication plugin rejecting a request), or if the request has been proxied, and one of the latter execution phases is currently running. Unlike kong.service.response.get_headers(), this function returns all headers as the client would see them upon reception, including headers added by Kong itself. By default, this function returns up to 100 headers (or what has been configured using lua_max_resp_headers). The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and equal to or less than 1000.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
# Given an response from the Service with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
headers = kong.response.get_headers()
headers.x_custom_header # “bla”
headers.x_another[1] # “foo bar”
headers[“X-Another”][2] # “baz”
- Parameters:
max_headers (number) – Limits the number of headers parsed.
- Returns:
headers A table representation of the headers in the response.
- Return type:
table
- Returns:
err If more headers than max_headers were present, returns a string with the error “truncated”.
- Return type:
str
- static get_source() str [source]¶
This function helps determine where the current response originated from. Since Kong is a reverse proxy, it can short-circuit a request and produce a response of its own, or the response can come from the proxied Service. Returns a string with three possible values: * “exit” is returned when, at some point during the processing of the
request, there has been a call to kong.response.exit(). This happens when the request was short-circuited by a plugin or by Kong itself (e.g. invalid credentials).
“error” is returned when an error has happened while processing the request. For example, a timeout while connecting to the upstream service.
“service” is returned when the response was originated by successfully contacting the proxied Service.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
if kong.response.get_source() == “service”:
kong.log(“The response comes from the Service”)
elseif kong.response.get_source() == “error”:
kong.log(“There was an error while processing the request”)
elseif kong.response.get_source() == “exit”:
kong.log(“There was an early exit while processing the request”)
- Returns:
The source.
- Return type:
str
- static get_status() number [source]¶
Returns the HTTP status code currently set for the downstream response (as a Lua number). If the request was proxied (as per kong.response.get_source()), the return value is the response from the Service (identical to kong.service.response.get_status()). If the request was _not_ proxied and the response was produced by Kong itself (i.e. via kong.response.exit()), the return value is returned as-is.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
kong.response.get_status() # 200
- Returns:
status The HTTP status code currently set for the downstream response.
- Return type:
number
- static set_header(name: str, of: table) None [source]¶
Sets a response header with the given value. This function overrides any existing header with the same name. Note: Underscores in header names are automatically transformed into dashes by default. If you want to deactivate this behavior, set the lua_transform_underscores_in_response_headers Nginx config option to off. This setting can be set in the Kong Config file:
nginx_http_lua_transform_underscores_in_response_headers = off
Be aware that changing this setting might break any plugins that rely on the automatic underscore conversion. You cannot set Transfer-Encoding header with this function. It will be ignored.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_header(“X-Foo”, “value”)
- Parameters:
name (str) – The name of the header
of (table) – strings|string|number|boolean value The new value for the header.
- Returns:
throws an error on invalid input.
- Return type:
None
- static set_headers(headers: table) None [source]¶
Sets the headers for the response. Unlike kong.response.set_header(), the headers argument must be a table in which each key is a string corresponding to a header’s name, and each value is a string, or an array of strings. The resulting headers are produced in lexicographical order. The order of entries with the same name (when values are given as an array) is retained. This function overrides any existing header bearing the same name as those specified in the headers argument. Other headers remain unchanged. You cannot set Transfer-Encoding header with this function. It will be ignored.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_headers({
[“Bla”] = “boo”,
[“X-Foo”] = “foo3”,
[“Cache-Control”] = { “no-store”, “no-cache” }
})
# Will add the following headers to the response, in this order:
# X-Bar: bar1
# Bla: boo
# Cache-Control: no-store
# Cache-Control: no-cache
# X-Foo: foo3
- Parameters:
headers (table)
- Returns:
throws an error on invalid input.
- Return type:
None
- static set_status(status: number) None [source]¶
Allows changing the downstream response HTTP status code before sending it to the client.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_status(404)
- Parameters:
status (number) – The new status.
- Returns:
throws an error on invalid input.
- Return type:
None
kong.router module¶
- class kong.router.router[source]¶
Bases:
object
- static get_route() table [source]¶
Returns the current route entity. The request is matched against this route.
- Phases:
access, header_filter, response, body_filter, log
- Example:
route = kong.router.get_route()
protocols = route.protocols
- Returns:
The route entity.
- Return type:
table
- static get_service() table [source]¶
Returns the current service entity. The request is targeted to this upstream service.
- Phases:
access, header_filter, response, body_filter, log
- Example:
if kong.router.get_service():
# routed by route & service entities
else:
# routed by a route without a service
- Returns:
The service entity.
- Return type:
table
kong.telemetry module¶
- class kong.telemetry.telemetry[source]¶
Bases:
object
- static log(plugin_name: str, plugin_config: table, message_type: str, message: str, attributes: table) None [source]¶
Records a structured log entry, to be reported via the OpenTelemetry plugin. This function has a dependency on the OpenTelemetry plugin, which must be configured to report OpenTelemetry logs.
- Phases:
rewrite, access, balancer, timer, header_filter, response, body_filter, log
- Example:
attributes = {
http_method = kong.request.get_method()
[“node.id”] = kong.node.get_id(),
hostname = kong.node.get_hostname(),
}
ok, err = kong.telemetry.log(“my_plugin”, conf, “result”, “successful operation”, attributes)
- Parameters:
plugin_name (str) – the name of the plugin
plugin_config (table) – the plugin configuration
message_type (str) – the type of the log message, useful to categorize the log entry
message (str) – the log message
attributes (table) – structured information to be included in the attributes field of the log entry
kong.vault module¶
- class kong.vault.vault[source]¶
Bases:
object
- static flush() None [source]¶
Flush vault LRU cache and start a timer to rotate secrets. @local
- Example:
kong.vault.flush()
- static get(reference: str) Tuple[str, str] [source]¶
Resolves the passed in reference and returns the value of it.
- Example:
value, err = kong.vault.get(“{vault://env/cert/key}”)
- Parameters:
reference (str) – reference to resolve
- Returns:
resolved value of the reference
- Return type:
str
- Returns:
error message on failure, otherwise nil
- Return type:
str
- static init_worker() None [source]¶
Initializes vault. Registers event handlers (on non-dbless nodes) and starts a recurring secrets rotation timer. Does nothing on control planes. @local
- static is_reference(reference: str) bool [source]¶
Checks if the passed in reference looks like a reference. Valid references start with ‘{vault://’ and end with ‘}’. If you need more thorough validation, use kong.vault.parse_reference.
- Example:
kong.vault.is_reference(“{vault://env/key}”) # true
kong.vault.is_reference(“not a reference”) # false
- Parameters:
reference (str) – reference to check
- Returns:
true is the passed in reference looks like a reference, otherwise false
- Return type:
bool
- static parse_reference(reference: str) Tuple[table, str] [source]¶
Parses and decodes the passed in reference and returns a table containing its components. Given a following resource:
`lua "{vault://env/cert/key?prefix=SSL_#1}" `
This function will return following table: ```lua {name = “env”, – name of the Vault entity or Vault strategy resource = “cert”, – resource where secret is stored key = “key”, – key to lookup if the resource is secret object config = { – if there are any config options specified
prefix = “SSL_”
}, version = 1 – if the version is specified
- Example:
ref, err = kong.vault.parse_reference(“{vault://env/cert/key?prefix=SSL_#1}”) # table
- Parameters:
reference (str) – reference to parse
- Returns:
a table containing each component of the reference, or nil on error
- Return type:
table
- Returns:
error message on failure, otherwise nil
- Return type:
str
- static update(options: table) table [source]¶
Helper function for secret rotation based on TTLs. Currently experimental.
- Example:
options = kong.vault.update({
cert = “# # -BEGIN CERTIFICATE# # -…”,
key = “# # -BEGIN RSA PRIVATE KEY# # -…”,
cert_alt = “# # -BEGIN CERTIFICATE# # -…”,
key_alt = “# # -BEGIN EC PRIVATE KEY# # -…”,
[“$refs”] = {
cert = “{vault://aws/cert}”,
key = “{vault://aws/key}”,
cert_alt = “{vault://aws/cert-alt}”,
key_alt = “{vault://aws/key-alt}”,
}
})
# or
options = {
cert = “# # -BEGIN CERTIFICATE# # -…”,
key = “# # -BEGIN RSA PRIVATE KEY# # -…”,
cert_alt = “# # -BEGIN CERTIFICATE# # -…”,
key_alt = “# # -BEGIN EC PRIVATE KEY# # -…”,
[“$refs”] = {
cert = “{vault://aws/cert}”,
key = “{vault://aws/key}”,
cert_alt = “{vault://aws/cert-alt}”,
key_alt = “{vault://aws/key-alt}”,
}
}
kong.vault.update(options)
- Parameters:
options (table) – options containing secrets and references (this function modifies the input options)
- Returns:
options with updated secret values
- Return type:
table
Module contents¶
- class kong.kong[source]¶
Bases:
object
- class client¶
Bases:
object
- static authenticate(consumer: table, credential: table) None ¶
Sets the authenticated consumer and/or credential as well as the authenticated consumer-group for the current request. While both consumer and credential can be nil, at least one of them must exist. Otherwise, this function will throw an error.
- Phases:
access
- Example:
# assuming credential and consumer have been set by some authentication code
kong.client.authenticate(consumer, credentials)
- Parameters:
consumer (table) – The consumer to set. If no value is provided, then any existing value will be cleared.
credential (table) – The credential to set. If no value is provided, then any existing value will be cleared.
- static authenticate_consumer_group_by_consumer_id(consumer_id: str) None ¶
If the consumer_id is neither a string nor nil, it throws an error. If the consumer group has already been authenticated, it doesn’t override the group. The function performs a redis-SCAN-like lookup using a subset of the cache_key. The consumer_group_mapping is sorted by group name for deterministic behavior, but this might be changed in future releases.
- Phases:
access
- Example:
# assuming consumer_id is provided by some code
kong.client.authenticate_consumer_group_by_consumer_id(consumer_id)
- Parameters:
consumer_id (str) – The consumer id to use for setting the consumer group. If no value is provided, the current consumer group is not changed.
- static get_consumer() table ¶
Returns the consumer entity of the currently authenticated consumer. If not set yet, it returns nil.
- Phases:
access, header_filter, response, body_filter, log
- Example:
consumer = kong.client.get_consumer()
if consumer:
consumer_id = consumer.id
else:
# request not authenticated yet, or a credential
# without a consumer (external auth)
- Returns:
The authenticated consumer entity.
- Return type:
table
- static get_consumer_group() table ¶
This function is deprecated in favor of get_consumer_groups. Retrieves the authenticated consumer group for the current request.
- Phases:
auth_and_later
- Example:
group = kong.client.get_consumer_group()
- Returns:
The authenticated consumer group. Returns nil if no consumer group has been authenticated for the current request.
- Return type:
table
- static get_consumer_groups() table ¶
Retrieves the authenticated consumer groups for the current request.
- Phases:
auth_and_later
- Example:
groups = kong.client.get_consumer_groups()
- Returns:
The authenticated consumer groups. Returns nil if no consumer groups has been authenticated for the current request.
- Return type:
table
- static get_credential() str ¶
Returns the credentials of the currently authenticated consumer. If not set yet, it returns nil.
- Phases:
access, header_filter, response, body_filter, log
- Example:
credential = kong.client.get_credential()
if credential:
consumer_id = credential.consumer_id
else:
# request not authenticated yet
- Returns:
The authenticated credential.
- Return type:
str
- static get_forwarded_ip() str ¶
Returns the remote address of the client making the request. Unlike kong.client.get_ip, this function will consider forwarded addresses in cases when a load balancer is in front of Kong. Whether this function returns a forwarded address or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive)
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# Given a client with IP 127.0.0.1 making connection through
# a load balancer with IP 10.0.0.1 to Kong answering the request for
# https://username:password@example.com:1234/v1/movies
kong.client.get_forwarded_ip() # “127.0.0.1”
# Note: This example assumes that 10.0.0.1 is one of the trusted IPs, and that
# the load balancer adds the right headers matching with the configuration
# of real_ip_header, e.g. proxy_protocol.
- Returns:
The remote IP address of the client making the request, considering forwarded addresses.
- Return type:
str
- static get_forwarded_port() number ¶
Returns the remote port of the client making the request. Unlike kong.client.get_port, this function will consider forwarded ports in cases when a load balancer is in front of Kong. Whether this function returns a forwarded port or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive)
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# [client]:40000 <-> 80:[balancer]:30000 <-> 80:[kong]:20000 <-> 80:[service]
kong.client.get_forwarded_port() # 40000
# Note: This example assumes that [balancer] is one of the trusted IPs, and that
# the load balancer adds the right headers matching with the configuration
# of real_ip_header, e.g. proxy_protocol.
- Returns:
The remote client port, considering forwarded ports.
- Return type:
number
- static get_ip() str ¶
Returns the remote address of the client making the request. This module always returns the address of the client directly connecting to Kong. That is, in cases when a load balancer is in front of Kong, this function returns the load balancer’s address, and not that of the downstream client.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# Given a client with IP 127.0.0.1 making connection through
# a load balancer with IP 10.0.0.1 to Kong answering the request for
# https://example.com:1234/v1/movies
kong.client.get_ip() # “10.0.0.1”
- Returns:
The remote IP address of the client making the request.
- Return type:
str
- static get_port() number ¶
Returns the remote port of the client making the request. This always returns the port of the client directly connecting to Kong. That is, in cases when a load balancer is in front of Kong, this function returns the load balancer’s port, and not that of the downstream client.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# [client]:40000 <-> 80:[balancer]:30000 <-> 80:[kong]:20000 <-> 80:[service]
kong.client.get_port() # 30000
- Returns:
The remote client port.
- Return type:
number
- static get_protocol(allow_terminated: bool | None) Tuple[str, str] ¶
Returns the protocol matched by the current route (“http”, “https”, “tcp” or “tls”), or nil, if no route has been matched, which can happen when dealing with erroneous requests.
- Phases:
access, header_filter, response, body_filter, log
- Example:
kong.client.get_protocol() # “http”
- Parameters:
allow_terminated (bool) – If set, the X-Forwarded-Proto header is checked when checking for HTTPS.
- Returns:
Can be one of “http”, “https”, “tcp”, “tls” or nil.
- Return type:
str
- Returns:
nil if successful, or an error message if it fails.
- Return type:
err
- static load_consumer(consumer_id: str, search_by_username: bool | None) Tuple[table, str] ¶
Returns the consumer from the datastore. Looks up the consumer by ID, and can optionally do a second search by name.
- Phases:
access, header_filter, response, body_filter, log
- Example:
consumer_id = “john_doe”
consumer = kong.client.load_consumer(consumer_id, true)
- Parameters:
consumer_id (str) – The consumer ID to look up.
search_by_username (bool) – If truthy, and if the consumer is not found by ID, then a second search by username will be performed.
- Returns:
Consumer entity or nil.
- Return type:
table
- Returns:
nil if successful, or an error message if it fails.
- Return type:
err
- static set_authenticated_consumer_group(group: table) None ¶
This function is deprecated in favor of set_authenticated_consumer_groups. Explicitly sets the authenticated consumer group for the current request. Throws an error if the group is neither a table nor nil.
- Phases:
auth_and_later
- Example:
# assuming group is provided by some code
kong.client.set_authenticated_consumer_group(group)
- Parameters:
group (table) – The consumer group to set. If no value is provided, then any existing value will be cleared. this value should be a table with metadata of the group like its id and name.
- static set_authenticated_consumer_groups(groups: table) None ¶
Explicitly sets the authenticated consumer groups for the current request. Throws an error if the groups parameter is neither a table nor nil.
- Phases:
auth_and_later
- Example:
kong.client.set_authenticated_consumer_groups({
{
id = “fed2bf38-10c4-404e-8d45-a2b0f521464d”,
name = “my-group”,
},
{
id = “736bb9d9-98f2-46d5-97fc-d7361d9488ee”,
name = “my-other-group”,
}
})
- Parameters:
groups (table) – The consumer groups to set. If no value is provided, then any existing value will be cleared. This value should be a sequence-like table of tables, with each item having at least an id and a name.
- class tls¶
Bases:
object
- static disable_session_reuse() Tuple[bool, str] ¶
Prevents the TLS session for the current connection from being reused by disabling the session ticket and session ID for the current TLS connection.
- Phases:
certificate
- Example:
res, err = kong.client.tls.disable_session_reuse()
if not res:
# do something with err
- Returns:
Returns true if successful, nil if it fails.
- Return type:
bool
- Returns:
Returns nil if successful, or an error message if it fails.
- Return type:
err
- static get_full_client_certificate_chain() Tuple[str, str] ¶
Returns the PEM encoded downstream client certificate chain with the client certificate at the top and intermediate certificates (if any) at the bottom.
- Phases:
rewrite, access, balancer, header_filter, body_filter, log
- Example:
cert, err = kong.client.tls.get_full_client_certificate_chain()
if err:
# do something with errif not cert:
# client did not complete mTLS# do something with cert
- Returns:
Returns a PEM-encoded client certificate if the mTLS handshake was completed, or nil if an error occurred or the client did not present its certificate.
- Return type:
str
- Returns:
Returns nil if successful, or an error message if it fails.
- Return type:
err
- static request_client_certificate(ca_certs: Any | None) Tuple[bool, str] ¶
Requests the client to present its client-side certificate to initiate mutual TLS authentication between server and client. This function requests, but does not require the client to start the mTLS process. The TLS handshake can still complete even if the client doesn’t present a client certificate. However, in that case, it becomes a TLS connection instead of an mTLS connection, as there is no mutual authentication. To find out whether the client honored the request, use get_full_client_certificate_chain in later phases. The ca_certs argument is the optional CA certificate chain opaque pointer, which can be created by the [parse_pem_cert](https://github.com/openresty/lua-resty-core/blob/master/lib/ngx/ssl.md#parse_pem_cert) or [resty.opensslx509.chain](https://github.com/fffonion/lua-resty-openssl#restyopensslx509chain) The Distinguished Name (DN) list hints of the CA certificates will be sent to clients. If omitted, will not send any DN list to clients.
- Phases:
certificate
- Example:
x509_lib = require “resty.openssl.x509”
chain_lib = require “resty.openssl.x509.chain”
res, err
chain = chain_lib.new()
# err check
x509, err = x509_lib.new(pem_cert, “PEM”)
# err check
res, err = chain:add(x509)
# err check
# chain.ctx is the raw data of the chain, i.e. STACK_OF(X509) *
res, err = kong.client.tls.request_client_certificate(chain.ctx)
if not res:
# do something with err
- Parameters:
ca_certs (cdata) – The CA certificate chain opaque pointer
- Returns:
Returns true if successful, or nil if it fails.
- Return type:
bool
- Returns:
Returns nil if successful, or an error message if it fails.
- Return type:
err
- static set_client_verify() None ¶
Overrides the client’s verification result generated by the log serializer. By default, the request.tls.client_verify field inside the log generated by Kong’s log serializer is the same as the [$ssl_client_verify](https://nginx.org/en/docs/http/ngx_http_ssl_module.html#var_ssl_client_verify) Nginx variable. Only “SUCCESS”, “NONE”, or “FAILED:<reason>” are accepted values. This function does not return anything on success, and throws a Lua error in case of a failure.
- Phases:
rewrite, access, balancer
- Example:
kong.client.tls.set_client_verify(“FAILED:unknown CA”)
- class cluster¶
Bases:
object
- static get_id() Tuple[str, str] ¶
Returns the unique ID for this Kong cluster. If Kong is running in DB-less mode without a cluster ID explicitly defined, then this method returns nil. For hybrid mode, all control planes and data planes belonging to the same cluster return the same cluster ID. For traditional database-based deployments, all Kong nodes pointing to the same database also return the same cluster ID.
- Example:
id, err = kong.cluster.get_id()
if err:
# handle errorif not id:
# no cluster ID is available# use id here
- Returns:
The v4 UUID used by this cluster as its ID.
- Return type:
str
- Returns:
An error message.
- Return type:
str
- class ctx¶
Bases:
object
Bases:
object
get a key-value pair from Kong’s shared memory
- Parameters:
k (str) – key for the ctx data
- Returns:
the per-request context data in ngx.ctx
- Return type:
Any
set a key-value pair in Kong’s shared memory
- Parameters:
k (str) – key for the ctx data
v (str) – value for the ctx data
- class enterprise_edition¶
Bases:
object
- class jwe¶
Bases:
object
- static decode(token: str) Tuple[str, str] ¶
This function will return a table that looks like this: ``` {
[1] = protected header (as it appears in token) [2] = encrypted key (as it appears in token) [3] = initialization vector (as it appears in token) [4] = ciphertext (as it appears in token) [5] = authentication tag (as it appears in token) protected = protected key (base64url decoded and json decoded) encrypted_key = encrypted key (base64url decoded) iv = initialization vector (base64url decoded) ciphertext = ciphertext (base64url decoded) tag = authentication tag (base64url decoded) aad = protected header (as it appears in token)
The original input can be reconstructed with:
` local token = table.concat(<decoded-table>, ".") `
If there is not exactly 5 parts in JWT token, or any decoding fails, the error is returned. @usage local jwe = require “kong.enterprise_edition.jwe” local jwt, err = jwe.decode(“eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImFwdSI6Ik1lUFhUS2oyWFR1NUktYldUSFI2bXci” .. “LCJhcHYiOiJmUHFoa2hfNkdjVFd1SG5YWFZBclVnIiwiZXBrIjp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYi” .. “LCJ4IjoiWWd3eF9NVXRLTW9NYUpNZXFhSjZjUFV1Z29oYkVVc0I1NndrRlpYRjVMNCIsInkiOiIxaEYzYzlR” .. “VEhELVozam1vYUp2THZwTGJqcVNaSW9KNmd4X2YtUzAtZ21RIn19..4ZrIopIhLi3LeXyE.-Ke4ofA.MI5lT” .. “kML5NIa-Twm-92F6Q”)
- if jwt then
print(jwt.protected.alg) – outputs “ECDH-ES”
end
- Parameters:
token (str) – JWE encrypted JWT token
- Returns:
A table containing JWT token parts decoded, or nil
- Return type:
str
- Returns:
Error message, or nil
- Return type:
str
- static decrypt(key: Any, token: str) Tuple[str, str] ¶
Supported keys (key argument): * Supported key formats:
JWK (given as a string or table)
PEM (given as a string)
DER (given as a string)
Supported key types: * RSA * EC, supported curves:
P-256
P-384
P-521
@usage local jwe = require “kong.enterprise_edition.jwe” local jwk = {
kty = “EC”, crv = “P-256”, use = “enc”, x = “MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4”, y = “4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM”, d = “870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE”,
} local plaintext, err = jwe.decrypt(jwk,
“eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImFwdSI6Ik1lUFhUS2oyWFR1NUktYldUSFI2bXci” .. “LCJhcHYiOiJmUHFoa2hfNkdjVFd1SG5YWFZBclVnIiwiZXBrIjp7Imt0eSI6IkVDIiwiY3J2IjoiUC0yNTYi” .. “LCJ4IjoiWWd3eF9NVXRLTW9NYUpNZXFhSjZjUFV1Z29oYkVVc0I1NndrRlpYRjVMNCIsInkiOiIxaEYzYzlR” .. “VEhELVozam1vYUp2THZwTGJqcVNaSW9KNmd4X2YtUzAtZ21RIn19..4ZrIopIhLi3LeXyE.-Ke4ofA.MI5lT” .. “kML5NIa-Twm-92F6Q”)
- if plaintext then
print(plaintext) – outputs “hello”
end
- Parameters:
key (Any) – Private key
token (str) – JWE encrypted JWT token
- Returns:
JWT token payload in plaintext, or nil
- Return type:
str
- Returns:
Error message, or nil
- Return type:
str
- static encrypt(alg: str, enc: str, key: Any, plaintext: str, options: table | None) Tuple[str, str] ¶
Supported algorithms (alg argument): * “RSA-OAEP” * “ECDH-ES” Supported encryption algorithms (enc argument): * “A256GCM” Supported keys (key argument): * Supported key formats:
JWK (given as a string or table)
PEM (given as a string)
DER (given as a string)
Supported key types: * RSA * EC, supported curves:
P-256
P-384
P-521
Supported options (options argument): * { zip = “DEF” }: whether to deflate the plaintext before encrypting * { apu = <string|boolean> }: Agreement PartyUInfo header parameter * { apv = <string|boolean> }: Agreement PartyVInfo header parameter The apu and apv can also be set to false to prevent them from being auto-generated (sixteen random bytes) and added to ephemeral public key. @usage local jwe = require “kong.enterprise_edition.jwe” local jwk = {
kty = “EC”, crv = “P-256”, use = “enc”, x = “MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4”, y = “4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM”,
} local token, err = jwe.encrypt(“ECDH-ES”, “A256GCM”, jwk, “hello”, {
zip = “DEF,
}) if token then
print(token)
end
- Parameters:
alg (str) – Algorithm used for key management
enc (str) – Encryption algorithm used for content encryption
key (Any) – Public key
plaintext (str) – Plaintext
options (table) – Options (optional), default: nil
- Returns:
JWE encrypted JWT token, or nil
- Return type:
str
- Returns:
Error message, or nil
- Return type:
str
- class ip¶
Bases:
object
- static is_trusted(address: str) bool ¶
Depending on the trusted_ips configuration property, this function returns whether a given IP is trusted or not. Both ipv4 and ipv6 are supported.
- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
if kong.ip.is_trusted(“1.1.1.1”):
kong.log(“The IP is trusted”)
- Parameters:
address (str) – A string representing an IP address.
- Returns:
true if the IP is trusted, false otherwise.
- Return type:
bool
- class log¶
Bases:
object
- static alert(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static crit(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static debug(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static deprecation(*args: Any) None ¶
Arguments given to this function can be of any type, but table arguments are converted to strings via tostring (thus potentially calling a table’s __tostring metamethod if set). When the last argument is a table, it is considered as a deprecation metadata. The table can include the following properties: ``` lua {
after = “2.5.0”, – deprecated after Kong version 2.5.0 (defaults to nil) removal = “3.0.0”, – about to be removed with Kong version 3.0.0 (defaults to nil) trace = true, – writes stack trace along with the deprecation message (defaults to nil)
For example, the following call:
` lua kong.log.deprecation("hello ", "world") `
would, within the core, produce a log line similar to:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
If invoked from within a plugin (for example, key-auth) it would include the namespace prefix:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
And with metatable, the following call:` lua kong.log.deprecation("hello ", "world", { after = "2.5.0", removal = "3.0.0" }) `
would, within the core, produce a log line similar to:` plain 2017/07/09 19:36:25 [warn] 25932#0: *1 [kong] some_file.lua:54 hello world (deprecated after 2.5.0, scheduled for removal in 3.0.0), client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost" `
- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.deprecation(“hello “, “world”)
kong.log.deprecation(“hello “, “world”, { after = “2.5.0” })
kong.log.deprecation(“hello “, “world”, { removal = “3.0.0” })
kong.log.deprecation(“hello “, “world”, { after = “2.5.0”, removal = “3.0.0” })
kong.log.deprecation(“hello “, “world”, { trace = true })
- Parameters:
*args –
all params will be concatenated and stringified before being sent to the log (if the last param is a table, it is considered as a deprecation metadata)
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static err(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static info(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static notice(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- static serialize() None ¶
- static set_serialize_value(key: str, value: Any, options: table) table ¶
Sets a value to be used on the serialize custom table. Logging plugins use the output of kong.log.serialize() as a base for their logs. This function lets you customize the log output. It can be used to replace existing values in the output, or to delete existing values by passing nil. Note: The type-checking of the value parameter can take some time, so it is deferred to the serialize() call, which happens in the log phase in most real-usage cases.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
# Adds a new value to the serialized table
kong.log.set_serialize_value(“my_new_value”, 1)
assert(kong.log.serialize().my_new_value == 1)
# Value can be a table
kong.log.set_serialize_value(“my”, { new = { value = 2 } })
assert(kong.log.serialize().my.new.value == 2)
# It is possible to change an existing serialized value
kong.log.set_serialize_value(“my_new_value”, 3)
assert(kong.log.serialize().my_new_value == 3)
# Unset an existing value by setting it to nil
kong.log.set_serialize_value(“my_new_value”, nil)
assert(kong.log.serialize().my_new_value == nil)
# Dots in the key are interpreted as table accesses
kong.log.set_serialize_value(“my.new.value”, 4)
assert(kong.log.serialize().my.new_value == 4)
- Parameters:
key (str) – The name of the field.
value (Any) – Value to be set. When a table is used, its keys must be numbers, strings, or booleans, and its values can be numbers, strings, or other tables like itself, recursively.
options (table) – Can contain two entries: options.mode can be set (the default, always sets), add (only add if entry does not already exist) and replace (only change value if it already exists).
- Returns:
The request information table.
- Return type:
table
- static warn(*args: Any) None ¶
Similar to kong.log(), but the produced log has the severity given by <level>, instead of notice. The supported levels are: * kong.log.alert() * kong.log.crit() * kong.log.err() * kong.log.warn() * kong.log.notice() * kong.log.info() * kong.log.debug() Logs have the same format as that of kong.log(). For example, the following call: ``` lua
kong.log.err(“hello “, “world”)
` would, within the core, produce a log line similar to: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost”` If invoked from within a plugin (for example, `key-auth`) it would include the namespace prefix: `
plain 2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: “GET /log HTTP/1.1”, host: “localhost” ```- Phases:
init_worker, certificate, rewrite, access, header_filter, response, body_filter, log
- Example:
kong.log.warn(“something require attention”)
kong.log.err(“something failed: “, err)
kong.log.alert(“something requires immediate action”)
- Parameters:
*args –
All params will be concatenated and stringified before being sent to the log.
- Returns:
Throws an error on invalid inputs.
- Return type:
None
- class nginx¶
Bases:
object
- static get_ctx(k: str) Any ¶
get a key-value pair from Kong’s per-request context
- Parameters:
k (str) – key for the ctx data
- Returns:
the per-request context data in ngx.ctx
- Return type:
Any
- static get_statistics() table ¶
Returns various connection and request metrics exposed by Nginx, similar to those reported by the [ngx_http_stub_status_module](https://nginx.org/en/docs/http/ngx_http_stub_status_module.html#data). The following fields are included in the returned table: * connections_active - the current number of active client connections including connections_waiting. * connections_reading - the current number of connections where nginx is reading the request header. * connections_writing - the current number of connections where nginx is writing the response back to the client. * connections_waiting - the current number of idle client connections waiting for a request. * connections_accepted - the total number of accepted client connections. * connections_handled - the total number of handled connections. Same as connections_accepted unless some resource limits have been reached
(for example, the [worker_connections](https://nginx.org/en/docs/ngx_core_module.html#worker_connections) limit).
total_requests - the total number of client requests.
- Example:
nginx_statistics = kong.nginx.get_statistics()
- Returns:
Nginx connections and requests statistics
- Return type:
table
- static get_subsystem() str ¶
- Returns:
the subsystem name
- Return type:
str
- static get_tls1_version_str() str ¶
- Returns:
the TLSv1 version string
- Return type:
str
- static get_var() str ¶
- Returns:
get NGINX variable value
- Return type:
str
- static req_start_time() number ¶
get the current request’s start timestamp
- Returns:
req_start_time
- Return type:
number
- static set_ctx(k: str, any: str) None ¶
set a key-value pair in Kong’s per-request context
- Parameters:
k (str) – key for the ctx data
any (str) – value for the ctx data
Bases:
object
get a key-value pair from Kong’s shared memory
- Parameters:
k (str) – key for the ctx data
- Returns:
the per-request context data in ngx.ctx
- Return type:
Any
set a key-value pair in Kong’s shared memory
- Parameters:
k (str) – key for the ctx data
v (str) – value for the ctx data
- class node¶
Bases:
object
- static get_hostname() str ¶
Returns the name used by the local machine.
- Example:
hostname = kong.node.get_hostname()
- Returns:
The local machine hostname.
- Return type:
str
- static get_id() str ¶
Returns the ID used by this node to describe itself.
- Example:
id = kong.node.get_id()
- Returns:
The v4 UUID used by this node as its ID.
- Return type:
str
- static get_memory_stats(unit: str | None, scale: number | None) table ¶
Returns memory usage statistics about this node.
- Example:
res = kong.node.get_memory_stats()
# res will have the following structure:
{
lua_shared_dicts = {
kong = {
allocated_slabs = 12288,
capacity = 24576
},
kong_db_cache = {
allocated_slabs = 12288,
capacity = 12288
}
},
workers_lua_vms = {
{
http_allocated_gc = 1102,
pid = 18004
},
{
http_allocated_gc = 1102,
pid = 18005
}
}
}
res = kong.node.get_memory_stats(“k”, 1)
# res will have the following structure:
{
lua_shared_dicts = {
kong = {
allocated_slabs = “12.0 KiB”,
capacity = “24.0 KiB”,
},
kong_db_cache = {
allocated_slabs = “12.0 KiB”,
capacity = “12.0 KiB”,
}
},
workers_lua_vms = {
{
http_allocated_gc = “1.1 KiB”,
pid = 18004
},
{
http_allocated_gc = “1.1 KiB”,
pid = 18005
}
}
}
- Parameters:
unit (str) – The unit that memory is reported in. Can be any of b/B, k/K, m/M, or g/G for bytes, kibibytes, mebibytes, or gibibytes, respectively. Defaults to b (bytes).
scale (number) – The number of digits to the right of the decimal point. Defaults to 2.
- Returns:
A table containing memory usage statistics for this node. If unit is b/B (the default), reported values are Lua numbers. Otherwise, reported values are strings with the unit as a suffix.
- Return type:
table
- class plugin¶
Bases:
object
- static get_id() str ¶
Returns the instance ID of the plugin.
- Phases:
rewrite, access, header_filter, response, body_filter, log
- Example:
kong.plugin.get_id() # “123e4567-e89b-12d3-a456-426614174000”
- Returns:
The ID of the running plugin
- Return type:
str
- class request¶
Bases:
object
- static get_body(mimetype: str | None, max_args: number | None, max_allowed_file_size: number | None) Tuple[table, str, str] ¶
Returns the request data as a key/value table. A high-level convenience function. The body is parsed with the most appropriate format: * If mimetype is specified, it decodes the body with the requested
content type (if supported). This takes precedence over any content type present in the request. The optional argument mimetype can be one of the following strings:
application/x-www-form-urlencoded
application/json
multipart/form-data
Whether mimetype is specified or a request content type is otherwise present in the request, each content type behaves as follows: * If the request content type is application/x-www-form-urlencoded:
Returns the body as form-encoded.
If the request content type is multipart/form-data: * Decodes the body as multipart form data
(same as multipart(kong.request.get_raw_body(), kong.request.get_header(“Content-Type”)):get_all() ).
If the request content type is application/json: * Decodes the body as JSON
(same as json.decode(kong.request.get_raw_body())).
JSON types are converted to matching Lua types.
If the request contains none of the above and the mimetype argument is not set, returns nil and an error message indicating the body could not be parsed.
The optional argument max_args can be used to set a limit on the number of form arguments parsed for application/x-www-form-urlencoded payloads, which is by default 100 (or what has been configured using lua_max_post_args). The third return value is string containing the mimetype used to parsed the body (as per the mimetype argument), allowing the caller to identify what MIME type the body was parsed as.
- Phases:
rewrite, access, response, admin_api
- Example:
body, err, mimetype = kong.request.get_body()
body.name # “John Doe”
body.age # “42”
- Parameters:
mimetype (str) – The MIME type.
max_args (number) – Sets a limit on the maximum number of parsed
max_allowed_file_size (number) – the max allowed file size to be read from arguments.
- Returns:
A table representation of the body.
- Return type:
table
- Returns:
An error message.
- Return type:
str
- Returns:
mimetype The MIME type used.
- Return type:
str
- static get_forwarded_host() str ¶
Returns the host component of the request’s URL or the value of the “host” header. Unlike kong.request.get_host(), this function also considers X-Forwarded-Host if it comes from a trusted source. The returned value is normalized to lowercase. Whether this function considers X-Forwarded-Host or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_host() # “example.com”
- Returns:
The forwarded host.
- Return type:
str
- static get_forwarded_path() str ¶
Returns the path component of the request’s URL, but also considers X-Forwarded-Path if it comes from a trusted source. The value is returned as a Lua string. Whether this function considers X-Forwarded-Path or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not do any normalization on the request path.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_path() # /path
- Returns:
The forwarded path.
- Return type:
str
- static get_forwarded_port() number ¶
Returns the port component of the request’s URL, but also considers X-Forwarded-Host if it comes from a trusted source. The value is returned as a Lua number. Whether this function considers X-Forwarded-Proto or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module. When running Kong behind the L4 port mapping (or forwarding), you can also configure: * [port_maps](https://docs.konghq.com/gateway/latest/reference/configuration/#port_maps) The port_maps configuration parameter enables this function to return the port to which the port Kong is listening to is mapped to (in case they differ).
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_port() # 1234
- Returns:
The forwarded port.
- Return type:
number
- static get_forwarded_prefix() str ¶
Returns the prefix path component of the request’s URL that Kong stripped before proxying to upstream. It also checks if X-Forwarded-Prefix comes from a trusted source, and uses it as-is when given. The value is returned as a Lua string. If a trusted X-Forwarded-Prefix is not passed, this function must be called after Kong has run its router (access phase), as the Kong router may strip the prefix of the request path. That stripped path becomes the return value of this function, unless there is already a trusted X-Forwarded-Prefix header in the request. Whether this function considers X-Forwarded-Prefix or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not do any normalization on the request path prefix.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_prefix() # /prefix
- Returns:
The forwarded path prefix or nil if the prefix was not stripped.
- Return type:
str
- static get_forwarded_scheme() str ¶
Returns the scheme component of the request’s URL, but also considers X-Forwarded-Proto if it comes from a trusted source. The returned value is normalized to lowercase. Whether this function considers X-Forwarded-Proto or not depends on several Kong configuration parameters: * [trusted_ips](https://docs.konghq.com/gateway/latest/reference/configuration/#trusted_ips) * [real_ip_header](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_header) * [real_ip_recursive](https://docs.konghq.com/gateway/latest/reference/configuration/#real_ip_recursive) Note: Kong does not offer support for the Forwarded HTTP Extension (RFC 7239) since it is not supported by ngx_http_realip_module.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_forwarded_scheme() # “https”
- Returns:
The forwarded scheme.
- Return type:
str
- static get_header(name: str) str ¶
Returns the value of the specified request header. The returned value is either a string, or can be nil if a header with name was not found in the request. If a header with the same name is present multiple times in the request, this function returns the value of the first occurrence of this header. Header names in are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request with the following headers:
# Host: foo.com
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
kong.request.get_header(“Host”) # “foo.com”
kong.request.get_header(“x-custom-header”) # “bla”
kong.request.get_header(“X-Another”) # “foo bar”
- Parameters:
name (str) – the name of the header to be returned
- Returns:
the value of the header or nil if not present
- Return type:
str
- static get_headers(max_headers: number | None) table ¶
Returns a Lua table holding the request headers. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header. By default, this function returns up to 100 headers (or what has been configured using lua_max_req_headers). The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and not greater than 1000.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request with the following headers:
# Host: foo.com
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
headers = kong.request.get_headers()
headers.host # “foo.com”
headers.x_custom_header # “bla”
headers.x_another[1] # “foo bar”
headers[“X-Another”][2] # “baz”
- Parameters:
max_headers (number) – Sets a limit on the maximum number of parsed headers.
- Returns:
The request headers in table form.
- Return type:
table
- static get_host() str ¶
Returns the host component of the request’s URL, or the value of the “Host” header. The returned value is normalized to lowercase form.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_host() # “example.com”
- Returns:
The hostname.
- Return type:
str
- static get_http_version() number ¶
Returns the HTTP version used by the client in the request as a Lua number, returning values such as 1, 1.1, 2.0, or nil for unrecognized values.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_http_version() # 1.1
- Returns:
The HTTP version as a Lua number.
- Return type:
number
- static get_method() str ¶
Returns the HTTP method of the request. The value is normalized to uppercase.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_method() # “GET”
- Returns:
The request method.
- Return type:
str
- static get_path() str ¶
Returns the normalized path component of the request’s URL. The return value is the same as kong.request.get_raw_path() but normalized according to RFC 3986 section 6: * Percent-encoded values of unreserved characters are decoded (%20
becomes ` `).
Percent-encoded values of reserved characters have their hexidecimal value uppercased (%2f becomes %2F).
Relative path elements (/. and /..) are dereferenced.
Duplicate slashes are consolidated (// becomes /).
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/t/Abc%20123%C3%B8%2f/parent/..//test/./
kong.request.get_path() # “/t/Abc 123ø%2F/test/”
- Returns:
the path
- Return type:
str
- static get_path_with_query() str ¶
Returns the path, including the query string if any. No transformations or normalizations are done.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies?movie=foo
kong.request.get_path_with_query() # “/v1/movies?movie=foo”
- Returns:
The path with the query string.
- Return type:
str
- static get_port() number ¶
Returns the port component of the request’s URL. The value is returned as a Lua number.
- Phases:
certificate, rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_port() # 1234
- Returns:
The port.
- Return type:
number
- static get_query(max_args: number | None) table ¶
Returns the table of query arguments obtained from the query string. Keys are query argument names. Values are either a string with the argument value, a boolean true if an argument was not given a value, or an array if an argument was given in the query string multiple times. Keys and values are unescaped according to URL-encoded escaping rules. Note that a query string ?foo&bar translates to two boolean true arguments, and ?foo=&bar= translates to two string arguments containing empty strings. By default, this function returns up to 100 arguments (or what has been configured using lua_max_uri_args). The optional max_args argument can be specified to customize this limit, but must be greater than 1 and not greater than 1000.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
for k, v in pairs(kong.request.get_query()) do
kong.log.inspect(k, v)# Will print
# “foo” “hello world”
# “bar” {“baz”, “bla”, true}
# “zzz” true
# “blo” “”
- Parameters:
max_args (number) – Sets a limit on the maximum number of parsed arguments.
- Returns:
A table representation of the query string.
- Return type:
table
- static get_query_arg() Any ¶
Returns the value of the specified argument, obtained from the query arguments of the current request. The returned value is either a string, a boolean true if an argument was not given a value, or nil if no argument with name was found. If an argument with the same name is present multiple times in the query string, this function returns the value of the first occurrence.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
kong.request.get_query_arg(“foo”) # “hello world”
kong.request.get_query_arg(“bar”) # “baz”
kong.request.get_query_arg(“zzz”) # true
kong.request.get_query_arg(“blo”) # “”
- Returns:
The value of the argument.
- Return type:
Any
- static get_raw_body() Tuple[bytes, str] ¶
Returns the plain request body. If the body has no size (empty), this function returns an empty string. If the size of the body is greater than the Nginx buffer size (set by client_body_buffer_size), this function fails and returns an error message explaining this limitation, unless max_allowed_file_size is set and equal to 0 or larger than the body size buffered to disk. Use of max_allowed_file_size requires Kong to read data from filesystem and has performance implications.
- Phases:
rewrite, access, response, admin_api
- Example:
# Given a body with payload “Hello, Earth!”:
kong.request.get_raw_body():gsub(“Earth”, “Mars”) # “Hello, Mars!”
- Returns:
The plain request body or nil if it does not fit into the NGINX temporary buffer.
- Return type:
bytes
- Returns:
An error message.
- Return type:
str
- static get_raw_path() str ¶
Returns the path component of the request’s URL. It is not normalized in any way and does not include the query string. NOTE: Using the raw path to perform string comparision during request handling (such as in routing, ACL/authorization checks, setting rate-limit keys, etc) is widely regarded as insecure, as it can leave plugin code vulnerable to path traversal attacks. Prefer kong.request.get_path() for such use cases.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/t/Abc%20123%C3%B8%2f/parent/..//test/./?movie=foo
kong.request.get_raw_path() # “/t/Abc%20123%C3%B8%2f/parent/..//test/./”
- Returns:
The path.
- Return type:
str
- static get_raw_query() str ¶
Returns the query component of the request’s URL. It is not normalized in any way (not even URL-decoding of special characters) and does not include the leading ? character.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com/foo?msg=hello%20world&bla=&bar
kong.request.get_raw_query() # “msg=hello%20world&bla=&bar”
- Returns:
The query component of the request’s URL.
- Return type:
str
- static get_scheme() str ¶
Returns the scheme component of the request’s URL. The returned value is normalized to lowercase form.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
# Given a request to https://example.com:1234/v1/movies
kong.request.get_scheme() # “https”
- Returns:
A string like “http” or “https”.
- Return type:
str
- static get_start_time() number ¶
Returns the request start time, in Unix epoch milliseconds.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
kong.request.get_start_time() # 1649960273000
- Returns:
The timestamp
- Return type:
number
- static get_uri_captures() table ¶
Returns the URI captures matched by the router.
- Phases:
rewrite, access, header_filter, response, body_filter, log, admin_api
- Example:
captures = kong.request.get_uri_captures()
for idx, value in ipairs(captures.unnamed) do
# do what you want to capturesfor name, value in pairs(captures.named) do
# do what you want to captures
- Returns:
tables containing unamed and named captures.
- Return type:
table
- class response¶
Bases:
object
- static add_header(name: str, of: table) None ¶
Adds a response header with the given value. Unlike kong.response.set_header(), this function does not remove any existing header with the same name. Instead, another header with the same name is added to the response. If no header with this name already exists on the response, then it is added with the given value, similarly to kong.response.set_header().
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.add_header(“Cache-Control”, “no-cache”)
kong.response.add_header(“Cache-Control”, “no-store”)
- Parameters:
name (str) – The header name.
of (table) – strings|string|number|boolean value The header value.
- Returns:
throws an error on invalid input.
- Return type:
None
- static clear_header(name: str) None ¶
Removes all occurrences of the specified header in the response sent to the client.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_header(“X-Foo”, “foo”)
kong.response.add_header(“X-Foo”, “bar”)
kong.response.clear_header(“X-Foo”)
# from here onwards, no X-Foo headers will exist in the response
- Parameters:
name (str) – The name of the header to be cleared
- Returns:
throws an error on invalid input.
- Return type:
None
- static error(status: number, message: str | None, headers: table | None) None ¶
This function interrupts the current processing and produces an error response. It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:
`lua return kong.response.error(500, "Error", {["Content-Type"] = "text/html"}) `
1. The status argument sets the status code of the response that is seen by the client. The status code must an error code, that is, greater than 399. 2. The optional message argument sets the message describing the error, which is written in the body. 3. The optional headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers().This method sends the response formatted in JSON, XML, HTML or plaintext. The actual format is determined using one of the following options, in this order: - Manually specified in the headers argument using the Content-Type header. - Conforming to the Accept header from the request. - If there is no setting in the Content-Type or Accept header, the response defaults to JSON format. Also see the Content-Length header in the produced response for convenience.
- Phases:
rewrite, access, admin_api, header_filter, only, if, body, is, nil
- Example:
return kong.response.error(403, “Access Forbidden”, {
[“Content-Type”] = “text/plain”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.error(403, “Access Forbidden”)
# -
return kong.response.error(403)
- Parameters:
status (number) – The status to be used (>399).
message (str) – The error message to be used.
headers (table) – The headers to be used.
- Returns:
throws an error on invalid input.
- Return type:
None
- static exit(status: number, body: bytes | None, headers: table | None) None ¶
This function interrupts the current processing and produces a response. It is typical to see plugins using it to produce a response before Kong has a chance to proxy the request (e.g. an authentication plugin rejecting a request, or a caching plugin serving a cached response). It is recommended to use this function in conjunction with the return operator, to better reflect its meaning:
`lua return kong.response.exit(200, "Success") `
Calling kong.response.exit() interrupts the execution flow of plugins in the current phase. Subsequent phases will still be invoked. For example, if a plugin calls kong.response.exit() in the access phase, no other plugin is executed in that phase, but the header_filter, body_filter, and log phases are still executed, along with their plugins. Plugins should be programmed defensively against cases when a request is not proxied to the Service, but instead is produced by Kong itself. 1. The first argument status sets the status code of the response that is seen by the client.In L4 proxy mode, the status code provided is primarily for logging and statistical purposes, and is not visible to the client directly. In this mode, only the following status codes are supported: * 200 - OK * 400 - Bad request * 403 - Forbidden * 500 - Internal server error * 502 - Bad gateway * 503 - Service unavailable
The second, optional, body argument sets the response body. If it is a string, no special processing is done, and the body is sent as-is. It is the caller’s responsibility to set the appropriate Content-Type header via the third argument. As a convenience, body can be specified as a table. In that case, the body is JSON-encoded and has the application/json Content-Type header set. On gRPC, we cannot send the body with this function, so it sends “body” in the grpc-message header instead. * If the body is a table, it looks for the message field in the body, and uses that as a grpc-message header. * If you specify application/grpc in the Content-Type header, the body is sent without needing the grpc-message header. In L4 proxy mode, body can only be nil or a string. Automatic JSON encoding is not available. When body is provided, depending on the value of status, the following happens: * When status is 500, 502 or 503, then body is logged in the Kong error log file. * When the status is anything else, body is sent back to the L4 client.
The third, optional, headers argument can be a table specifying response headers to send. If specified, its behavior is similar to kong.response.set_headers(). This argument is ignored in L4 proxy mode.
Unless manually specified, this method automatically sets the Content-Length header in the produced response for convenience.
- Phases:
preread, rewrite, access, admin_api, header_filter, only, if, body, is, nil
- Example:
return kong.response.exit(403, “Access Forbidden”, {
[“Content-Type”] = “text/plain”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.exit(403, [[{“message”:”Access Forbidden”}]], {
[“Content-Type”] = “application/json”,
[“WWW-Authenticate”] = “Basic”
})
# -
return kong.response.exit(403, { message = “Access Forbidden” }, {
[“WWW-Authenticate”] = “Basic”
})
# -
# In L4 proxy mode
return kong.response.exit(200, “Success”)
- Parameters:
status (number) – The status to be used.
body (bytes) – The body to be used.
headers (table) – The headers to be used.
- Returns:
throws an error on invalid input.
- Return type:
None
- static get_header(name: str) str ¶
Returns the value of the specified response header, as would be seen by the client once received. The list of headers returned by this function can consist of both response headers from the proxied Service _and_ headers added by Kong (e.g. via kong.response.add_header()). The return value is either a string, or can be nil if a header with name is not found in the response. If a header with the same name is present multiple times in the request, this function returns the value of the first occurrence of this header.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
# Given a response with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
kong.response.get_header(“x-custom-header”) # “bla”
kong.response.get_header(“X-Another”) # “foo bar”
kong.response.get_header(“X-None”) # nil
- Parameters:
name (str) – The name of the header. Header names are case-insensitive and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header.
- Returns:
The value of the header.
- Return type:
str
- static get_headers(max_headers: number | None) Tuple[table, str] ¶
Returns a Lua table holding the response headers. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_). For example, the header X-Custom-Header can also be retrieved as x_custom_header. A response initially has no headers. Headers are added when a plugin short-circuits the proxying by producing a header (e.g. an authentication plugin rejecting a request), or if the request has been proxied, and one of the latter execution phases is currently running. Unlike kong.service.response.get_headers(), this function returns all headers as the client would see them upon reception, including headers added by Kong itself. By default, this function returns up to 100 headers (or what has been configured using lua_max_resp_headers). The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and equal to or less than 1000.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
# Given an response from the Service with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
headers = kong.response.get_headers()
headers.x_custom_header # “bla”
headers.x_another[1] # “foo bar”
headers[“X-Another”][2] # “baz”
- Parameters:
max_headers (number) – Limits the number of headers parsed.
- Returns:
headers A table representation of the headers in the response.
- Return type:
table
- Returns:
err If more headers than max_headers were present, returns a string with the error “truncated”.
- Return type:
str
- static get_source() str ¶
This function helps determine where the current response originated from. Since Kong is a reverse proxy, it can short-circuit a request and produce a response of its own, or the response can come from the proxied Service. Returns a string with three possible values: * “exit” is returned when, at some point during the processing of the
request, there has been a call to kong.response.exit(). This happens when the request was short-circuited by a plugin or by Kong itself (e.g. invalid credentials).
“error” is returned when an error has happened while processing the request. For example, a timeout while connecting to the upstream service.
“service” is returned when the response was originated by successfully contacting the proxied Service.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
if kong.response.get_source() == “service”:
kong.log(“The response comes from the Service”)
elseif kong.response.get_source() == “error”:
kong.log(“There was an error while processing the request”)
elseif kong.response.get_source() == “exit”:
kong.log(“There was an early exit while processing the request”)
- Returns:
The source.
- Return type:
str
- static get_status() number ¶
Returns the HTTP status code currently set for the downstream response (as a Lua number). If the request was proxied (as per kong.response.get_source()), the return value is the response from the Service (identical to kong.service.response.get_status()). If the request was _not_ proxied and the response was produced by Kong itself (i.e. via kong.response.exit()), the return value is returned as-is.
- Phases:
header_filter, response, body_filter, log, admin_api
- Example:
kong.response.get_status() # 200
- Returns:
status The HTTP status code currently set for the downstream response.
- Return type:
number
- static set_header(name: str, of: table) None ¶
Sets a response header with the given value. This function overrides any existing header with the same name. Note: Underscores in header names are automatically transformed into dashes by default. If you want to deactivate this behavior, set the lua_transform_underscores_in_response_headers Nginx config option to off. This setting can be set in the Kong Config file:
nginx_http_lua_transform_underscores_in_response_headers = off
Be aware that changing this setting might break any plugins that rely on the automatic underscore conversion. You cannot set Transfer-Encoding header with this function. It will be ignored.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_header(“X-Foo”, “value”)
- Parameters:
name (str) – The name of the header
of (table) – strings|string|number|boolean value The new value for the header.
- Returns:
throws an error on invalid input.
- Return type:
None
- static set_headers(headers: table) None ¶
Sets the headers for the response. Unlike kong.response.set_header(), the headers argument must be a table in which each key is a string corresponding to a header’s name, and each value is a string, or an array of strings. The resulting headers are produced in lexicographical order. The order of entries with the same name (when values are given as an array) is retained. This function overrides any existing header bearing the same name as those specified in the headers argument. Other headers remain unchanged. You cannot set Transfer-Encoding header with this function. It will be ignored.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_headers({
[“Bla”] = “boo”,
[“X-Foo”] = “foo3”,
[“Cache-Control”] = { “no-store”, “no-cache” }
})
# Will add the following headers to the response, in this order:
# X-Bar: bar1
# Bla: boo
# Cache-Control: no-store
# Cache-Control: no-cache
# X-Foo: foo3
- Parameters:
headers (table)
- Returns:
throws an error on invalid input.
- Return type:
None
- static set_status(status: number) None ¶
Allows changing the downstream response HTTP status code before sending it to the client.
- Phases:
rewrite, access, header_filter, response, admin_api
- Example:
kong.response.set_status(404)
- Parameters:
status (number) – The new status.
- Returns:
throws an error on invalid input.
- Return type:
None
- class router¶
Bases:
object
- static get_route() table ¶
Returns the current route entity. The request is matched against this route.
- Phases:
access, header_filter, response, body_filter, log
- Example:
route = kong.router.get_route()
protocols = route.protocols
- Returns:
The route entity.
- Return type:
table
- static get_service() table ¶
Returns the current service entity. The request is targeted to this upstream service.
- Phases:
access, header_filter, response, body_filter, log
- Example:
if kong.router.get_service():
# routed by route & service entities
else:
# routed by a route without a service
- Returns:
The service entity.
- Return type:
table
- class service¶
Bases:
object
- class request¶
Bases:
object
- static add_header(header: str, of: table) None ¶
Adds a request header with the given value to the request to the Service. Unlike kong.service.request.set_header(), this function doesn’t remove any existing headers with the same name. Instead, several occurrences of the header will be present in the request. The order in which headers are added is retained.
- Phases:
rewrite, access
- Example:
kong.service.request.add_header(“Cache-Control”, “no-cache”)
kong.service.request.add_header(“Cache-Control”, “no-store”)
- Parameters:
header (str) – The header name. Example: “Cache-Control”.
of (table) – strings|string|number|boolean value The header value. Example: “no-cache”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static clear_header(header: str) None ¶
Removes all occurrences of the specified header from the request to the Service.
- Phases:
rewrite, access
- Example:
kong.service.request.set_header(“X-Foo”, “foo”)
kong.service.request.add_header(“X-Foo”, “bar”)
kong.service.request.clear_header(“X-Foo”)
# from here onwards, no X-Foo headers will exist in the request
- Parameters:
header (str) – The header name. Example: “X-Foo”.
- Returns:
throws an error on invalid inputs. The function does not throw an error if no header was removed.
- Return type:
None
- static disable_tls() Tuple[bool, str] ¶
Disables the TLS handshake to upstream for [ngx_stream_proxy_module](https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html). This overrides the [proxy_ssl](https://nginx.org/en/docs/stream/ngx_stream_proxy_module.html#proxy_ssl) directive, effectively setting it to off for the current stream session. Once this function has been called, it is not possible to re-enable TLS handshake for the current session.
- Phases:
preread, balancer
- Example:
ok, err = kong.service.request.disable_tls()
if not ok:
# do something with error
- Returns:
true if the operation succeeded, nil if an error occurred.
- Return type:
bool
- Returns:
An error message describing the error if there was one.
- Return type:
str
- static enable_buffering() None ¶
Enables buffered proxying, which allows plugins to access Service body and response headers at the same time.
- Phases:
rewrite, access, balancer
- Example:
kong.service.request.enable_buffering()
- Returns:
- Return type:
None
- static set_body(args: table, mimetype: str | None) Tuple[bool, str] ¶
Sets the body of the request to the Service. Unlike kong.service.request.set_raw_body(), the args argument must be a table, and is encoded with a MIME type. The encoding MIME type can be specified in the optional mimetype argument, or if left unspecified, is chosen based on the Content-Type header of the client’s request. Behavior based on MIME type in the Content-Type header: * application/x-www-form-urlencoded: Encodes the arguments as
form-encoded. Keys are produced in lexicographical order. The order of entries within the same key (when values are given as an array) is retained. Any string values given are URL-encoded.
multipart/form-data: Encodes the arguments as multipart form data.
application/json: Encodes the arguments as JSON (same as kong.service.request.set_raw_body(json.encode(args))). Lua types are converted to matching JSON types.
If the MIME type is none of the above, this function returns nil and an error message indicating the body could not be encoded. If the mimetype argument is specified, the Content-Type header is set accordingly in the request to the Service. If further control of the body generation is needed, a raw body can be given as a string with kong.service.request.set_raw_body().
- Phases:
rewrite, access, balancer
- Example:
kong.service.set_header(“application/json”)
ok, err = kong.service.request.set_body({
name = “John Doe”,
age = 42,
numbers = {1, 2, 3}
})
# Produces the following JSON body:
# { “name”: “John Doe”, “age”: 42, “numbers”:[1, 2, 3] }
ok, err = kong.service.request.set_body({
foo = “hello world”,
bar = {“baz”, “bla”, true},
zzz = true,
blo = “”
}, “application/x-www-form-urlencoded”)
# Produces the following body:
# bar=baz&bar=bla&bar&blo=&foo=hello%20world&zzz
- Parameters:
args (table) – A table with data to be converted to the appropriate format and stored in the body.
mimetype (str) – can be one of:
- Returns:
true on success, nil otherwise.
- Return type:
bool
- Returns:
nil on success, an error message in case of error. Throws an error on invalid inputs.
- Return type:
str
- static set_header(header: str, of: table) None ¶
Sets a header in the request to the Service with the given value. Any existing header with the same name will be overridden. If the header argument is “host” (case-insensitive), then this also sets the SNI of the request to the Service.
- Phases:
rewrite, access, balancer
- Example:
kong.service.request.set_header(“X-Foo”, “value”)
- Parameters:
header (str) – The header name. Example: “X-Foo”.
of (table) – strings|string|boolean|number value The header value. Example: “hello world”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_headers(headers: table) None ¶
Sets the headers of the request to the Service. Unlike kong.service.request.set_header(), the headers argument must be a table in which each key is a string (corresponding to a header’s name), and each value is a string, or an array of strings. The resulting headers are produced in lexicographical order. The order of entries with the same name (when values are given as an array) is retained. This function overrides any existing header bearing the same name as those specified in the headers argument. Other headers remain unchanged. If the “Host” header is set (case-insensitive), then this also sets the SNI of the request to the Service.
- Phases:
rewrite, access
- Example:
kong.service.request.set_header(“X-Foo”, “foo1”)
kong.service.request.add_header(“X-Foo”, “foo2”)
kong.service.request.set_header(“X-Bar”, “bar1”)
kong.service.request.set_headers({
[“X-Foo”] = “foo3”,
[“Cache-Control”] = { “no-store”, “no-cache” },
[“Bla”] = “boo”
})
# Will add the following headers to the request, in this order:
# X-Bar: bar1
# Bla: boo
# Cache-Control: no-store
# Cache-Control: no-cache
# X-Foo: foo3
- Parameters:
headers (table) – A table where each key is a string containing a header name and each value is either a string or an array of strings.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_method(method: str) None ¶
Sets the HTTP method for the request to the service.
- Phases:
rewrite, access
- Example:
kong.service.request.set_method(“DELETE”)
- Parameters:
method (str) – The method string, which must be in all uppercase. Supported values are: “GET”, “HEAD”, “PUT”, “POST”, “DELETE”, “OPTIONS”, “MKCOL”, “COPY”, “MOVE”, “PROPFIND”, “PROPPATCH”, “LOCK”, “UNLOCK”, “PATCH”, or “TRACE”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_path(path: str) None ¶
Sets the path component for the request to the service. The input accepts any valid normalized URI (including UTF-8 characters) and this API will perform necessary escaping according to the RFC to make the request valid. Input should not include the query string.
- Phases:
access, rewrite, balancer
- Example:
kong.service.request.set_path(“/v2/movies”)
- Parameters:
path (str) – The path string. Special characters and UTF-8 characters are allowed, for example: “/v2/movies” or “/foo/😀”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_query(args: table) None ¶
Set the query string of the request to the Service. Unlike kong.service.request.set_raw_query(), the query argument must be a table in which each key is a string (corresponding to an argument’s name), and each value is either a boolean, a string, or an array of strings or booleans. Additionally, all string values will be URL-encoded. The resulting query string contains keys in their lexicographical order. The order of entries within the same key (when values are given as an array) is retained. If further control of the query string generation is needed, a raw query string can be given as a string with kong.service.request.set_raw_query().
- Phases:
rewrite, access
- Example:
kong.service.request.set_query({
foo = “hello world”,
bar = {“baz”, “bla”, true},
zzz = true,
blo = “”
})
# Produces the following query string:
# bar=baz&bar=bla&bar&blo=&foo=hello%20world&zzz
- Parameters:
args (table) – A table where each key is a string (corresponding to an argument name), and each value is either a boolean, a string, or an array of strings or booleans. Any string values given are URL-encoded.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_raw_body(body: str) None ¶
Sets the body of the request to the Service. The body argument must be a string and will not be processed in any way. This function also sets the Content-Length header appropriately. To set an empty body, you can provide an empty string (“”) to this function. For a higher-level function to set the body based on the request content type, see kong.service.request.set_body().
- Phases:
rewrite, access, balancer
- Example:
kong.service.request.set_raw_body(“Hello, world!”)
- Parameters:
body (str) – The raw body.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_raw_query(query: str) None ¶
Sets the query string of the request to the Service. The query argument is a string (without the leading ? character), and is not processed in any way. For a higher-level function to set the query string from a Lua table of arguments, see kong.service.request.set_query().
- Phases:
rewrite, access
- Example:
kong.service.request.set_raw_query(“zzz&bar=baz&bar=bla&bar&blo=&foo=hello%20world”)
- Parameters:
query (str) – The raw querystring. Example: “foo=bar&bla&baz=hello%20world”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- static set_scheme(scheme: str) None ¶
Sets the protocol to use when proxying the request to the Service.
- Phases:
access, rewrite, balancer
- Example:
kong.service.request.set_scheme(“https”)
- Parameters:
scheme (str) – The scheme to be used. Supported values are “http” or “https”.
- Returns:
throws an error on invalid inputs.
- Return type:
None
- class response¶
Bases:
object
- static get_body(mimetype: str | None, max_args: number | None) str ¶
Returns the decoded buffered body.
- Phases:
header_filter, body_filter, log
- Example:
# Plugin needs to call kong.service.request.enable_buffering() on rewrite
# or access phase prior calling this function.
body = kong.service.response.get_body()
- Parameters:
mimetype (str) – The MIME type of the response (if known).
max_args (number) – Sets a limit on the maximum number of (what?) that can be parsed.
- Returns:
The decoded buffered body
- Return type:
str
- static get_header(name: str) str ¶
Returns the value of the specified response header. Unlike kong.response.get_header(), this function only returns a header if it is present in the response from the Service (ignoring headers added by Kong itself).
- Phases:
header_filter, body_filter, log
- Example:
# Given a response with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
kong.log.inspect(kong.service.response.get_header(“x-custom-header”)) # “bla”
kong.log.inspect(kong.service.response.get_header(“X-Another”)) # “foo bar”
- Parameters:
name (str) – The name of the header. Header names in are case-insensitive and are normalized to lowercase, and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header.
- Returns:
The value of the header, or nil if a header with name is not found in the response. If a header with the same name is present multiple times in the response, this function returns the value of the first occurrence of this header.
- Return type:
str
- static get_headers(max_headers: number | None) Tuple[table, str] ¶
Returns a Lua table holding the headers from the Service response. Keys are header names. Values are either a string with the header value, or an array of strings if a header was sent multiple times. Header names in this table are case-insensitive and dashes (-) can be written as underscores (_); that is, the header X-Custom-Header can also be retrieved as x_custom_header. Unlike kong.response.get_headers(), this function only returns headers that are present in the response from the Service (ignoring headers added by Kong itself). If the request is not proxied to a Service (e.g. an authentication plugin rejected a request and produced an HTTP 401 response), then the returned headers value might be nil, since no response from the Service has been received. By default, this function returns up to 100 headers. The optional max_headers argument can be specified to customize this limit, but must be greater than 1 and not greater than 1000.
- Phases:
header_filter, body_filter, log
- Example:
# Given a response with the following headers:
# X-Custom-Header: bla
# X-Another: foo bar
# X-Another: baz
headers = kong.service.response.get_headers()
if headers:
kong.log.inspect(headers.x_custom_header) # “bla”
kong.log.inspect(headers.x_another[1]) # “foo bar”
kong.log.inspect(headers[“X-Another”][2]) # “baz”Note that this function returns a proxy table
which cannot be iterated with pairs or used as operand of #.
- Parameters:
max_headers (number) – Sets a limit on the maximum number of headers that can be parsed.
- Returns:
The response headers in table form.
- Return type:
table
- Returns:
If more headers than max_headers are present, returns a string with the error “truncated”.
- Return type:
str
- static get_raw_body() bytes ¶
Returns the raw buffered body.
- Phases:
header_filter, body_filter, log
- Example:
# Plugin needs to call kong.service.request.enable_buffering() on rewrite
# or access phase prior calling this function.
body = kong.service.response.get_raw_body()
- Returns:
The raw buffered body.
- Return type:
bytes
- static get_status() number ¶
Returns the HTTP status code of the response from the Service as a Lua number.
- Phases:
header_filter, body_filter, log
- Example:
kong.log.inspect(kong.service.response.get_status()) # 418
- Returns:
The status code from the response from the Service, or nil if the request was not proxied (that is, if kong.response.get_source() returned anything other than “service”).
- Return type:
number
- static set_retries(retries: number) None ¶
Sets the retries count for the current request. This will override the default retries count set in the Upstream entity. The retries argument expects an integer between 0 and 32767.
- Phases:
access
- Example:
kong.service.set_retries(233)
- Parameters:
retries (number)
- static set_target(host: str, port: number) None ¶
Sets the host and port on which to connect to for proxying the request. Using this method is equivalent to ask Kong to not run the load-balancing phase for this request, and consider it manually overridden. Load-balancing components such as retries and health-checks will also be ignored for this request. Use kong.service.set_retries to overwrite retries count. The host argument expects the hostname or IP address of the upstream server, and the port expects a port number.
- Phases:
access
- Example:
kong.service.set_target(“service.local”, 443)
kong.service.set_target(“192.168.130.1”, 80)
- Parameters:
host (str)
port (number)
- static set_timeouts(connect_timeout: number, write_timeout: number, read_timeout: number) None ¶
Sets the timeouts for the current request. This will override the default timeouts set in the Upstream entity.
The connect_timeout, write_timeout, and read_timeout arguments expect an integer between 1 and 2147483646.
- Phases:
access
- Example:
kong.service.set_timeouts(233, 233, 233)
- Parameters:
connect_timeout (number)
write_timeout (number)
read_timeout (number)
- static set_tls_verify(on: bool) Tuple[bool, str] ¶
Sets whether TLS verification is enabled while handshaking with the Service. The on argument is a boolean flag, where true means upstream verification is enabled and false disables it. This call affects only the current request. If the trusted certificate store is not set already (via [proxy_ssl_trusted_certificate](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_trusted_certificate) or [kong.service.set_upstream_ssl_trusted_store](#kongserviceset_upstream_ssl_trusted_store)), then TLS verification will always fail with “unable to get local issuer certificate” error.
- Phases:
rewrite, access, balancer, preread
- Example:
ok, err = kong.service.set_tls_verify(true)
if not ok:
# do something with error
- Parameters:
on (bool) – Whether to enable TLS certificate verification for the current request
- Returns:
true if the operation succeeded, nil if an error occurred
- Return type:
bool
- Returns:
An error message describing the error if there was one
- Return type:
str
- static set_tls_verify_depth(depth: number) Tuple[bool, str] ¶
Sets the maximum depth of verification when validating upstream server’s TLS certificate. This call affects only the current request. For the depth to be actually used the verification has to be enabled with either the [proxy_ssl_verify](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_verify) directive or using the [kong.service.set_tls_verify](#kongserviceset_tls_verify) function.
- Phases:
rewrite, access, balancer, preread
- Example:
ok, err = kong.service.set_tls_verify_depth(3)
if not ok:
# do something with error
- Parameters:
depth (number) – Depth to use when validating. Must be non-negative
- Returns:
true if the operation succeeded, nil if an error occurred
- Return type:
bool
- Returns:
An error message describing the error if there was one
- Return type:
str
- static set_upstream(host: str) Tuple[bool, str] ¶
Sets the desired Upstream entity to handle the load-balancing step for this request. Using this method is equivalent to creating a Service with a host property equal to that of an Upstream entity (in which case, the request would be proxied to one of the Targets associated with that Upstream). The host argument should receive a string equal to the name of one of the Upstream entities currently configured.
- Phases:
access
- Example:
ok, err = kong.service.set_upstream(“service.prod”)
if not ok:
kong.log.err(err)
return
- Parameters:
host (str)
- Returns:
true on success, or nil if no upstream entities where found
- Return type:
bool
- Returns:
An error message describing the error if there was one.
- Return type:
str
- class telemetry¶
Bases:
object
- static log(plugin_name: str, plugin_config: table, message_type: str, message: str, attributes: table) None ¶
Records a structured log entry, to be reported via the OpenTelemetry plugin. This function has a dependency on the OpenTelemetry plugin, which must be configured to report OpenTelemetry logs.
- Phases:
rewrite, access, balancer, timer, header_filter, response, body_filter, log
- Example:
attributes = {
http_method = kong.request.get_method()
[“node.id”] = kong.node.get_id(),
hostname = kong.node.get_hostname(),
}
ok, err = kong.telemetry.log(“my_plugin”, conf, “result”, “successful operation”, attributes)
- Parameters:
plugin_name (str) – the name of the plugin
plugin_config (table) – the plugin configuration
message_type (str) – the type of the log message, useful to categorize the log entry
message (str) – the log message
attributes (table) – structured information to be included in the attributes field of the log entry
- class vault¶
Bases:
object
- static flush() None ¶
Flush vault LRU cache and start a timer to rotate secrets. @local
- Example:
kong.vault.flush()
- static get(reference: str) Tuple[str, str] ¶
Resolves the passed in reference and returns the value of it.
- Example:
value, err = kong.vault.get(“{vault://env/cert/key}”)
- Parameters:
reference (str) – reference to resolve
- Returns:
resolved value of the reference
- Return type:
str
- Returns:
error message on failure, otherwise nil
- Return type:
str
- static init_worker() None ¶
Initializes vault. Registers event handlers (on non-dbless nodes) and starts a recurring secrets rotation timer. Does nothing on control planes. @local
- static is_reference(reference: str) bool ¶
Checks if the passed in reference looks like a reference. Valid references start with ‘{vault://’ and end with ‘}’. If you need more thorough validation, use kong.vault.parse_reference.
- Example:
kong.vault.is_reference(“{vault://env/key}”) # true
kong.vault.is_reference(“not a reference”) # false
- Parameters:
reference (str) – reference to check
- Returns:
true is the passed in reference looks like a reference, otherwise false
- Return type:
bool
- static parse_reference(reference: str) Tuple[table, str] ¶
Parses and decodes the passed in reference and returns a table containing its components. Given a following resource:
`lua "{vault://env/cert/key?prefix=SSL_#1}" `
This function will return following table: ```lua {name = “env”, – name of the Vault entity or Vault strategy resource = “cert”, – resource where secret is stored key = “key”, – key to lookup if the resource is secret object config = { – if there are any config options specified
prefix = “SSL_”
}, version = 1 – if the version is specified
- Example:
ref, err = kong.vault.parse_reference(“{vault://env/cert/key?prefix=SSL_#1}”) # table
- Parameters:
reference (str) – reference to parse
- Returns:
a table containing each component of the reference, or nil on error
- Return type:
table
- Returns:
error message on failure, otherwise nil
- Return type:
str
- static update(options: table) table ¶
Helper function for secret rotation based on TTLs. Currently experimental.
- Example:
options = kong.vault.update({
cert = “# # -BEGIN CERTIFICATE# # -…”,
key = “# # -BEGIN RSA PRIVATE KEY# # -…”,
cert_alt = “# # -BEGIN CERTIFICATE# # -…”,
key_alt = “# # -BEGIN EC PRIVATE KEY# # -…”,
[“$refs”] = {
cert = “{vault://aws/cert}”,
key = “{vault://aws/key}”,
cert_alt = “{vault://aws/cert-alt}”,
key_alt = “{vault://aws/key-alt}”,
}
})
# or
options = {
cert = “# # -BEGIN CERTIFICATE# # -…”,
key = “# # -BEGIN RSA PRIVATE KEY# # -…”,
cert_alt = “# # -BEGIN CERTIFICATE# # -…”,
key_alt = “# # -BEGIN EC PRIVATE KEY# # -…”,
[“$refs”] = {
cert = “{vault://aws/cert}”,
key = “{vault://aws/key}”,
cert_alt = “{vault://aws/cert-alt}”,
key_alt = “{vault://aws/key-alt}”,
}
}
kong.vault.update(options)
- Parameters:
options (table) – options containing secrets and references (this function modifies the input options)
- Returns:
options with updated secret values
- Return type:
table
- static warmup() None ¶
Warmups vault caches from config. @local