From e880d5cd6259d4562dd06b9af3fa63c26a7b6ba2 Mon Sep 17 00:00:00 2001 From: starrrLight Date: Fri, 16 Oct 2026 00:08:51 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E5=9C=BA=E6=99=AF=E6=B5=8B=E8=AF=95):=20?= =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=96=87=E4=BB=B6=E8=BD=AC=E5=8F=91=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 从原始 multipart 中解析文件并校验 SHA-256,报告补充上游路径和逐项断言结果。 加强状态、响应头、期望事件和 SSE 数据校验,补充路径和文件转发回归测试。 --- docs/plugins.md | 2 +- middleware/scenario_runner.py | 120 ++++++++++++++++++++++++++++++---- tests/test_scenario_runner.py | 20 ++++++ 3 files changed, 128 insertions(+), 14 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 2f3bd50..e6da88e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -148,7 +148,7 @@ Docker 镜像安装 LibreOffice Writer;本地运行需将 `soffice` 或 `libre 普通 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 请求中。 +文件场景的 `file.path` 相对于场景 JSON 所在目录解析,并拒绝目录外路径。`field`、`filename`、`mime` 可选,普通请求头通过 `headers` 提供;multipart 的 `Content-Type` 和 boundary 由工具生成。工具记录上游收到的原始路径、请求头和请求体,`expect.file_forwarded: true` 会从原始 multipart 中解析文件并校验字节及 SHA-256 一致。 ```json { diff --git a/middleware/scenario_runner.py b/middleware/scenario_runner.py index 9eef781..a09390e 100644 --- a/middleware/scenario_runner.py +++ b/middleware/scenario_runner.py @@ -2,7 +2,9 @@ import argparse import asyncio +import hashlib import json +import re import sys from pathlib import Path from urllib.parse import unquote, urlsplit @@ -11,6 +13,7 @@ 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 @@ -38,6 +41,12 @@ def _headers(value, label): 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") @@ -71,6 +80,9 @@ def _validate_scenarios(root): _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"]: @@ -79,6 +91,19 @@ def _validate_scenarios(root): 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 @@ -115,6 +140,7 @@ def build_request(scenario, scenario_dir): ) 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") @@ -132,13 +158,20 @@ def build_request(scenario, scenario_dir): "http://scenario.local" + scenario["path"], headers=headers, data=form, - files={field: (filename, source.read_bytes(), mime)}, + 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_path": source, "file_bytes": source.read_bytes()}, + file_info, ) body = _json_text(scenario.get("body", ""), f"scenario {scenario['id']}.body") @@ -157,11 +190,13 @@ def _response_body(response, kind): 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") + if "data" in event and not isinstance(event["data"], str): + event["data"] = _json_text(event["data"], "SSE event data") event.setdefault("has_data", True) - chunks.append(encode_sse(event, 256 * 1024)) + 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 @@ -210,26 +245,85 @@ def _json_or_text(body): 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_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"]: + 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']}" ) - if "body" in expected and _json_or_text(response.content) != expected["body"]: + 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") - if "events" in expected and [event.get("event") for event in events] != expected["events"]: + 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") - if "upstream_path" in expected and record["path"] != expected["upstream_path"]: + 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"): - if not file_info or file_info["file_bytes"] not in record["body"]: + 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 were not forwarded" + f"scenario {scenario['id']}: uploaded file bytes or SHA-256 mismatch" ) - return {"status": response.status_code, "events": [event.get("event") for event in events]} + 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): diff --git a/tests/test_scenario_runner.py b/tests/test_scenario_runner.py index 2dc6d10..a397845 100644 --- a/tests/test_scenario_runner.py +++ b/tests/test_scenario_runner.py @@ -91,6 +91,8 @@ async def test_runner_executes_sse_post_and_file_with_real_matching(tmp_path, ca assert reports[0]["plugins"] == ["marker"] assert reports[1]["plugins"] == [] assert reports[2]["plugins"] == [] + assert reports[2]["upstream_path"] == "/upload?source=test" + assert reports[2]["assertions"]["file_forwarded"] is True assert len(capsys.readouterr().out.splitlines()) == 3 @@ -100,6 +102,24 @@ def test_scenario_schema_and_file_path_safety(tmp_path): with pytest.raises(ScenarioError, match="must not be empty"): load_scenarios(scenario) + scenario.write_text( + json.dumps( + { + "scenarios": [ + { + "id": "fragment", + "kind": "post", + "path": "/upload#fragment", + "response": {"body": {}}, + } + ] + } + ), + encoding="utf-8", + ) + with pytest.raises(ScenarioError, match="fragment"): + load_scenarios(scenario) + with pytest.raises(ScenarioError, match="below the scenario directory"): build_request( {