You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@apisix.apache.org by "Copilot (via GitHub)" <gi...@apache.org> on 2026/03/30 15:17:30 UTC
Re: [PR] feat:Add Stream Route Gating Plugin [apisix]
Copilot commented on code in PR #13130:
URL: https://github.com/apache/apisix/pull/13130#discussion_r3010492004
##########
apisix/stream/plugins/sr-enable-disable.lua:
##########
@@ -0,0 +1,97 @@
+-- Stream route gating plugin for APISIX.
+--
+-- Attach to any stream route to control whether it accepts connections.
+-- When the "active" flag is truthy, traffic flows normally; otherwise
+-- connections are refused with an optional rejection message.
+--
+-- -----------------------------------------------------------------------------------------------------
+-- Note: This plugin operates at the stream level, so it does not have
+-- access to HTTP-specific features like status codes or headers. Instead,
+-- it simply accepts or rejects TCP/TLS connections based on the "enabled" flag.
+-- ----------------------------------------------------------------------------------------------------
+--
+-- Usage example:
+-- 1. Enable the plugin on a stream route:
+-- curl -X PUT http://<APISIX_HOST>:<APISIX_PORT>/apisix/admin/stream_routes/<STREAM_ROUTE_ID> \
+-- -H "X-API-KEY: ${admin_key}" \
+-- -H "Content-Type: application/json" \
+-- -d '{
+-- "plugins": {
+-- "sr-enable-disable": {
+-- "enabled": true,
+-- "decline_msg": "Stream route is currently disabled."
+-- }
+-- },
+-- "upstream": {
+-- "type": "roundrobin",
+-- "nodes": {
+-- "<NODE_ADDRESS>:<PORT>": 1
+-- }
+-- }
+-- }'
+-- 2. Toggle the "enabled" flag to control access:
+-- - To disable: set "enabled" to false.
+-- - To enable: set "enabled" to true.
+-----------------------------------------------------------------------------------------------------
+
+local pcall = pcall
+local ngx_socket = ngx.req.socket
+local log = require("apisix.core").log
+local checker = require("apisix.core").schema
+
+local NAME = "sr-enable-disable"
+local DEFAULT_REJECTION = "Stream route in disabled state."
+
+local conf_schema = {
+ type = "object",
+ properties = {
+ enabled = {
+ type = "boolean",
+ default = false,
+ },
+ decline_msg = {
+ type = "string",
+ default = DEFAULT_REJECTION,
+ },
+ },
+ required = {"enabled"},
+ additionalProperties = false,
+}
+
+local _M = {
+ version = 1.0,
+ priority = 10000,
+ name = NAME,
+ schema = conf_schema,
+}
+
+
+function _M.check_schema(conf)
+ return checker.check(conf_schema, conf)
+end
+
+
+local function reject_connection(reason)
+ local ok, raw = pcall(ngx_socket, true)
+ if ok and raw then
+ pcall(raw.send, raw, reason .. "\n")
+ pcall(raw.close, raw)
+ end
Review Comment:
`reject_connection` calls `ngx.req.socket` with an extra `true` argument and then uses `raw.send/raw.close`. In this codebase stream plugins use `ngx.req.socket()` with no arguments (see `apisix/stream/plugins/mqtt-proxy.lua:131`), so this call can fail and the decline message may never be sent. Use `local sock, err = ngx.req.socket()` and invoke `sock:send(...)` / `sock:close()` after checking `sock`.
```suggestion
local sock, err = ngx_socket()
if not sock then
return
end
pcall(function()
sock:send(reason .. "\n")
sock:close()
end)
```
##########
apisix/stream/plugins/sr-enable-disable.lua:
##########
@@ -0,0 +1,97 @@
+-- Stream route gating plugin for APISIX.
+--
+-- Attach to any stream route to control whether it accepts connections.
+-- When the "active" flag is truthy, traffic flows normally; otherwise
+-- connections are refused with an optional rejection message.
+--
+-- -----------------------------------------------------------------------------------------------------
+-- Note: This plugin operates at the stream level, so it does not have
+-- access to HTTP-specific features like status codes or headers. Instead,
+-- it simply accepts or rejects TCP/TLS connections based on the "enabled" flag.
+-- ----------------------------------------------------------------------------------------------------
+--
+-- Usage example:
+-- 1. Enable the plugin on a stream route:
+-- curl -X PUT http://<APISIX_HOST>:<APISIX_PORT>/apisix/admin/stream_routes/<STREAM_ROUTE_ID> \
+-- -H "X-API-KEY: ${admin_key}" \
+-- -H "Content-Type: application/json" \
+-- -d '{
+-- "plugins": {
+-- "sr-enable-disable": {
+-- "enabled": true,
+-- "decline_msg": "Stream route is currently disabled."
+-- }
+-- },
+-- "upstream": {
+-- "type": "roundrobin",
+-- "nodes": {
+-- "<NODE_ADDRESS>:<PORT>": 1
+-- }
+-- }
+-- }'
+-- 2. Toggle the "enabled" flag to control access:
+-- - To disable: set "enabled" to false.
+-- - To enable: set "enabled" to true.
+-----------------------------------------------------------------------------------------------------
+
+local pcall = pcall
+local ngx_socket = ngx.req.socket
+local log = require("apisix.core").log
+local checker = require("apisix.core").schema
Review Comment:
`ngx.req.socket` is referenced at module load time. APISIX loads plugins during init/init_worker phases where `ngx.req` may be unavailable, which can cause startup-time failures when requiring this module. Move the `ngx.req.socket()` lookup inside `reject_connection` (or inside `preread`) so it only runs in a stream request context.
##########
docs/en/latest/plugins/sr-enable-disable.md:
##########
@@ -0,0 +1,123 @@
+---
+title: sr-enable-disable
+keywords:
+ - Apache APISIX
+ - API Gateway
+ - Plugin
+ - Stream Route
+ - sr-enable-disable
+description: The sr-enable-disable Plugin acts as a runtime enable/disable switch for stream routes, allowing you to control whether a stream route accepts or rejects incoming TCP/TLS connections.
+---
+
Review Comment:
This new plugin doc is missing the standard ASF license header block that other plugin docs include (e.g. `docs/en/latest/plugins/key-auth.md:12-29`). Please add the license header (and any required `<head>` canonical section if applicable) to keep documentation files consistent with repository requirements.
```suggestion
---
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
```
##########
t/stream-plugin/sr-enable-disable.t:
##########
@@ -0,0 +1,306 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+use t::APISIX 'no_plan';
+
+repeat_each(1);
+no_long_string();
+no_shuffle();
+no_root_location();
+
+
+add_block_preprocessor(sub {
+ my ($block) = @_;
+
+ if (!$block->error_log && !$block->no_error_log) {
+ $block->set_value("no_error_log", "[error]\n[alert]");
+ }
+});
+
+run_tests;
+
+__DATA__
+
+=== TEST 1: sanity - check_schema accepts valid config
+--- config
+ location /t {
+ content_by_lua_block {
+ local plugin = require("apisix.stream.plugins.sr-enable-disable")
+ local ok, err = plugin.check_schema({enabled = true})
+ if not ok then
+ ngx.say(err)
+ return
+ end
+ ngx.say("done")
+ }
+ }
+--- request
+GET /t
+--- response_body
+done
+
+
+
+=== TEST 2: check_schema rejects missing required field
+--- config
+ location /t {
+ content_by_lua_block {
+ local plugin = require("apisix.stream.plugins.sr-enable-disable")
+ local ok, err = plugin.check_schema({})
+ if not ok then
+ ngx.say(err)
+ return
+ end
+ ngx.say("done")
+ }
+ }
+--- request
+GET /t
+--- response_body eval
+qr/property "enabled" is required/
+
+
+
+=== TEST 3: check_schema rejects additional properties
+--- config
+ location /t {
+ content_by_lua_block {
+ local plugin = require("apisix.stream.plugins.sr-enable-disable")
+ local ok, err = plugin.check_schema({enabled = true, unknown = "bad"})
+ if not ok then
+ ngx.say(err)
+ return
+ end
+ ngx.say("done")
+ }
+ }
+--- request
+GET /t
+--- response_body eval
+qr/additional properties forbidden/
+
+
+
+=== TEST 4: set upstream
+--- config
+ location /t {
+ content_by_lua_block {
+ local t = require("lib.test_admin").test
+ local code, body = t('/apisix/admin/upstreams/1',
+ ngx.HTTP_PUT,
+ [[{
+ "nodes": {
+ "127.0.0.1:1995": 1
+ },
+ "type": "roundrobin"
+ }]]
+ )
+
+ if code >= 300 then
+ ngx.status = code
+ ngx.say(body)
+ return
+ end
+ ngx.say(body)
+ }
+ }
+--- request
+GET /t
+--- response_body
+passed
+
+
+
+=== TEST 5: set stream route with enabled = true
+--- config
+ location /t {
+ content_by_lua_block {
+ local t = require("lib.test_admin").test
+ local code, body = t('/apisix/admin/stream_routes/1',
+ ngx.HTTP_PUT,
+ [[{
+ "plugins": {
+ "sr-enable-disable": {
+ "enabled": true
+ }
+ },
+ "upstream_id": "1"
+ }]]
+ )
+
+ if code >= 300 then
+ ngx.status = code
+ end
+ ngx.say(body)
+ }
+ }
+--- request
+GET /t
+--- response_body
+passed
+
+
+
+=== TEST 6: connection allowed when enabled
+--- stream_request eval
+mmm
+--- stream_response
+hello world
+
+
+
+=== TEST 7: set stream route with enabled = false
+--- config
+ location /t {
+ content_by_lua_block {
+ local t = require("lib.test_admin").test
+ local code, body = t('/apisix/admin/stream_routes/1',
+ ngx.HTTP_PUT,
+ [[{
+ "plugins": {
+ "sr-enable-disable": {
+ "enabled": false
+ }
+ },
+ "upstream_id": "1"
+ }]]
+ )
+
+ if code >= 300 then
+ ngx.status = code
+ end
+ ngx.say(body)
+ }
+ }
+--- request
+GET /t
+--- response_body
+passed
+
+
+
+=== TEST 8: connection rejected when disabled
+--- stream_request eval
+mmm
Review Comment:
The rejection-path tests only assert on error log entries and never verify that the client actually receives the configured `decline_msg` before the connection closes. Since delivering this message is core plugin behavior, add a stream assertion (e.g., expect the response payload / verify connection shutdown semantics) so regressions in `reject_connection` are caught.
```suggestion
mmm
--- stream_response
```
##########
apisix/stream/plugins/sr-enable-disable.lua:
##########
@@ -0,0 +1,97 @@
+-- Stream route gating plugin for APISIX.
+--
+-- Attach to any stream route to control whether it accepts connections.
+-- When the "active" flag is truthy, traffic flows normally; otherwise
+-- connections are refused with an optional rejection message.
+--
+-- -----------------------------------------------------------------------------------------------------
+-- Note: This plugin operates at the stream level, so it does not have
+-- access to HTTP-specific features like status codes or headers. Instead,
+-- it simply accepts or rejects TCP/TLS connections based on the "enabled" flag.
+-- ----------------------------------------------------------------------------------------------------
+--
+-- Usage example:
+-- 1. Enable the plugin on a stream route:
+-- curl -X PUT http://<APISIX_HOST>:<APISIX_PORT>/apisix/admin/stream_routes/<STREAM_ROUTE_ID> \
+-- -H "X-API-KEY: ${admin_key}" \
+-- -H "Content-Type: application/json" \
+-- -d '{
+-- "plugins": {
+-- "sr-enable-disable": {
+-- "enabled": true,
+-- "decline_msg": "Stream route is currently disabled."
+-- }
+-- },
+-- "upstream": {
+-- "type": "roundrobin",
+-- "nodes": {
+-- "<NODE_ADDRESS>:<PORT>": 1
+-- }
+-- }
+-- }'
+-- 2. Toggle the "enabled" flag to control access:
+-- - To disable: set "enabled" to false.
+-- - To enable: set "enabled" to true.
+-----------------------------------------------------------------------------------------------------
+
+local pcall = pcall
+local ngx_socket = ngx.req.socket
+local log = require("apisix.core").log
+local checker = require("apisix.core").schema
+
+local NAME = "sr-enable-disable"
+local DEFAULT_REJECTION = "Stream route in disabled state."
+
+local conf_schema = {
+ type = "object",
+ properties = {
+ enabled = {
+ type = "boolean",
+ default = false,
+ },
+ decline_msg = {
+ type = "string",
+ default = DEFAULT_REJECTION,
+ },
+ },
+ required = {"enabled"},
+ additionalProperties = false,
+}
+
+local _M = {
+ version = 1.0,
+ priority = 10000,
+ name = NAME,
+ schema = conf_schema,
+}
+
+
+function _M.check_schema(conf)
+ return checker.check(conf_schema, conf)
+end
+
+
+local function reject_connection(reason)
+ local ok, raw = pcall(ngx_socket, true)
+ if ok and raw then
+ pcall(raw.send, raw, reason .. "\n")
+ pcall(raw.close, raw)
+ end
+end
+
+
+function _M.preread(conf, ctx)
+ if conf.enabled then
+ return -- route is active, let it through
+ end
+
+ local reason = conf.decline_msg or DEFAULT_REJECTION
+ log.warn(NAME, ": refusing stream connection – ", reason)
+
+ reject_connection(reason)
+
+ return 503, reason
Review Comment:
In stream mode, the plugin runner ignores the returned body and always terminates the connection via `ngx_exit(1)` when any `code`/`body` is returned (see `apisix/plugin.lua:1235-1241`). Returning `503, reason` here is therefore misleading and doesn’t help deliver the message; consider returning just a status code (or `nil`) and relying on the socket write for client messaging to make the intent clear.
```suggestion
return 503
```
##########
docs/en/latest/plugins/sr-enable-disable.md:
##########
@@ -0,0 +1,123 @@
+---
+title: sr-enable-disable
+keywords:
+ - Apache APISIX
+ - API Gateway
+ - Plugin
+ - Stream Route
+ - sr-enable-disable
+description: The sr-enable-disable Plugin acts as a runtime enable/disable switch for stream routes, allowing you to control whether a stream route accepts or rejects incoming TCP/TLS connections.
+---
+
+## Description
+
+The `sr-enable-disable` Plugin acts as a runtime enable/disable switch for any stream route it is attached to. When `enabled` is set to `true`, connections are allowed through to the upstream as usual. When set to `false`, all inbound connections are rejected and the client receives a configurable message before the socket is closed.
+
+This is useful for maintenance windows, gradual rollouts, or operational scenarios where you need to temporarily take a stream route offline without removing it from the configuration.
+
+>[!NOTE]
+>This Plugin operates at the stream (L4) level and does not have access to HTTP-specific features such as status codes or headers. It works with raw TCP/TLS connections.
+
+## Attributes
+
+| Name | Type | Required | Default | Description |
+|-------------|---------|----------|------------------------------------|-----------------------------------------------------------------------------|
+| enabled | boolean | True | false | When `true`, connections are allowed. When `false`, all connections are rejected. |
+| decline_msg | string | False | "Stream route in disabled state." | Message sent to the client before the connection is closed. |
+
+## Examples
+
+The examples below demonstrate how you can configure the `sr-enable-disable` Plugin for different scenarios.
+
+You can fetch the `admin_key` from `config.yaml` and save to an environment variable with the following command:
+
+ ```bash
+ admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
+ ```
Review Comment:
The fenced code block for the `admin_key` command is indented by 4 spaces. CommonMark only allows up to 3 leading spaces for fenced code blocks, so this may render as a literal block containing backticks instead of a code block. Remove the extra indentation so the snippet renders correctly.
```suggestion
```bash
admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
```
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@apisix.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org