"""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())