Files
starrrLight fa937803c7 fix(场景): 默认输出插件运行日志
场景命令直接输出插件消息并保留各日志级别,详细模式继续显示生命周期。保持标准输出为场景结果 JSON,补充默认和详细模式的命令行回归测试并简化文档。
2026-10-16 14:40:45 +08:00

437 lines
17 KiB
Python

"""Run JSON-defined HTTP scenarios through the real middleware application."""
import argparse
import asyncio
import hashlib
import json
import logging
import re
import sys
from pathlib import Path
from urllib.parse import unquote, urlsplit
import httpx
from aiohttp import web
from .config import load_settings
from .errors import MiddlewareError
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 _status(value, label):
if type(value) is not int or not 100 <= value <= 599:
raise ScenarioError(f"{label} must be an HTTP status integer")
return 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")
response = item["response"]
_status(response.get("status", 200), f"scenario {scenario_id}.response.status")
_headers(response.get("headers"), f"scenario {scenario_id}.response.headers")
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")
expected = item.get("expect", {})
if not isinstance(expected, dict):
raise ScenarioError(f"scenario {scenario_id}: expect must be an object")
if "status" in expected:
_status(expected["status"], f"scenario {scenario_id}.expect.status")
if "events" in expected and (
kind != "sse"
or not isinstance(expected["events"], list)
or any(not isinstance(event, str) for event in expected["events"])
):
raise ScenarioError(
f"scenario {scenario_id}: expect.events is only a string list for SSE"
)
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"])
file_bytes = source.read_bytes()
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, file_bytes, mime)},
)
file_info = {
"file_path": source,
"file_bytes": file_bytes,
"field": field,
"filename": filename,
"sha256": hashlib.sha256(file_bytes).hexdigest(),
}
return (
parsed,
dict(request.headers),
request.read(),
file_info,
)
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)
if "data" in event and not isinstance(event["data"], str):
event["data"] = _json_text(event["data"], "SSE event data")
event.setdefault("has_data", True)
try:
chunks.append(encode_sse(event, 256 * 1024))
except (MiddlewareError, TypeError, ValueError) as exc:
raise ScenarioError("SSE event contains an invalid field") from exc
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 _forwarded_file_bytes(record, file_info):
"""Extract the selected file part from the raw multipart body."""
content_type = next(
(value for name, value in record["headers"].items() if name.lower() == "content-type"),
"",
)
match = re.search(r"boundary=(?:\"([^\"]+)\"|([^;\s]+))", content_type, re.I)
if match is None:
return None
boundary = (match.group(1) or match.group(2)).encode("latin-1", errors="ignore")
marker = b"--" + boundary
for part in record["body"].split(marker)[1:]:
if part.startswith(b"--"):
break
if part.startswith(b"\r\n"):
part = part[2:]
headers, separator, payload = part.partition(b"\r\n\r\n")
if not separator:
continue
if payload.endswith(b"\r\n"):
payload = payload[:-2]
disposition = next(
(
line
for line in headers.split(b"\r\n")
if line.lower().startswith(b"content-disposition:")
),
b"",
)
name_match = re.search(rb'\bname="([^\"]*)"', disposition, re.I)
if name_match is None:
continue
name = name_match.group(1).decode("utf-8", errors="replace")
if name == file_info["field"]:
return payload
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 = {}
_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")
checks["events"] = (
"events" not in expected or [event.get("event") for event in events] == expected["events"]
)
if not checks["events"]:
raise ScenarioError(f"scenario {scenario['id']}: SSE event names mismatch")
checks["upstream_path"] = (
"upstream_path" not in expected or record["path"] == expected["upstream_path"]
)
if not checks["upstream_path"]:
raise ScenarioError(f"scenario {scenario['id']}: upstream path mismatch")
if expected.get("file_forwarded"):
forwarded = _forwarded_file_bytes(record, file_info) if file_info else None
checks["file_forwarded"] = bool(
forwarded is not None
and hashlib.sha256(forwarded).hexdigest() == file_info["sha256"]
and forwarded == file_info["file_bytes"]
)
if not checks["file_forwarded"]:
raise ScenarioError(
f"scenario {scenario['id']}: uploaded file bytes or SHA-256 mismatch"
)
return {
"status": response.status_code,
"events": [event.get("event") for event in events],
"upstream_path": record["path"],
"assertions": checks,
}
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
)
_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
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)
parser.add_argument("--verbose", action="store_true", help="显示插件生命周期和执行结果日志")
args = parser.parse_args(argv)
handler = logging.StreamHandler()
if not args.verbose:
handler.addFilter(
lambda record: (
record.levelno >= logging.WARNING or str(record.msg).startswith("plugin_log ")
)
)
logging.basicConfig(
level=logging.INFO, format="%(levelname)s %(name)s %(message)s", handlers=[handler]
)
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())