diff --git a/README.md b/README.md index c52de82..f34aace 100644 --- a/README.md +++ b/README.md @@ -100,3 +100,13 @@ git diff --check 宿主测试将 Lua 源码内置在用例中,运行时写入测试临时目录以验证实际加载流程;配置测试也自行生成配置,不依赖项目的业务 `plugins/`、`config.yaml` 或模型目录。 测试使用模拟 Agent,并包含真实 Uvicorn/TCP 流式接收、并发满载和客户端断开检查。网络授权测试验证 DNS 地址、白名单、TLS 默认设置及禁止代理/自动重定向;不会连接真实审核供应商、模型或 MCP。实际部署仍需使用甲方接口执行连通性验收。 + +可以用 JSON 场景文件把 SSE、普通 POST 和文件上传一次性送入真实中间层流程。运行器只把固定上游替换为临时模拟 Agent,仍加载 `config.yaml` 中的真实 Lua 插件、路径匹配、审核服务、模型和 LibreOffice;外部依赖缺失或审核失败会直接报错。 + +```powershell +.venv\Scripts\python.exe -m middleware.scenario_runner ` + --config config.yaml ` + --scenarios tests/scenarios/example.json +``` + +场景 JSON 的 `path` 可包含查询参数,`body` 支持字符串或 JSON 值,SSE 返回体使用 `events` 数组,文件路径相对于场景文件目录。完整字段和示例见 [插件开发文档](docs/plugins.md#json-场景运行器)。 diff --git a/docs/plugins.md b/docs/plugins.md index a33dd5a..2f3bd50 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -134,6 +134,65 @@ TXT 仅支持 UTF-8、UTF-8 BOM、带 BOM 的 UTF-16 LE/BE,不猜测其他编 Docker 镜像安装 LibreOffice Writer;本地运行需将 `soffice` 或 `libreoffice` 放入 PATH。缺失时 DOC 的状态为 `failed`,插件允许后仍原样转发。 +## JSON 场景运行器 + +`middleware.scenario_runner` 提供本地场景测试入口。它启动一个临时上游模拟 Agent,把 JSON 中定义的响应返回给中间层,再通过真实 ASGI 入口发送请求。插件文件、`match.paths`、Lua 生命周期、真实审核服务、模型和 LibreOffice 均来自 `--config`,不会被替换;因此缺少任何已配置依赖时运行直接失败。 + +```powershell +.venv\Scripts\python.exe -m middleware.scenario_runner ` + --config config.yaml ` + --scenarios tests/scenarios/example.json +``` + +场景文件必须包含非空的 `scenarios` 数组,每项包含唯一 `id`、`kind`(`sse`、`post` 或 `file`)、`path` 和 `response`。`path` 使用真实请求路径,可附带查询字符串;路径匹配仍由宿主使用解码后的路径完成,查询字符串只用于转发和上游断言。 + +普通 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 请求中。 + +```json +{ + "scenarios": [ + { + "id": "chat-stream", + "kind": "sse", + "path": "/chat/stream?trace=demo", + "headers": {"content-type": "application/json"}, + "body": {"message": "你好", "messages": [{"role": "user", "content": "你好"}]}, + "response": { + "status": 200, + "headers": {"content-type": "text/event-stream"}, + "events": [ + {"event": "run_started", "id": "1", "data": {"data": {"status": "started"}}}, + {"event": "text_delta", "id": "2", "data": {"data": {"content": "安全内容"}}}, + {"event": "run_completed", "id": "3", "data": {"data": {"status": "success"}}} + ] + }, + "expect": {"status": 200, "events": ["run_started", "text_delta", "run_completed"]} + }, + { + "id": "ordinary-post", + "kind": "post", + "path": "/api/echo", + "headers": {"content-type": "application/json"}, + "body": {"message": "普通请求"}, + "response": {"status": 200, "body": {"ok": true}}, + "expect": {"status": 200, "body": {"ok": true}, "upstream_path": "/api/echo"} + }, + { + "id": "text-upload", + "kind": "file", + "path": "/upload?source=test", + "file": {"field": "file", "path": "fixtures/sample.txt", "mime": "text/plain"}, + "response": {"status": 200, "body": {"stored": true}}, + "expect": {"status": 200, "body": {"stored": true}, "file_forwarded": true} + } + ] +} +``` + +示例文件中的 `/chat/stream` 命中当前业务插件链;`/api/echo` 和 `/upload` 不命中当前配置中的业务插件,但仍经过宿主真实请求、响应和附件生命周期。使用方配置上传审核插件后,可以直接把其 `match.paths` 指向 `/upload` 复用文件场景。每个场景运行后输出场景 ID、解码路径、匹配插件 ID、状态码和断言结果;任一断言失败返回非零退出码。 + ## JSON 数据桥 `host.json.decode(text)`、`host.json.encode(value)` 保留对象、数组、布尔、数字和 null。JSON null 用 `host.json.null` 表示;不与 Lua nil 混淆。 diff --git a/middleware/scenario_runner.py b/middleware/scenario_runner.py new file mode 100644 index 0000000..9eef781 --- /dev/null +++ b/middleware/scenario_runner.py @@ -0,0 +1,303 @@ +"""Run JSON-defined HTTP scenarios through the real middleware application.""" + +import argparse +import asyncio +import json +import sys +from pathlib import Path +from urllib.parse import unquote, urlsplit + +import httpx +from aiohttp import web + +from .config import load_settings +from .proxy import create_app +from .sse import decode_sse, encode_sse + + +class ScenarioError(ValueError): + pass + + +def _json_text(value, label): + if isinstance(value, str): + return value + try: + return json.dumps(value, ensure_ascii=False, separators=(",", ":")) + except (TypeError, ValueError) as exc: + raise ScenarioError(f"{label} must be a string or JSON value") from exc + + +def _headers(value, label): + if value is None: + return {} + if not isinstance(value, dict) or any( + not isinstance(name, str) or not isinstance(item, str) for name, item in value.items() + ): + raise ScenarioError(f"{label} must be an object of string headers") + return dict(value) + + +def _split_path(value): + if not isinstance(value, str) or not value.startswith("/"): + raise ScenarioError("scenario path must be an absolute path") + parsed = urlsplit(value) + if ( + parsed.scheme + or parsed.netloc + or parsed.fragment + or any(ord(char) < 0x20 or ord(char) == 0x7F for char in value) + ): + raise ScenarioError("scenario path must not contain scheme, host, fragment or controls") + return parsed + + +def _validate_scenarios(root): + if not isinstance(root, dict) or not isinstance(root.get("scenarios"), list): + raise ScenarioError("scenario file must contain a scenarios array") + if not root["scenarios"]: + raise ScenarioError("scenarios must not be empty") + seen = set() + result = [] + for item in root["scenarios"]: + if not isinstance(item, dict): + raise ScenarioError("each scenario must be an object") + scenario_id = item.get("id") + kind = item.get("kind") + if not isinstance(scenario_id, str) or not scenario_id or scenario_id in seen: + raise ScenarioError("scenario ids must be unique non-empty strings") + if kind not in {"sse", "post", "file"}: + raise ScenarioError(f"scenario {scenario_id}: kind must be sse, post or file") + _split_path(item.get("path")) + if "response" not in item or not isinstance(item["response"], dict): + raise ScenarioError(f"scenario {scenario_id}: response is required") + if kind == "sse" and not isinstance(item["response"].get("events"), list): + raise ScenarioError(f"scenario {scenario_id}: SSE response.events is required") + if kind != "sse" and "body" not in item["response"]: + raise ScenarioError(f"scenario {scenario_id}: response.body is required") + if kind == "file": + file = item.get("file") + if not isinstance(file, dict) or not isinstance(file.get("path"), str): + raise ScenarioError(f"scenario {scenario_id}: file.path is required") + seen.add(scenario_id) + result.append(item) + return result + + +def load_scenarios(path): + path = Path(path).resolve() + try: + root = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ScenarioError(f"cannot read scenario file: {path.name}") from exc + return path, _validate_scenarios(root) + + +def _safe_file_path(root, value): + candidate = (root / value).resolve() + try: + candidate.relative_to(root.resolve()) + except ValueError as exc: + raise ScenarioError("file path must stay below the scenario directory") from exc + if not candidate.is_file(): + raise ScenarioError(f"scenario file does not exist: {value}") + return candidate + + +def build_request(scenario, scenario_dir): + parsed = _split_path(scenario["path"]) + headers = _headers(scenario.get("headers"), f"scenario {scenario['id']}.headers") + kind = scenario["kind"] + if kind == "file": + if any(name.lower() in {"content-type", "content-length"} for name in headers): + raise ScenarioError( + f"scenario {scenario['id']}: file headers cannot set Content-Type or length" + ) + file = scenario["file"] + source = _safe_file_path(scenario_dir, file["path"]) + field = file.get("field", "file") + filename = file.get("filename", source.name) + mime = file.get("mime", "application/octet-stream") + if not all(isinstance(value, str) and value for value in (field, filename, mime)): + raise ScenarioError( + f"scenario {scenario['id']}: file field, filename and mime must be strings" + ) + form = scenario.get("form", {}) + if not isinstance(form, dict) or any( + not isinstance(k, str) or not isinstance(v, str) for k, v in form.items() + ): + raise ScenarioError(f"scenario {scenario['id']}: form must contain string values") + request = httpx.Request( + "POST", + "http://scenario.local" + scenario["path"], + headers=headers, + data=form, + files={field: (filename, source.read_bytes(), mime)}, + ) + return ( + parsed, + dict(request.headers), + request.read(), + {"file_path": source, "file_bytes": source.read_bytes()}, + ) + + body = _json_text(scenario.get("body", ""), f"scenario {scenario['id']}.body") + if not isinstance(scenario.get("body", ""), str) and not any( + name.lower() == "content-type" for name in headers + ): + headers["content-type"] = "application/json" + return parsed, headers, body.encode("utf-8"), None + + +def _response_body(response, kind): + headers = _headers(response.get("headers"), "response.headers") + if kind == "sse": + chunks = [] + for event in response["events"]: + if not isinstance(event, dict): + raise ScenarioError("SSE events entries must be objects") + event = dict(event) + data = event.get("data") + if data is not None and not isinstance(data, str): + event["data"] = _json_text(data, "SSE event data") + event.setdefault("has_data", True) + chunks.append(encode_sse(event, 256 * 1024)) + headers.setdefault("content-type", "text/event-stream") + return b"".join(chunks), headers + return _json_text(response.get("body", ""), "response.body").encode("utf-8"), headers + + +class MockUpstream: + def __init__(self): + self.app = web.Application() + self.app.router.add_route("*", "/{path:.*}", self.handle) + self.runner = None + self.site = None + self.current = None + self.records = [] + + async def __aenter__(self): + self.runner = web.AppRunner(self.app) + await self.runner.setup() + self.site = web.TCPSite(self.runner, "127.0.0.1", 0) + await self.site.start() + return self + + async def __aexit__(self, *_): + await self.runner.cleanup() + + @property + def url(self): + return f"http://127.0.0.1:{self.site._server.sockets[0].getsockname()[1]}" + + async def handle(self, request): + if self.current is None: + raise web.HTTPServiceUnavailable() + body = await request.read() + self.records.append( + {"path": request.raw_path, "headers": dict(request.headers), "body": body} + ) + response_body, headers = _response_body(self.current["response"], self.current["kind"]) + return web.Response( + status=self.current["response"].get("status", 200), headers=headers, body=response_body + ) + + +def _json_or_text(body): + try: + return json.loads(body.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError): + return body.decode("utf-8", errors="replace") + + +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") + if "status" in expected and response.status_code != expected["status"]: + raise ScenarioError( + f"scenario {scenario['id']}: status {response.status_code} != {expected['status']}" + ) + if "body" in expected and _json_or_text(response.content) != expected["body"]: + raise ScenarioError(f"scenario {scenario['id']}: response body mismatch") + if "events" in expected and [event.get("event") for event in events] != expected["events"]: + raise ScenarioError(f"scenario {scenario['id']}: SSE event names mismatch") + if "upstream_path" in expected and record["path"] != expected["upstream_path"]: + raise ScenarioError(f"scenario {scenario['id']}: upstream path mismatch") + if expected.get("file_forwarded"): + if not file_info or file_info["file_bytes"] not in record["body"]: + raise ScenarioError( + f"scenario {scenario['id']}: uploaded file bytes were not forwarded" + ) + return {"status": response.status_code, "events": [event.get("event") for event in events]} + + +async def run_scenarios(config_path, scenario_path): + scenario_path, scenarios = load_scenarios(scenario_path) + settings = load_settings(config_path) + async with MockUpstream() as upstream: + settings = settings.model_copy(update={"upstream": upstream.url}) + app = create_app(settings) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app), base_url="http://middleware" + ) as client: + reports = [] + for scenario in scenarios: + parsed, headers, body, file_info = build_request(scenario, scenario_path.parent) + decoded_path = unquote(parsed.path) + matched = [ + plugin.id for plugin in app.state.manager.plugins_for_path(decoded_path) + ] + upstream.current = scenario + upstream.records.clear() + if scenario["kind"] == "file": + response = await client.post( + scenario["path"], content=body, headers=headers + ) + else: + response = await client.post( + scenario["path"], content=body, headers=headers + ) + events = [] + if scenario["kind"] == "sse": + + async def chunks(payload=response.content): + yield payload + + events = [ + event + async for event in decode_sse( + chunks(), settings.limits.max_sse_frame_bytes + ) + ] + record = ( + upstream.records[-1] + if upstream.records + else {"path": "", "body": b"", "headers": {}} + ) + result = _assert_scenario(scenario, response, record, file_info, events) + result.update({"id": scenario["id"], "path": decoded_path, "plugins": matched}) + reports.append(result) + print(json.dumps(result, ensure_ascii=False)) + return reports + + +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) + args = parser.parse_args(argv) + try: + asyncio.run(run_scenarios(args.config, args.scenarios)) + except (ScenarioError, OSError, RuntimeError, ValueError) as exc: + print(f"场景运行失败: {exc}", file=sys.stderr) + return 1 + except Exception as exc: + print(f"场景运行失败: {type(exc).__name__}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/scenarios/example.json b/tests/scenarios/example.json new file mode 100644 index 0000000..9d50e98 --- /dev/null +++ b/tests/scenarios/example.json @@ -0,0 +1,71 @@ +{ + "scenarios": [ + { + "id": "chat-stream", + "kind": "sse", + "path": "/chat/stream?trace=demo", + "headers": { + "content-type": "application/json", + "x-test": "sse" + }, + "body": { + "message": "你好", + "messages": [{"role": "user", "content": "你好"}] + }, + "response": { + "status": 200, + "headers": {"content-type": "text/event-stream"}, + "events": [ + {"event": "run_started", "id": "1", "data": {"data": {"status": "started"}}}, + {"event": "text_delta", "id": "2", "data": {"data": {"content": "安全内容"}}}, + {"event": "run_completed", "id": "3", "data": {"data": {"status": "success"}}} + ] + }, + "expect": { + "status": 200, + "events": ["run_started", "text_delta", "run_completed"], + "upstream_path": "/chat/stream?trace=demo" + } + }, + { + "id": "ordinary-post", + "kind": "post", + "path": "/api/echo", + "headers": {"content-type": "application/json"}, + "body": {"message": "普通请求"}, + "response": { + "status": 200, + "headers": {"content-type": "application/json"}, + "body": {"ok": true} + }, + "expect": { + "status": 200, + "body": {"ok": true}, + "upstream_path": "/api/echo" + } + }, + { + "id": "text-upload", + "kind": "file", + "path": "/upload?source=test", + "headers": {"x-test": "upload"}, + "file": { + "field": "file", + "path": "fixtures/sample.txt", + "filename": "sample.txt", + "mime": "text/plain" + }, + "response": { + "status": 200, + "headers": {"content-type": "application/json"}, + "body": {"stored": true} + }, + "expect": { + "status": 200, + "body": {"stored": true}, + "upstream_path": "/upload?source=test", + "file_forwarded": true + } + } + ] +} diff --git a/tests/scenarios/fixtures/sample.docx b/tests/scenarios/fixtures/sample.docx new file mode 100644 index 0000000..b7231f9 Binary files /dev/null and b/tests/scenarios/fixtures/sample.docx differ diff --git a/tests/scenarios/fixtures/sample.txt b/tests/scenarios/fixtures/sample.txt new file mode 100644 index 0000000..48f29b5 --- /dev/null +++ b/tests/scenarios/fixtures/sample.txt @@ -0,0 +1 @@ +场景运行器附件正文 diff --git a/tests/test_scenario_runner.py b/tests/test_scenario_runner.py new file mode 100644 index 0000000..2dc6d10 --- /dev/null +++ b/tests/test_scenario_runner.py @@ -0,0 +1,131 @@ +import json + +import pytest + +from middleware.scenario_runner import ScenarioError, build_request, load_scenarios, run_scenarios + + +def write_config(tmp_path): + plugin = tmp_path / "marker.lua" + plugin.write_text( + "return {on_request=function(ctx,r) r.headers['x-marker']='matched'; " + "return {action='replace',value=r} end}", + encoding="utf-8", + ) + config = tmp_path / "config.yaml" + config.write_text( + "upstream: http://unused\nplugins:\n" + " - id: marker\n file: marker.lua\n match:\n paths: [/stream]\n", + encoding="utf-8", + ) + return config + + +def write_scenarios(tmp_path): + fixture = tmp_path / "sample.txt" + fixture.write_text("附件正文", encoding="utf-8") + scenario = tmp_path / "scenarios.json" + scenario.write_text( + json.dumps( + { + "scenarios": [ + { + "id": "sse", + "kind": "sse", + "path": "/stream?token=a%2Fb", + "headers": {"content-type": "application/json"}, + "body": {"message": "hello"}, + "response": { + "status": 200, + "headers": {"content-type": "text/event-stream"}, + "events": [ + {"event": "run_started", "data": {"data": {"ok": True}}}, + {"event": "run_completed", "data": {"data": {"ok": True}}}, + ], + }, + "expect": { + "status": 200, + "events": ["run_started", "run_completed"], + "upstream_path": "/stream?token=a%2Fb", + }, + }, + { + "id": "post", + "kind": "post", + "path": "/other/", + "headers": {"content-type": "application/json"}, + "body": {"hello": "普通 POST"}, + "response": {"status": 201, "body": {"created": True}}, + "expect": { + "status": 201, + "body": {"created": True}, + "upstream_path": "/other/", + }, + }, + { + "id": "file", + "kind": "file", + "path": "/upload?source=test", + "file": {"path": "sample.txt", "field": "file", "mime": "text/plain"}, + "response": {"status": 200, "body": {"stored": True}}, + "expect": { + "status": 200, + "body": {"stored": True}, + "upstream_path": "/upload?source=test", + "file_forwarded": True, + }, + }, + ] + }, + ensure_ascii=False, + ), + encoding="utf-8", + ) + return scenario + + +async def test_runner_executes_sse_post_and_file_with_real_matching(tmp_path, capsys): + reports = await run_scenarios(write_config(tmp_path), write_scenarios(tmp_path)) + + assert [report["id"] for report in reports] == ["sse", "post", "file"] + assert reports[0]["plugins"] == ["marker"] + assert reports[1]["plugins"] == [] + assert reports[2]["plugins"] == [] + assert len(capsys.readouterr().out.splitlines()) == 3 + + +def test_scenario_schema_and_file_path_safety(tmp_path): + scenario = tmp_path / "scenario.json" + scenario.write_text(json.dumps({"scenarios": []}), encoding="utf-8") + with pytest.raises(ScenarioError, match="must not be empty"): + load_scenarios(scenario) + + with pytest.raises(ScenarioError, match="below the scenario directory"): + build_request( + { + "id": "escape", + "kind": "file", + "path": "/upload", + "file": {"path": "../secret.txt"}, + }, + tmp_path, + ) + + +def test_file_request_generates_multipart_headers(tmp_path): + source = tmp_path / "input.txt" + source.write_text("内容", encoding="utf-8") + parsed, headers, body, info = build_request( + { + "id": "file", + "kind": "file", + "path": "/upload", + "headers": {"x-test": "yes"}, + "file": {"path": "input.txt", "field": "attachment"}, + }, + tmp_path, + ) + assert parsed.path == "/upload" + assert headers["x-test"] == "yes" + assert headers["content-type"].startswith("multipart/form-data; boundary=") + assert info["file_bytes"] in body