Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
fix: normalize parse paths and validate API filenames
myhlolicab8e460399f
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.ymlindex 4a2df0de..83ad6318 100644--- a/.github/workflows/cli.yml+++ b/.github/workflows/cli.yml@@ -127,6 +127,17 @@ jobs:tests/unittest/test_doclib_instance_dependencies.py \tests/unittest/test_doclib_lifespan.py \tests/unittest/test_doclib_architecture.py+ - name: Run Windows and macOS filename boundary tests+ if: runner.os != 'Linux'+ run: |+ uv run --no-project --no-sync python -m pytest -o addopts='' --strict-markers \+ --junitxml=build/ci/filenames.xml \+ -k 'path_extension or parse_filename or csv or task_filename' \+ tests/unittest/test_filetypes.py \+ tests/unittest/test_kit_commands.py \+ tests/unittest/test_task_tiers.py \+ tests/unittest/test_file_parse.py \+ tests/unittest/test_file_parse_http.py- name: Retain test reportsif: ${{ always() }}uses: actions/upload-artifact@v6diff --git a/docs/en/usage/file_parse.md b/docs/en/usage/file_parse.mdindex dd34730f..873f1c34 100644--- a/docs/en/usage/file_parse.md+++ b/docs/en/usage/file_parse.md@@ -44,6 +44,10 @@ Omitting tier lets the upstream choose Standard → Basic → Flash → Advanced`output_formats` is neither a JSON string nor a comma-separated value: use repeated form fields. `include_model_output` is removed and returns 400 when supplied.+Multipart filenames retain the existing compatibility behavior: backslashes are treated as directory separators, and directory components are removed before validation. Both `../report.csv` and `C:\fakepath\report.csv` are submitted upstream as `report.csv`.++The resulting basename must contain 1–1024 characters, must not be exactly `.` or `..`, and must not contain slashes, backslashes, colons, or Unicode `Cc` control characters. Unicode names, spaces, and hidden names such as `.report.csv` are allowed, without trimming or percent-decoding. Invalid names return `400 invalid_request` before creating an upload staging file or an upstream task. The JSON [Tasks API](tasks.md) instead rejects path-like `file_name` values directly.+## Upload and attachment responsesThese are Bash/curl examples; in Windows PowerShell use `curl.exe` and adjust line continuations. The service calculates the size and hash from the actual uploaded file.diff --git a/docs/en/usage/tasks.md b/docs/en/usage/tasks.mdindex 50bcf4e4..a39981d3 100644--- a/docs/en/usage/tasks.md+++ b/docs/en/usage/tasks.md@@ -35,7 +35,7 @@ Each `files[]` entry:| Field | Type | Requirement ||---|---|---|-| `file_name` | string | Required logical filename, 1–1024 characters, retaining its extension. Duplicate names are allowed. |+| `file_name` | string | Required logical basename, 1–1024 characters, retaining its extension without directory components. Duplicate names are allowed. || `bytes` | integer or null | Required positive integer for uploads. Optional for URLs; when supplied, must match the actual size. || `url` | string or null | HTTP(S) download URL; omitted or null means a client upload. || `sha256sum` | string or null | Optional 64-character lowercase hexadecimal SHA-256 for validation and, for uploads, cache preflight. |@@ -43,6 +43,12 @@ Each `files[]` entry:Requests must omit `file_id/client_file_id`, including null values. The server allocates public `file_id` values in input order; duplicate names or content still receive different IDs. Use IDs to correlate uploads, queries, cancellation, and downloads. Local/Router result Files IDs match these IDs; Files lookup returns 404 before the result exists. Source-cache IDs remain private.+For both uploads and URL inputs, `file_name` must not contain `/`, backslashes, colons, or Unicode `Cc` control characters, and must not be exactly `.` or `..`. Unicode names, spaces, `.report.csv`, and `report..csv` are allowed. Accepted names are preserved without trimming, percent-decoding, or silently stripping directory components.++Names such as `../report.csv`, `C:\input\report.csv`, and `report.csv:stream` return `400 invalid_request` with `error.param="files.<index>.file_name"`. One invalid name rejects the entire manifest before allocating tasks, file IDs, or upload links; Routers do not forward it downstream.++This tightens acceptance of path-like names: custom clients must extract the basename locally before submission. The official SDK already sends `path.name`. Logical names identify formats and display names, not server filesystem locations; storage continues to use generated identifiers or content hashes. Local CLI paths still support `../` and absolute paths. The multipart [file-parse API](file_parse.md) retains its compatibility behavior of stripping directory components before validating the resulting basename.+### Tier selection- For PDFs/images, an omitted or null tier selects the first supported value in **standard → basic → flash → advanced** order. Advanced is selected automatically only when it is the sole available tier.diff --git a/docs/zh/usage/file_parse.md b/docs/zh/usage/file_parse.mdindex 980c6a19..4022e086 100644--- a/docs/zh/usage/file_parse.md+++ b/docs/zh/usage/file_parse.md@@ -38,6 +38,10 @@ MINERU_API_URL=https://mineru.net/api MINERU_API_KEY=your-key \| `wait_timeout` | `3600` | 整数秒,范围 `0–3600`。 || `request_id` | 自动生成 | 1–64 个字母、数字、下划线或短横线。提前指定并保存它,可在连接中断后查询。 |+上传名称沿用 multipart 兼容规则:先将反斜杠视为目录分隔符并去除目录,再校验 basename。例如 `../report.csv` 和 `C:\fakepath\report.csv` 都以 `report.csv` 提交给上游。++得到的文件名必须为 1–1024 个字符,不能恰好为 `.` 或 `..`,不能包含斜杠、反斜杠、冒号或 Unicode `Cc` 类控制字符;中文、空格和 `.report.csv` 等隐藏名称允许使用。不裁剪空格或解码百分号。非法名称在创建上传暂存文件和上游任务前返回 `400 invalid_request`。这与 JSON [Tasks API](tasks.md) 直接拒绝路径形式 `file_name` 的规则不同。+未提供 tier 表单字段时,包装层在上游 Tasks 请求中省略该字段,由上游按 **standard → basic → flash → advanced** 选择默认档位;仅开放 advanced 时自动选择 advanced。显式值原样传递,PDF/图片请求的档位不受上游支持时返回错误,不自动升降档。所有正常可用服务都支持 Office、HTML 等现有原生格式,固定使用 flash,即使传入上游未开放的合法档位也不改变原生解析路径。diff --git a/docs/zh/usage/tasks.md b/docs/zh/usage/tasks.mdindex 117ae895..2e2fc00a 100644--- a/docs/zh/usage/tasks.md+++ b/docs/zh/usage/tasks.md@@ -96,12 +96,18 @@ Office、HTML 等已支持的原生文档固定使用 flash,不受请求 tier| 字段 | 必填 | 说明 ||---|---|---|-| `file_name` | 是 | 逻辑文件名,保留扩展名;不同条目允许同名。 |+| `file_name` | 是 | 1–1024 个字符的逻辑文件名(basename),保留扩展名,不含目录;不同条目允许同名。 || `url` | 否 | HTTP(S) 文件下载地址,受部署来源策略约束;省略或 `null` 表示客户端上传。 || `bytes` | 条件 | 上传项必填;URL 项可省略或为 `null`。提供时必须是严格正整数。 || `sha256sum` | 否 | 64 位小写十六进制 SHA-256;用于完整性校验,上传项还用于源文件缓存预检。 || `page_range` | 否 | 逐文件 PDF 页范围,未提供时继承全局值;非 PDF 仍只支持整本解析。 |+`file_name` 对上传和 URL 输入使用相同校验:不允许 `/`、反斜杠、冒号、Unicode `Cc` 类控制字符,也不能恰好为 `.` 或 `..`。中文、空格、`.report.csv` 和 `report..csv` 等名称允许使用;服务不裁剪空格、不解码百分号,也不把路径自动截成文件名。++例如 `../report.csv`、`C:\input\report.csv` 和 `report.csv:stream` 均返回 `400 invalid_request`,`error.param` 为 `files.<index>.file_name`。清单中任一名称非法,整个请求在分配任务、文件 ID 和上传链接前失败,Router 不向下游转发。++这是对路径形式名称的接口收紧:自定义客户端应在本地提取 basename 后提交;官方 SDK 已使用 `path.name`。逻辑文件名用于格式识别和展示,不指定服务器的读写路径;服务端继续使用生成的标识或内容哈希存储文件。CLI 的本地输入路径仍支持 `../` 和绝对路径。multipart [file_parse](file_parse.md) 保留先去除目录、再校验文件名的兼容行为。+### 文件 ID 与输入关联服务端为每个输入分配唯一的 `file_id`,请求不得包含 `client_file_id` 或 `file_id`,即使值为 `null` 也返回 `400 invalid_request`。diff --git a/mineru/filetypes.py b/mineru/filetypes.pyindex f5544c10..ebaf6ea2 100644--- a/mineru/filetypes.py+++ b/mineru/filetypes.py@@ -1,6 +1,7 @@from __future__ import annotationsimport re+import unicodedatafrom pathlib import Pathfrom typing import Final@@ -145,15 +146,25 @@ def rtf_header_offset(file_bytes: bytes) -> int | None:def normalize_parse_extension(path_or_ext: str | Path) -> str:+ """优先提取路径后缀,无后缀时按裸扩展名归一化。"""text = str(path_or_ext)- if text.startswith("."):- return text.lower().lstrip(".")suffix = Path(text).suffixif suffix:return suffix.lower().lstrip(".")return text.lower().lstrip(".")+def validate_parse_filename(name: str) -> str:+ """校验 API 使用的纯文件名,原样返回且不访问文件系统或改写名称。"""+ if not 1 <= len(name) <= 1024 or name in {".", ".."}:+ raise ValueError("File name must contain 1–1024 characters and must not be '.' or '..'")+ if any(char in name for char in ("/", "\\", ":")):+ raise ValueError("File name must be a basename without '/', '\\', or ':'")+ if any(unicodedata.category(char) == "Cc" for char in name):+ raise ValueError("File name must not contain control characters")+ return name++def file_type_for_extension(path_or_ext: str | Path) -> str:ext = normalize_parse_extension(path_or_ext)return FILE_TYPE_BY_EXTENSION.get(ext, ext or "unknown")diff --git a/mineru/kit/file_parse/app.py b/mineru/kit/file_parse/app.pyindex 752cb9d1..8b881ed9 100644--- a/mineru/kit/file_parse/app.py+++ b/mineru/kit/file_parse/app.py@@ -22,6 +22,7 @@ from starlette.exceptions import HTTPExceptionfrom starlette.requests import ClientDisconnectfrom starlette.types import ASGIApp, Receive, Scope, Send+from ...filetypes import validate_parse_filenamefrom ...task_types import TASK_OUTPUT_FORMATSfrom ...types import TIERSfrom .models import GatewayError, ParseOptions, Record@@ -92,7 +93,14 @@ def _request_schema() -> dict[str, Any]:properties = ParseOptions.model_json_schema()["properties"]properties.update({- "file": {"type": "string", "format": "binary"},+ "file": {+ "type": "string",+ "format": "binary",+ "description": (+ "One file. Directory components are stripped from its multipart filename before validating the "+ "1–1024 character basename; '.', '..', colons, and Unicode Cc control characters are rejected."+ ),+ },"request_id": {"type": "string", "pattern": REQUEST_ID.pattern},"wait_timeout": {"type": "integer", "minimum": 0, "maximum": 3600, "default": 3600},}@@ -146,8 +154,10 @@ async def _receive_file(request: Request, service: FileParseService) -> tuple[Re):raise GatewayError("invalid_request", "Exactly one file and textual parameters are required", 400)filename = (upload.filename or "").replace("\\", "/").rsplit("/", 1)[-1]- if filename in {"", ".", ".."} or len(filename) > 1024 or any(ord(char) < 32 for char in filename):- raise GatewayError("invalid_request", "A valid filename is required", 400)+ try:+ validate_parse_filename(filename)+ except ValueError as exc:+ raise GatewayError("invalid_request", str(exc), 400) from excrequest_id = str(form.get("request_id", uuid.uuid4().hex))if not REQUEST_ID.fullmatch(request_id):raise GatewayError("invalid_request", "Invalid request_id", 400)diff --git a/mineru/tasks/contracts.py b/mineru/tasks/contracts.pyindex 82121995..41369ea9 100644--- a/mineru/tasks/contracts.py+++ b/mineru/tasks/contracts.py@@ -5,8 +5,9 @@ from __future__ import annotationsfrom typing import Literalfrom docvortex.document.page_range import PAGE_RANGE_DESCRIPTION-from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, model_validator+from pydantic import AnyHttpUrl, BaseModel, ConfigDict, Field, field_validator, model_validator+from ..filetypes import validate_parse_filenamefrom ..task_types import TaskFileState, TaskOutputFormat, TaskStatusfrom ..types import Tier@@ -54,12 +55,25 @@ class TaskFileInput(BaseModel):"""仅声明输入,文件标识由服务端分配,不接受任何客户端 ID。"""model_config = ConfigDict(extra="forbid")- file_name: str = Field(min_length=1, max_length=1024)+ file_name: str = Field(+ min_length=1,+ max_length=1024,+ description=(+ "Logical basename, not a path. No '/', backslash, ':', Unicode Cc control characters, or names '.' / '..'. "+ "Hidden names and spaces are allowed; accepted names are preserved without trimming or URL decoding."+ ),+ )bytes: int | None = Field(default=None, gt=0, strict=True)url: str | None = Nonesha256sum: str | None = Field(default=None, pattern=r"^[a-f0-9]{64}$")page_range: str | None = Field(default=None, description=PAGE_RANGE_DESCRIPTION)+ @field_validator("file_name")+ @classmethod+ def validate_file_name(cls, value: str) -> str:+ """在接单前统一拒绝路径名称,保留逐文件字段的错误位置。"""+ return validate_parse_filename(value)+@model_validator(mode="after")def validate_source(self) -> TaskFileInput:"""上传项必须声明大小;URL 只校验合法性,保留签名地址的原始字符串。"""diff --git a/tests/unittest/test_file_parse.py b/tests/unittest/test_file_parse.pyindex 947374f3..d5acae7b 100644--- a/tests/unittest/test_file_parse.py+++ b/tests/unittest/test_file_parse.py@@ -235,6 +235,58 @@ def test_file_parse_forwards_tier_only_when_provided(tmp_path: Path, tier: str |assert options["tier"] == tier+ "filename,expected",+ [+ ("../t.csv", "t.csv"),+ ("/input/t.csv", "t.csv"),+ (r"C:\fakepath\t.csv", "t.csv"),+ (r"\\server\share\t.csv", "t.csv"),+ (".t.csv", ".t.csv"),+ ("报告 2026.CSV", "报告 2026.CSV"),+ ("%2e%2e%2ft.csv", "%2e%2e%2ft.csv"),+ ],+)+def test_file_parse_filename_retains_basename_compatibility(tmp_path: Path, filename: str, expected: str) -> None:+ """multipart 继续去除两类目录分隔符,随后原样转发合法文件名。"""+ upstream = Upstream()+ app = application(tmp_path, upstream)+ with TestClient(app) as client:+ response = client.post("/v1/file_parse", files={"file": (filename, b"name,age\nAlice,30\n", "text/csv")})+ assert response.status_code == 200, response.text+ assert upstream.tasks["task_1"]["options"]["files"][0]["file_name"] == expected+ assert not list(app.state.service.store.sources.iterdir())+++ "filename", ["../", ".", "..", "a" * 1025, "C:t.csv", "t.csv:stream", "t\x00.csv", "t\x7f.csv", "t\x85.csv"]+)+def test_file_parse_filename_rejected_before_staging(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, filename: str) -> None:+ """basename 非法时,包装层在创建暂存文件或联系上游前返回参数错误。"""+ upstream = Upstream()+ app = application(tmp_path, upstream)++ def unexpected_staging(*args: Any, **kwargs: Any) -> tuple[int, str]:+ """参数校验失败后不允许创建上传暂存文件。"""+ pytest.fail("invalid filename must be rejected before staging")++ # 原始 multipart 保留控制字符,避免 HTTPX 将文件名中的字符自动转义。+ body = (+ f'--boundary\r\nContent-Disposition: form-data; name="file"; filename="{filename}"\r\n'+ "Content-Type: text/csv\r\n\r\nname,age\nAlice,30\n\r\n--boundary--\r\n"+ ).encode("utf-8")+ with TestClient(app) as client:+ monkeypatch.setattr("mineru.kit.file_parse.app.tempfile.mkstemp", unexpected_staging)+ response = client.post(+ "/v1/file_parse", content=body, headers={"Content-Type": "multipart/form-data; boundary=boundary"}+ )+ assert response.status_code == 400, response.text+ assert response.json()["error"]["code"] == "invalid_request"+ assert not app.state.service.records+ assert not list(app.state.service.store.sources.iterdir())+ assert not upstream.calls++@pytest.mark.parametrize("formats", FORMATS)def test_formats_are_returned_unchanged(tmp_path: Path, formats: list[str]) -> None:"""覆盖全部十五种格式组合及附件字节、文件名、MIME 和临时文件释放。"""diff --git a/tests/unittest/test_file_parse_http.py b/tests/unittest/test_file_parse_http.pyindex 279f27ab..66843c56 100644--- a/tests/unittest/test_file_parse_http.py+++ b/tests/unittest/test_file_parse_http.py@@ -3,6 +3,7 @@from __future__ import annotationsimport io+import jsonimport socketimport subprocessimport sys@@ -84,6 +85,26 @@ def test_api_and_router_all_formats(live_service: _LiveService, tmp_path: Path)assert_clean(app.state.service.store.sources)+def test_file_parse_filename_is_metadata_over_tcp(live_service: _LiveService, tmp_path: Path) -> None:+ """带目录的 multipart 名称经真实 API/Router 解析时,只读取上传字节。"""+ sentinel = tmp_path / "outside.csv"+ server_data = b"name,value\nSERVER_SENTINEL,999\n"+ sentinel.write_bytes(server_data)+ content = b"name,value\nUPLOADED_BYTES,42\n"+ with wrapper(tmp_path / "wrapper", live_service.url, "test-key") as (client, app):+ for index, name in enumerate(("../outside.csv", str(sentinel), r"C:\fakepath\outside.csv")):+ response = parse_file(client, f"filename_{index}", name, content, ["default"])+ assert response.status_code == 200, response.text+ assert 'filename="outside.zip"' in response.headers["content-disposition"]+ with zipfile.ZipFile(io.BytesIO(response.content)) as archive:+ markdown = archive.read("markdown.md")+ assert b"UPLOADED_BYTES" in markdown and b"SERVER_SENTINEL" not in markdown+ assert json.loads(archive.read("middle_json.json"))["extensions"]["mineru"]["tier"] == "flash"+ assert sentinel.read_bytes() == server_data+ assert_clean(app.state.service.store.sources)+ assert_clean(app.state.service.store.results)++def cloud_bridge(upstream: Upstream) -> FastAPI:"""通过独立网络端口暴露模拟 SaaS 协议,数据传输仍走真实 HTTP。"""app = FastAPI()diff --git a/tests/unittest/test_filetypes.py b/tests/unittest/test_filetypes.pyindex c507f116..16563bfd 100644--- a/tests/unittest/test_filetypes.py+++ b/tests/unittest/test_filetypes.py@@ -22,11 +22,89 @@ from mineru.filetypes import (TEXT_EXTENSIONS,is_flash_only_parse_extension,is_page_range_parse_extension,+ is_tiered_parse_extension,+ mime_type_for_extension,+ normalize_parse_extension,+ validate_parse_filename,)from mineru.kit.common import ensure_supported_inputs, expand_input_pathsfrom mineru.parser import parse[email protected]("as_path", [False, True])+ "template",+ [+ "{ext}",+ ".{ext}",+ "in/t.{ext}",+ "../in/t.{ext}",+ "./in/t.{ext}",+ ".data/t.{ext}",+ ".t.{ext}",+ "/absolute/t.{ext}",+ r"..\in\t.{ext}",+ ],+)+ "ext,mime,flash",+ [+ ("CSV", "text/csv", True),+ ("DOCX", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", True),+ ("PDF", "application/pdf", False),+ ("JPG", "image/jpeg", False),+ ],+)+def test_path_extension_controls_format_capabilities(as_path: bool, template: str, ext: str, mime: str, flash: bool) -> None:+ """相对路径、隐藏名称和裸扩展名共享后缀、档位、分页与 MIME 判定。"""+ text = template.format(ext=ext)+ value = Path(text) if as_path else text+ assert normalize_parse_extension(value) == ext.lower()+ assert is_flash_only_parse_extension(value) is flash+ assert is_tiered_parse_extension(value) is (not flash)+ assert is_page_range_parse_extension(value) is (ext == "PDF")+ assert mime_type_for_extension(value) == mime+++ "name",+ ["report.csv", ".report.csv", "report..csv", "报告 2026.CSV", " report.csv ", "%2e%2e%2freport.csv", "README", "a" * 1024],+)+def test_parse_filename_preserves_valid_basename(name: str) -> None:+ """纯文件名校验保留中文、空格、隐藏名称和百分号,不改写输入或限制扩展名。"""+ assert validate_parse_filename(name) == name+++ "name",+ [+ "",+ ".",+ "..",+ "a" * 1025,+ "../t.csv",+ "in/t.csv",+ "/t.csv",+ r"..\t.csv",+ r"C:\in\t.csv",+ "C:t.csv",+ r"\\server\share\t.csv",+ "t.csv:stream",+ ],+)+def test_parse_filename_rejects_paths_and_invalid_lengths(name: str) -> None:+ """API 文件名独立拒绝两种路径分隔符、盘符、备用数据流和非法长度。"""+ with pytest.raises(ValueError):+ validate_parse_filename(name)+++def test_parse_filename_rejects_all_c0_and_c1_controls() -> None:+ """覆盖 C0、DEL 和 C1 控制字符,避免仅拦截 NUL 或换行。"""+ for codepoint in (*range(0x20), *range(0x7F, 0xA0)):+ with pytest.raises(ValueError):+ validate_parse_filename(f"report{chr(codepoint)}.csv")++def test_office_extensions_includes_legacy_binary_formats() -> None:assert {"doc", "docx", "ppt", "pptx", "xls", "xlsx", "rtf"} <= OFFICE_EXTENSIONSdiff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 9e7fa97c..ac92f8ce 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -8,7 +8,7 @@ import tomllibfrom collections.abc import Callablefrom pathlib import Pathfrom types import ModuleType-from typing import Any+from typing import Any, Literalimport pytestimport typer@@ -24,6 +24,7 @@ from mineru.kit.main import appfrom mineru.kit.vlm_server import mlx_vlm_serverfrom mineru.parser.base import ParseResultfrom mineru.model.registry import MODEL_COMPLETE_MARKER+from mineru.types import Tierfrom mineru.version import __version__runner = CliRunner()@@ -991,6 +992,87 @@ def test_parse_rejects_removed_backend_option(backend: str, tmp_path: Path) -> Nassert "No such option: --backend" in " ".join(result.output.split())+def _csv_input_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch, form: str) -> str:+ """构造相同 CSV 的多种真实路径,从工作子目录调用 CLI。"""+ work = tmp_path / "work"+ (tmp_path / "in").mkdir()+ (work / ".data").mkdir(parents=True)+ for path in (tmp_path / "in/t.csv", work / "t.csv", work / ".data/t.csv", work / ".t.csv"):+ path.write_text("name,age\nAlice,30\n", encoding="utf-8")+ monkeypatch.chdir(work)+ return {+ "relative": "t.csv",+ "parent": "../in/t.csv",+ "hidden-directory": ".data/t.csv",+ "hidden-file": ".t.csv",+ "absolute": str(work / "t.csv"),+ }[form]++[email protected]("form", ["relative", "parent", "hidden-directory", "hidden-file", "absolute"])[email protected]("tier", ["basic", "standard", "advanced"])+def test_parse_rejects_single_csv_quality_tier_before_parsing(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, form: str, tier: str+) -> None:+ """同一 CSV 不因路径写法而绕过单文件质量档位校验。"""+ source = _csv_input_path(tmp_path, monkeypatch, form)++ def unexpected_parse(*args: Any, **kwargs: Any) -> ParseResult:+ """任何到达解析器的调用都说明 CLI 漏掉了前置校验。"""+ pytest.fail("invalid single-file tier must be rejected before parsing")++ monkeypatch.setattr(parse, "local_parse", unexpected_parse)+ output = tmp_path / "result.json"+ result = runner.invoke(app, ["parse", source, "--tier", tier, "-f", "middle_json", "-o", str(output)])++ assert result.exit_code == 1+ assert f"Tier '{tier}' is only supported for PDF and image files" in " ".join(result.output.split())+ assert not output.exists()++[email protected]("form", ["relative", "parent", "hidden-directory", "hidden-file", "absolute"])[email protected]("tier", [None, "flash"])+def test_parse_csv_paths_produce_real_flash_outputs(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, form: str, tier: str | None+) -> None:+ """省略 tier 或显式 Flash 时,各种路径都生成可读的真实 CSV 产物。"""+ source = _csv_input_path(tmp_path, monkeypatch, form)+ output = tmp_path / "result.json"+ arguments = ["parse", source, "-f", "middle_json", "-o", str(output)]+ if tier is not None:+ arguments.extend(["--tier", tier])+ result = runner.invoke(app, arguments)++ assert result.exit_code == 0, result.output+ payload = json.loads(output.read_text(encoding="utf-8"))+ assert payload["extensions"]["mineru"]["tier"] == "flash"+ assert "Alice" in json.dumps(payload["pages"])++[email protected]("directory", [False, True])+def test_parse_csv_batch_paths_normalize_tier_before_parsing(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, directory: bool+) -> None:+ """批量和目录输入仍在 CLI 边界将原生文件归一为 Flash。"""+ _csv_input_path(tmp_path, monkeypatch, "parent")+ original = parse.local_parse+ calls: list[Tier] = []++ def record_parse(+ path: Path, *, tier: Tier, ocr_mode: Literal["auto", "txt", "ocr"], image_analysis: bool, page_range: str+ ) -> ParseResult:+ """记录 CLI 实际传入的档位,并保留真实 CSV 解析。"""+ calls.append(tier)+ return original(path, tier=tier, ocr_mode=ocr_mode, image_analysis=image_analysis, page_range=page_range)++ monkeypatch.setattr(parse, "local_parse", record_parse)+ inputs = [".data"] if directory else ["../in/t.csv", ".t.csv"]+ result = runner.invoke(app, ["parse", *inputs, "--tier", "advanced", "-o", str(tmp_path / "out")])++ assert result.exit_code == 0, result.output+ assert calls == ["flash"] * len(inputs)++def test_parse_rejects_single_office_input_with_quality_tier(monkeypatch: Any, tmp_path: Path) -> None:source = tmp_path / "demo.docx"output = tmp_path / "out.md"diff --git a/tests/unittest/test_task_tiers.py b/tests/unittest/test_task_tiers.pyindex f1e57e60..a4f30617 100644--- a/tests/unittest/test_task_tiers.py+++ b/tests/unittest/test_task_tiers.py@@ -306,6 +306,94 @@ def test_mixed_task_tiers_across_deployments(asyncio.run(scenario())[email protected]("deployment", ["api", "router", "cascade"])+def test_task_filename_rejection_precedes_resource_allocation(tmp_path: Path, deployment: str) -> None:+ """上传和 URL 混合清单中的非法名称在所有部署上均不得分配资源或转发。"""+ sentinel = tmp_path / "outside.csv"+ sentinel.write_bytes(b"SERVER_SENTINEL")+ invalid_names = [+ "",+ ".",+ "..",+ "a" * 1025,+ "../outside.csv",+ str(sentinel),+ r"..\outside.csv",+ r"C:\in\t.csv",+ "C:t.csv",+ r"\\server\share\t.csv",+ "t.csv:stream",+ "t\x00.csv",+ "t\r\n.csv",+ "t\x7f.csv",+ "t\x85.csv",+ ]++ async def scenario() -> None:+ """先提交一个合法条目再附加非法条目,验证整个清单原子拒绝。"""+ async with _deployment(tmp_path, deployment, {"native": ("standard",)}) as (client, _app, apps, submissions):+ for source in ({"bytes": 1}, {"url": "https://source.invalid/t.csv"}):+ for name in invalid_names:+ response = await client.post(+ "/v1/tasks",+ json={"files": [{"file_name": "valid.csv", **source}, {"file_name": name, **source}]},+ )+ assert response.status_code == 400, response.text+ assert response.json()["error"]["code"] == "invalid_request"+ assert response.json()["error"]["param"] == "files.1.file_name"+ assert not submissions+ for service in apps:+ assert not service.state.task_store._records+ if hasattr(service.state, "file_store"):+ assert not service.state.file_store._allocated_file_ids+ else:+ assert not service.state.registry._allocated_file_ids+ assert sentinel.read_bytes() == b"SERVER_SENTINEL"++ asyncio.run(scenario())++[email protected]("deployment", ["api", "router", "cascade"])+def test_native_csv_filename_and_storage_boundary(tmp_path: Path, deployment: str) -> None:+ """隐藏与中文 CSV 使用真实原生解析,源文件名不能替代上传内容或控制落盘位置。"""+ sentinel = tmp_path / ".t.csv"+ server_data = b"name,value\nSERVER_SENTINEL,999\n"+ sentinel.write_bytes(server_data)+ content = b"name,value\nUPLOADED_BYTES,42\n"++ async def scenario() -> None:+ """检查接单档位、各跳名称、真实下载产物与受管存储目录。"""+ async with _deployment(tmp_path, deployment, {"native": ("standard",)}) as (client, app, apps, submissions):+ inputs = [(name, content) for name in (".t.csv", "报告 2026.CSV", "report..csv", "%2e%2e%2ft.csv")]+ response = await client.post("/v1/tasks", json=_request_body(inputs, {"tier": "advanced"}))+ assert response.status_code == 202, response.text+ task = response.json()+ assert app.state.task_store._records[task["task_id"]].options.tier == "flash"+ result = await _complete(client, task, inputs)+ assert result["status"] == "completed", result+ assert [item["file_name"] for item in result["files"]] == [name for name, _data in inputs]+ for item in result["files"]:+ assert item["parse"]["tier"] == "flash"+ archive = await _archive(client, item)+ assert b"UPLOADED_BYTES" in archive["markdown.md"]+ assert b"SERVER_SENTINEL" not in archive["markdown.md"]+ middle = json.loads(archive["middle_json.json"])+ assert middle["extensions"]["mineru"]["tier"] == "flash"+ assert all("tier" not in body for _host, body in submissions)+ for service in apps:+ if hasattr(service.state, "file_store"):+ store = service.state.file_store+ for record in store._files.values():+ assert record.sha256sum is not None+ assert store._blob_abs(record.sha256sum).resolve().is_relative_to(store._root.resolve())+ else:+ store = service.state.source_store+ assert all(source.path.resolve().is_relative_to(store._root.resolve()) for source in store._files.values())+ assert sentinel.read_bytes() == server_data++ asyncio.run(scenario())++@pytest.mark.parametrize("deployment", ["api", "router", "cascade"])def test_native_only_task_ignores_unavailable_explicit_tier(tmp_path: Path, deployment: str) -> None:"""纯原生文档携带未开放的 advanced 时仍按 flash 完成,并保存归一化选项。"""