fix(场景): 准确报告策略阻断并对齐文本路径

在解码 SSE 前检查 HTTP 状态和响应类型,避免将 JSON 错误响应误报为 PluginFailure。增加 verbose 插件执行日志及 403、502 回归测试,修正响应插件的 data.content 路径,并保留本地关闭网络审核插件的配置。
This commit is contained in:
starrrLight committed 2026-10-16 14:25:02 +08:00
1 parent 48f7dfc59f
commit 17c56cac3c
4 files changed
+61 -7

No files matched your search

+3 -2
View File
@@ -27,6 +27,7 @@ llm:
plugins:
- id: network-review
enabled: false
file: plugins/network_review.lua
match:
paths: [/chat/stream]
@@ -49,7 +50,7 @@ plugins:
llm: {allow: [guard_model]}
config:
model: guard_model # 必须与 llm 注册的 id 一致
content_path: content
content_path: data.content
- id: request-rewrite
file: plugins/request_rewrite.lua
@@ -64,7 +65,7 @@ plugins:
paths: [/chat/stream]
config:
text_event: text_delta
content_path: content
content_path: data.content
terminal_error_events: [run_error]
control_event_names: [heartbeat, run_started, run_finished, run_error, run_completed]
max_buffer_bytes: 262144
+2
View File
@@ -146,6 +146,8 @@ Docker 镜像安装 LibreOffice Writer;本地运行需将 `soffice` 或 `libre
场景文件必须包含非空的 `scenarios` 数组,每项包含唯一 `id`、`kind`(`sse`、`post` 或 `file`)、`path` 和 `response`。`path` 使用真实请求路径,可附带查询字符串;路径匹配仍由宿主使用解码后的路径完成,查询字符串只用于转发和上游断言。
排查失败时可在命令末尾追加 `--verbose`,查看 `plugin_hook` 日志中的插件名、hook 和执行结果。运行器先检查 HTTP 状态,再解析 SSE;例如 `status 403 != 200 (PolicyBlocked)` 表示请求被策略阻断,可通过日志定位返回 `action=block` 的插件。项目配置中的 `review.example.com` 是示例地址,需替换为真实可用的审核服务并同步配置网络授权。真实 Agent 的文本位于 SSE JSON 的 `data.content`,因此响应审核和脱敏插件的 `content_path` 应配置为 `data.content`。
普通 POST 的 `body` 可以是字符串或 JSON 值;非字符串值按 UTF-8 JSON 编码。响应 `body` 使用相同规则。SSE 响应使用 `events` 数组,工具通过宿主现有 SSE 编码器生成真实字节流;每个事件可包含 `event`、`id`、`data`、`comments`、`retry`,`data` 为对象时会先编码为 JSON 文本。
文件场景的 `file.path` 相对于场景 JSON 所在目录解析,并拒绝目录外路径。`field`、`filename`、`mime` 可选,普通请求头通过 `headers` 提供;multipart 的 `Content-Type` 和 boundary 由工具生成。工具记录上游收到的原始路径、请求头和请求体,`expect.file_forwarded: true` 会从原始 multipart 中解析文件并校验字节及 SHA-256 一致。
+36 -5
View File
@@ -4,6 +4,7 @@ import argparse
import asyncio
import hashlib
import json
import logging
import re
import sys
from pathlib import Path
@@ -284,16 +285,31 @@ def _forwarded_file_bytes(record, file_info):
return None
def _assert_status(scenario, response):
expected = scenario.get("expect", {})
if "status" in expected and response.status_code != expected["status"]:
error = _json_or_text(response.content)
error = error.get("error") if isinstance(error, dict) else None
# Only middleware-owned error labels belong in failure diagnostics.
suffix = (
f" ({error})"
if isinstance(error, str)
and error in {"PolicyBlocked", "MiddlewareFailure", "Overloaded", "InvalidMultipart"}
else ""
)
raise ScenarioError(
f"scenario {scenario['id']}: status {response.status_code} != {expected['status']}"
f"{suffix}"
)
def _assert_scenario(scenario, response, record, file_info, events):
expected = scenario.get("expect", {})
if not isinstance(expected, dict):
raise ScenarioError(f"scenario {scenario['id']}: expect must be an object")
checks = {}
checks["status"] = "status" not in expected or response.status_code == expected["status"]
if not checks["status"]:
raise ScenarioError(
f"scenario {scenario['id']}: status {response.status_code} != {expected['status']}"
)
_assert_status(scenario, response)
checks["status"] = True
checks["body"] = "body" not in expected or _json_or_text(response.content) == expected["body"]
if not checks["body"]:
raise ScenarioError(f"scenario {scenario['id']}: response body mismatch")
@@ -353,8 +369,20 @@ async def run_scenarios(config_path, scenario_path):
response = await client.post(
scenario["path"], content=body, headers=headers
)
_assert_status(scenario, response)
events = []
if scenario["kind"] == "sse":
if (
response.headers.get("content-type", "")
.split(";", 1)[0]
.strip()
.lower()
!= "text/event-stream"
):
raise ScenarioError(
f"scenario {scenario['id']}: expected text/event-stream, "
f"received non-SSE response (status {response.status_code})"
)
async def chunks(payload=response.content):
yield payload
@@ -381,7 +409,10 @@ def main(argv=None):
parser = argparse.ArgumentParser(description="Run JSON scenarios through agent-safe-middleware")
parser.add_argument("--config", default="config.yaml")
parser.add_argument("--scenarios", required=True)
parser.add_argument("--verbose", action="store_true", help="显示插件生命周期和执行结果日志")
args = parser.parse_args(argv)
if args.verbose:
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
try:
asyncio.run(run_scenarios(args.config, args.scenarios))
except (ScenarioError, OSError, RuntimeError, ValueError) as exc:
+20
View File
@@ -96,6 +96,26 @@ async def test_runner_executes_sse_post_and_file_with_real_matching(tmp_path, ca
assert len(capsys.readouterr().out.splitlines()) == 3
@pytest.mark.parametrize(
("hook", "expected"),
[
("return {action='block'}", r"status 403 != 200 \(PolicyBlocked\)"),
("error('private-plugin-message')", r"status 502 != 200 \(MiddlewareFailure\)"),
],
)
async def test_sse_rejection_reports_http_status_before_decoding(tmp_path, hook, expected):
config = write_config(tmp_path)
(tmp_path / "marker.lua").write_text(
f"return {{on_request=function(ctx,r) {hook} end}}", encoding="utf-8"
)
with pytest.raises(ScenarioError, match=expected) as failure:
await run_scenarios(config, write_scenarios(tmp_path))
assert "scenario sse:" in str(failure.value)
assert "private-plugin-message" not in str(failure.value)
def test_scenario_schema_and_file_path_safety(tmp_path):
scenario = tmp_path / "scenario.json"
scenario.write_text(json.dumps({"scenarios": []}), encoding="utf-8")