diff --git a/README.md b/README.md index caa75af..f5a15a6 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ curl.exe -N http://127.0.0.1:8080/chat/stream -H "Content-Type: application/json ## 配置与部署 -配置结构及默认限制见 `config.yaml`。插件路径相对于配置文件解析,列表顺序就是执行顺序。启用、停用、代码和配置变更均重启生效。所有插件文件(含关闭的条目)必须存在;只有启用的插件会校验 Lua 代码和初始化。加载失败时服务不就绪。 +配置结构及默认限制见 `config.yaml`。插件路径相对于配置文件解析,列表顺序就是执行顺序。插件级 `match.paths` 由宿主按请求路径精确选择参与链的插件;省略时匹配所有路径。旧的 `config.paths` 不再兼容。启用、停用、代码和配置变更均重启生效。所有插件文件(含关闭的条目)必须存在;只有启用的插件会校验 Lua 代码和初始化。加载失败时服务不就绪。 网络授权位于每个插件的 `network.allow`。公网 HTTPS 默认端口 443;内网域名需额外配置 CIDR,HTTP 和其他端口须明确配置。空列表表示插件不能发起网络请求。 diff --git a/config.yaml b/config.yaml index 35c5b86..ff60f21 100644 --- a/config.yaml +++ b/config.yaml @@ -21,6 +21,8 @@ llm: plugins: - id: network-review file: plugins/network_review.lua + match: + paths: [/chat/stream] network: allow: - domain: review.example.com # 本地联调改 mock-review.local @@ -32,28 +34,30 @@ plugins: url: https://review.example.com/check # 本地联调改 http://mock-review.local:8001/check fields: [messages] headers: {x-api-key: "injected-by-admin"} - paths: [/chat/stream] - id: response-guard file: plugins/response_guard.lua + match: + paths: [/chat/stream] llm: {allow: [guard_model]} config: model: guard_model # 必须与 llm 注册的 id 一致 content_path: content - paths: [/chat/stream] - id: request-rewrite file: plugins/request_rewrite.lua + match: + paths: [/chat/stream] config: prefix: "[checked] " - paths: [/chat/stream] - id: stream-redact file: plugins/stream_redact.lua + match: + paths: [/chat/stream] config: text_event: text_delta content_path: content terminal_error_events: [run_error] control_event_names: [heartbeat, run_started, run_finished, run_error, run_completed] max_buffer_bytes: 262144 - paths: [/chat/stream] diff --git a/docs/plugins.md b/docs/plugins.md index b959bb8..6d29e0a 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -16,6 +16,22 @@ return plugin `ctx` 包含中间层生成的 `request_id` 和当前 `plugin_id`。它不是用户身份或授权证据。每次钩子获得数据副本,需通过返回值传递修改。插件用模块局部变量保存本请求状态;不同插件、不同请求均不共享全局变量。 +## 路径匹配 + +插件是否参与一次请求由宿主根据插件级 `match.paths` 决定,Lua 插件不再读取或维护路径白名单和 `bypass` 状态。一次请求创建会话时完成匹配,后续的 `on_request`、`on_response`、`on_event`、`on_end` 和 `close` 始终使用同一组插件。 + +```yaml +plugins: + - id: request-rewrite + file: plugins/request_rewrite.lua + match: + paths: [/chat/stream] + config: + prefix: "[checked] " +``` + +`match.paths` 是精确路径列表,区分大小写和尾斜杠,不支持前缀、通配符、查询参数或正则。省略 `match` 表示匹配所有路径。旧的 `config.paths` 已移除,启动时会报错并要求迁移到 `match.paths`。 + ## 钩子数据 | 钩子 | 第二参数 | 可以返回的动作 | diff --git a/middleware/config.py b/middleware/config.py index 2a88eff..f819286 100644 --- a/middleware/config.py +++ b/middleware/config.py @@ -109,14 +109,42 @@ class PluginLLMAccess(Model): allow: list[str] = Field(default_factory=list) +class PluginMatch(Model): + paths: list[str] = Field(min_length=1) + + @field_validator("paths") + @classmethod + def paths_valid(cls, value: list[str]) -> list[str]: + if len(value) != len(set(value)): + raise ValueError("plugin match.paths contains a duplicate path") + for path in value: + if not path.startswith("/"): + raise ValueError("plugin match.paths entries must be absolute paths") + if any(ord(char) < 0x20 or ord(char) == 0x7F for char in path): + raise ValueError("plugin match.paths entries must not contain control characters") + if any(char in path for char in "*?#"): + raise ValueError("plugin match.paths entries must be exact paths without wildcards") + return value + + def matches(self, path: str) -> bool: + return path in self.paths + + class PluginConfig(Model): id: str = Field(pattern=r"^[a-zA-Z0-9_-]{1,64}$") file: Path enabled: bool = True + match: PluginMatch | None = None config: dict = Field(default_factory=dict) network: NetworkPolicy = Field(default_factory=NetworkPolicy) llm: PluginLLMAccess = Field(default_factory=PluginLLMAccess) + @model_validator(mode="after") + def reject_legacy_path_match(self): + if "paths" in self.config: + raise ValueError(f"plugin {self.id}: config.paths is unsupported; use match.paths") + return self + class Limits(Model): max_sessions: int = Field(default=4, gt=0) diff --git a/middleware/proxy.py b/middleware/proxy.py index 7811e15..55a1a0c 100644 --- a/middleware/proxy.py +++ b/middleware/proxy.py @@ -240,10 +240,11 @@ def create_app(settings: Settings | str = "config.yaml") -> FastAPI: handed_off = False try: manager = app.state.manager - session = await manager.open(request_id) + request_path = request.scope["path"] + session = await manager.open(request_id, path=request_path) original = { "method": "POST", - "path": "/chat/stream", + "path": request_path, "headers": safe_headers(dict(request.headers)), "body": text, } diff --git a/middleware/runtime.py b/middleware/runtime.py index abf9fef..fe7d6ad 100644 --- a/middleware/runtime.py +++ b/middleware/runtime.py @@ -18,8 +18,9 @@ ADAPTER_ID = "__protocol_adapter__" class Session: - def __init__(self, manager, request_id=None): + def __init__(self, manager, request_id=None, plugins=None): self.manager = manager + self.plugins = list(manager.plugins if plugins is None else plugins) self.context = {"request_id": request_id or str(uuid4())} self.started = time.monotonic() self.closed = False @@ -140,9 +141,10 @@ class Session: ) async def initialize(self, adapter_only=False): - for plugin_id, source in self.manager.sources.items(): - if adapter_only and plugin_id != ADAPTER_ID: - continue + plugin_ids = [] if adapter_only else [plugin.id for plugin in self.plugins] + plugin_ids.append(ADAPTER_ID) + for plugin_id in plugin_ids: + source = self.manager.sources[plugin_id] await self.rpc( { "op": "load", @@ -170,7 +172,7 @@ class Session: async def apply(self, hook, value, start=0): values = [value] - for plugin in self.manager.plugins[start:]: + for plugin in self.plugins[start:]: output = [] for item in values: result = await self.invoke(plugin.id, hook, item) @@ -226,7 +228,7 @@ class Session: async def end(self): output = [] - for index, plugin in enumerate(self.manager.plugins): + for index, plugin in enumerate(self.plugins): result = await self.invoke(plugin.id, "on_end") for event in self.decision(result, None, "on_end"): output.extend(await self.apply("on_event", event, start=index + 1)) @@ -293,11 +295,12 @@ class PluginManager: await self.llm.start() self.llm_started = True - async def open(self, request_id=None, adapter_only=False): + async def open(self, request_id=None, path=None, adapter_only=False, all_plugins=False): if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions: raise Overloaded() await self.start() - session = Session(self, request_id) + plugins = self.plugins if all_plugins or path is None else self.plugins_for_path(path) + session = Session(self, request_id, plugins) self.sessions.add(session) try: await session.initialize(adapter_only) @@ -307,9 +310,14 @@ class PluginManager: raise async def validate(self): - session = await self.open() + session = await self.open(all_plugins=True) await session.aclose() + def plugins_for_path(self, path): + return [ + plugin for plugin in self.plugins if plugin.match is None or plugin.match.matches(path) + ] + async def error_event(self, request_id, last_event, error_type): # Failed/timed-out business runtimes never render their own errors. session = await self.open(request_id, adapter_only=True) diff --git a/plugins/network_review.lua b/plugins/network_review.lua index 463ca91..bc66945 100644 --- a/plugins/network_review.lua +++ b/plugins/network_review.lua @@ -96,46 +96,15 @@ function plugin.init(ctx, options) end end - -- 新增:路径白名单(可选)。未配置时保持原行为——审核所有请求; - -- 配置后只有命中白名单的路径才走外发审核,其余请求直接放行。 - local paths = {} - if options.paths ~= nil then - if type(options.paths) ~= "table" then - error("network_review config.paths must be an array") - end - local seen_paths = {} - for _, p in ipairs(options.paths) do - if not is_non_empty_string(p) or p:sub(1, 1) ~= "/" then - error("network_review config.paths entries must be non-empty path strings") - end - if seen_paths[p] then - error("network_review config.paths contains a duplicate path") - end - seen_paths[p] = true - paths[p] = true - end - end - settings = { url = options.url, fields = fields, headers = headers, - paths = paths, } return nil end function plugin.on_request(ctx, request) - -- 新增:路径白名单判断。必须放在 body 检查之前,否则 GET /health 这类 - -- 无 body 的非 AI 请求会被 "invalid request body" 拦截。 - -- 未配置 paths 时此分支不生效,行为与原版完全一致(fail-closed 审核一切)。 - if next(settings.paths) ~= nil then - local path = type(request) == "table" and request.path or nil - if path == nil or not settings.paths[path] then - return { action = "pass" } - end - end - if type(request) ~= "table" or type(request.body) ~= "string" then return { action = "block", reason = "invalid request body" } end diff --git a/plugins/request_rewrite.lua b/plugins/request_rewrite.lua index 92613fe..94213fc 100644 --- a/plugins/request_rewrite.lua +++ b/plugins/request_rewrite.lua @@ -108,45 +108,14 @@ function plugin.init(ctx, options) end end - -- 新增:路径白名单(可选)。未配置时保持原行为——对所有含 message - -- 字段的请求打标;配置后只有命中白名单的 AI 路径才改写, - -- 非 AI 路径(即使恰好有 message 字段)原样放行,不被加前缀。 - local paths = {} - if options.paths ~= nil then - if type(options.paths) ~= "table" then - error("request_rewrite config.paths must be an array") - end - local count = 0 - for _, p in ipairs(options.paths) do - if type(p) ~= "string" or p == "" or p:sub(1, 1) ~= "/" then - error("request_rewrite config.paths entries must be non-empty path strings") - end - paths[p] = true - count = count + 1 - end - if count == 0 then - error("request_rewrite config.paths must be non-empty when present") - end - end - -- Atomically replace local settings; don't retain the caller's config table. - settings = { prefix = prefix, paths = paths } + settings = { prefix = prefix } -- plugins.md requires init to return nil. return nil end function plugin.on_request(ctx, request) - -- 新增:路径白名单判断。放在 body 检查之前,保证无 body 的 - -- 非 AI 请求(GET /health 等)也能通过,且不会被误加前缀。 - -- 未配置 paths 时此分支不生效,行为与原版完全一致。 - if next(settings.paths) ~= nil then - local path = type(request) == "table" and request.path or nil - if path == nil or not settings.paths[path] then - return { action = "pass" } - end - end - if type(request) ~= "table" or type(request.body) ~= "string" then return { action = "block", reason = "invalid request object" } end diff --git a/plugins/response_guard.lua b/plugins/response_guard.lua index afd62d8..92ae249 100644 --- a/plugins/response_guard.lua +++ b/plugins/response_guard.lua @@ -457,29 +457,12 @@ function plugin.init(ctx, options) end end - -- 新增:路径白名单(可选)。语义与 network_review.paths 一致: - -- 未配置时审核所有请求;配置后只有命中路径的请求才进入审核流程, - -- 其余请求登记 bypass 标记后放行(供响应阶段钩子识别)。 - local paths = {} - if candidate.paths ~= nil then - if type(candidate.paths) ~= "table" then - error("response_guard config.paths must be an array") - end - for _, p in ipairs(candidate.paths) do - if type(p) ~= "string" or p == "" or p:sub(1, 1) ~= "/" then - error("response_guard config.paths entries must be non-empty path strings") - end - paths[p] = true - end - end - local normalized = {} for k, v in pairs(candidate) do normalized[k] = v end normalized.content_path = path normalized.non_text_events = events - normalized.paths = paths config = normalized -- Do not reset requests here: hosts may invoke init during request @@ -494,18 +477,6 @@ function plugin.on_request(ctx, request) return { action = "block", reason = "missing request_id" } end - -- 新增:路径白名单判断。未命中白名单的请求(非 AI 流量)不做审核, - -- 但必须登记 bypass 标记后才能放行——响应阶段的 on_event/on_response - -- 依靠 requests[key] 区分"不需要审核"(bypass)和"状态丢失"(block)。 - if next(config.paths) ~= nil then - local path = type(request) == "table" and request.path or nil - if path == nil or not config.paths[path] then - clear(key) - requests[key] = { bypass = true } - return { action = "pass" } - end - end - local body = type(request) == "table" and request.body or "" local ok, decoded = pcall(host.json.decode, body or "") if not ok or type(decoded) ~= "table" then @@ -616,13 +587,6 @@ function plugin.on_response(ctx, response) local state = requests[key] - -- 新增:请求阶段已判定为非 AI 路径(bypass),本插件不参与其响应处理。 - -- 非流式响应一次性结束,顺手清掉标记,避免残留状态。 - if state and state.bypass then - clear(key) - return nil - end - if not state then return { action = "block", reason = "request state missing for non-streaming response" } end @@ -691,13 +655,6 @@ function plugin.on_event(ctx, event) local key = key_for(ctx) local state = key and requests[key] or nil - -- 新增:请求阶段已判定为非 AI 路径(bypass),事件流不归本插件管。 - -- 注意 bypass 判断必须放在 "request state missing" 之前,否则 - -- 非 AI 流量的事件会被当作状态丢失而 fail-closed 拦截。 - if state and state.bypass then - return nil - end - local event_name = type(event.event) == "string" and event.event or nil if not state then -- Preserve pre-request control frames only when they contain no text at @@ -753,14 +710,6 @@ function plugin.on_end(ctx) local key = key_for(ctx) local state = key and requests[key] or nil - -- bypass 请求全程未缓冲,清理标记后直接放行。 - -- 不能落入 moderate_and_release:bypass 状态没有 pending 字段, - -- 对 #state.pending 取长度会抛 runtime error。 - if state and state.bypass then - clear(key) - return nil - end - return moderate_and_release(key, true) end diff --git a/plugins/stream_redact.lua b/plugins/stream_redact.lua index 1977741..5479b69 100644 --- a/plugins/stream_redact.lua +++ b/plugins/stream_redact.lua @@ -162,28 +162,6 @@ local function normalize_settings(options) error("stream_redact: config.content_path must be a dot path or non-empty string array (use * for a dense content array)") end - -- 新增:路径白名单(可选)。语义与 network_review/response_guard 的 - -- paths 一致:未配置时对所有 SSE 流生效;配置后只对命中路径的 - -- 请求缓冲/脱敏,其余请求由 on_request 登记 bypass 后全程放行。 - local paths = {} - if options.paths ~= nil then - if type(options.paths) ~= "table" then - error("stream_redact: config.paths must be an array") - end - local count = 0 - for _, p in ipairs(options.paths) do - if type(p) ~= "string" or p == "" or string.sub(p, 1, 1) ~= "/" - or contains_cr_lf_nul(p) then - error("stream_redact: config.paths entries must be non-empty path strings without CR/LF/NUL") - end - paths[p] = true - count = count + 1 - end - if count == 0 then - error("stream_redact: config.paths must be non-empty when present") - end - end - return { max_buffer_bytes = max_buffer_bytes, text_event = text_event, @@ -191,7 +169,6 @@ local function normalize_settings(options) redact_event_names = redact_event_names, terminal_error_events = terminal_error_events, control_event_names = control_event_names, - paths = paths, } end @@ -214,7 +191,6 @@ local function copy_settings(source) redact_event_names = copy_set(source.redact_event_names), terminal_error_events = copy_set(source.terminal_error_events), control_event_names = copy_set(source.control_event_names), - paths = copy_set(source.paths), } end @@ -599,27 +575,6 @@ function plugin.init(ctx, options) return nil end -function plugin.on_request(ctx, request) - -- 新增钩子:本插件原本看不到请求路径,靠这个回调在请求阶段判断。 - -- 未命中白名单(非 AI 路径)的请求登记 bypass 标记,其 SSE 事件流 - -- 与非流式响应在 on_event/on_response/on_end 中直接放行, - -- 不缓冲、不拦截。配置了 paths 时必须保证宿主会调用本钩子。 - if next(settings.paths) == nil then - return nil - end - local key = request_key(ctx) - if not key then - return nil -- 与其他请求侧插件不同:这里没有审核职责,不 fail-closed - end - local path = type(request) == "table" and request.path or nil - if path == nil or not settings.paths[path] then - clear_state(key) - states[key] = { bypass = true } - end - return nil -end - - function plugin.on_response(ctx, response) -- This example's guarantee is SSE-only. Refuse ordinary responses rather -- than silently passing unredacted content through the same enabled rule. @@ -627,17 +582,6 @@ function plugin.on_response(ctx, response) return { action = "block", reason = "invalid response object" } end - -- 新增:请求阶段已判定为非 AI 路径(bypass),本插件不参与其响应处理。 - -- 非流式响应一次性结束,顺手清掉标记;流式响应交给 on_event/on_end 收尾。 - local key = request_key(ctx) - local state = key and states[key] or nil - if state and state.bypass then - if response.streaming ~= true then - clear_state(key) - end - return nil - end - if response.streaming == true then return nil end @@ -650,13 +594,7 @@ function plugin.on_event(ctx, event) return { action = "block", reason = "missing request id" } end - -- 新增:请求阶段已判定为非 AI 路径(bypass),事件流不归本插件管。 - -- 必须放在事件合法性检查和状态创建之前,否则非 AI 流量会被 - -- 无条件缓冲到流结束,甚至因事件形态不符被 fail-closed 拦截。 local existing = states[key] - if existing and existing.bypass then - return nil - end local size = estimate_event_bytes(event) if not size then @@ -721,12 +659,6 @@ function plugin.on_end(ctx) return nil end - -- 新增:bypass 请求全程未缓冲,结束钩子只需清理标记。 - if state.bypass then - clear_state(key) - return nil - end - if state.aborted then clear_state(key) return nil @@ -743,4 +675,4 @@ function plugin.close(ctx) clear_state(request_key(ctx)) end -return plugin \ No newline at end of file +return plugin diff --git a/tests/test_config.py b/tests/test_config.py index 2fef4ac..6343b54 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -3,7 +3,7 @@ from pathlib import Path import pytest from pydantic import ValidationError -from middleware.config import NetworkRule, Settings, load_settings +from middleware.config import NetworkRule, PluginConfig, PluginMatch, Settings, load_settings def test_configuration_and_paths(tmp_path, monkeypatch): @@ -73,6 +73,25 @@ def test_duplicate_ids_and_missing_file(tmp_path): ) +def test_plugin_match_paths_are_exact_and_legacy_paths_are_rejected(tmp_path): + plugin = tmp_path / "plugin.lua" + plugin.write_text("return {}", encoding="utf-8") + + match = PluginMatch(paths=["/chat/stream"]) + assert match.matches("/chat/stream") + assert not match.matches("/chat/stream/") + assert not match.matches("/chat/stream?token=x") + + with pytest.raises(ValidationError): + PluginMatch(paths=[]) + for invalid in ["chat/stream", "/chat/*", "/chat/stream?x=1", "/chat/stream#part"]: + with pytest.raises(ValidationError): + PluginMatch(paths=[invalid]) + + with pytest.raises(ValidationError, match="config.paths.*match.paths"): + PluginConfig(id="legacy", file=plugin, config={"paths": ["/chat/stream"]}) + + @pytest.mark.parametrize("domain", ["*", "bad/example.com", "foo..com", "127.0.0.1", "*.com*"]) def test_bad_domains(domain): with pytest.raises(ValueError): diff --git a/tests/test_runtime.py b/tests/test_runtime.py index 28c13f2..3437f95 100644 --- a/tests/test_runtime.py +++ b/tests/test_runtime.py @@ -57,6 +57,37 @@ async def test_chain_isolation_json_and_disabled(tmp_path): assert not manager.sessions +async def test_host_selects_plugins_once_by_exact_path(tmp_path): + first = tmp_path / "first.lua" + second = tmp_path / "second.lua" + first.write_text( + "return {on_request=function(ctx,r) r.body=r.body..' first'; return {action='replace',value=r} end}", + encoding="utf-8", + ) + second.write_text( + "return {on_request=function(ctx,r) r.body=r.body..' second'; return {action='replace',value=r} end}", + encoding="utf-8", + ) + settings = Settings( + upstream="http://agent:8000", + plugins=[ + PluginConfig(id="first", file=first, match={"paths": ["/first"]}), + PluginConfig(id="second", file=second, match={"paths": ["/second"]}), + ], + ) + manager = PluginManager(settings) + first_session = await manager.open(path="/first") + try: + assert await first_session.apply("on_request", {"body": "x"}) == [{"body": "x first"}] + finally: + await first_session.aclose() + second_session = await manager.open(path="/second?ignored=true") + try: + assert await second_session.apply("on_request", {"body": "x"}) == [{"body": "x"}] + finally: + await second_session.aclose() + + async def test_hold_flush_runs_downstream(tmp_path): manager = manager_for( tmp_path,