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
feat: implement validation for image sidecar paths and enhance export cache management
myhlolifd83c9a787f7
diff --git a/mineru/doclib/services/parse_svc.py b/mineru/doclib/services/parse_svc.pyindex 8d4a5a1a..a6ff078f 100644--- a/mineru/doclib/services/parse_svc.py+++ b/mineru/doclib/services/parse_svc.py@@ -1220,6 +1220,7 @@ def _remap_api_result_pages_to_page_range(result: ParseResult, page_range: str))for page, page_no in zip(result.pages, requested_page_numbers, strict=True):page.page_idx = page_no - 1+ result.refresh_export_cache(preserve_images=True)def _parse_coverage(request_page_range: str, rows: list[ParseRow]) -> dict:diff --git a/mineru/kit/common.py b/mineru/kit/common.pyindex f2134146..6d6d1c52 100644--- a/mineru/kit/common.py+++ b/mineru/kit/common.py@@ -5,12 +5,13 @@ from __future__ import annotationsimport jsonimport osimport zipfile-from pathlib import Path, PureWindowsPath+from pathlib import Pathfrom typing import Literalfrom ..data.data_reader_writer.filebase import FileBasedDataWriterfrom ..parser.base import ParseResultfrom ..types import Tier+from ..utils.image_payload import validate_image_sidecar_pathSupportedBundle = Literal["pipeline", "vlm", "all"]KitFormat = Literal["markdown", "middle_json", "zip"]@@ -174,21 +175,9 @@ def _write_utf8_text(path: Path, content: str) -> None:def _resolve_safe_sidecar_path(output_dir: Path, image_path: str) -> str:"""校验图片 sidecar 路径必须落在输出目录内,并返回安全的相对路径。"""- posix_path = Path(image_path)- windows_path = PureWindowsPath(image_path)- if (- not image_path- or posix_path.is_absolute()- or windows_path.is_absolute()- or windows_path.drive- or windows_path.root- or ".." in posix_path.parts- or ".." in windows_path.parts- ):- raise ValueError(f"Unsafe image sidecar path: {image_path}")-+ safe_image_path = validate_image_sidecar_path(image_path)output_root = output_dir.resolve()- target_path = (output_root / posix_path).resolve()+ target_path = (output_root / safe_image_path).resolve()try:target_path.relative_to(output_root)except ValueError as exc:diff --git a/mineru/parser/api_client.py b/mineru/parser/api_client.pyindex c843f5e1..42e4e56a 100644--- a/mineru/parser/api_client.py+++ b/mineru/parser/api_client.py@@ -19,6 +19,7 @@ from typing import Anyimport httpxfrom ..types import PageInfo, Tier+from ..utils.image_payload import validate_image_sidecar_pathfrom .base import DocumentParser, ParseResult@@ -340,7 +341,8 @@ def _download_image_sidecars(parser: MinerUApiParser, outputs: dict[str, Any]) -img_path = ref.get("path")if not isinstance(img_path, str) or not img_path:continue- images[img_path] = _download_bytes(parser, ref)+ safe_img_path = validate_image_sidecar_path(img_path)+ images[safe_img_path] = _download_bytes(parser, ref)return images@@ -356,7 +358,8 @@ async def _async_download_image_sidecars(parser: MinerUApiParser, outputs: dict[img_path = ref.get("path")if not isinstance(img_path, str) or not img_path:continue- images[img_path] = await _async_download_bytes(parser, ref)+ safe_img_path = validate_image_sidecar_path(img_path)+ images[safe_img_path] = await _async_download_bytes(parser, ref)return imagesdiff --git a/mineru/parser/base.py b/mineru/parser/base.pyindex e57d314f..1ec92485 100644--- a/mineru/parser/base.py+++ b/mineru/parser/base.py@@ -178,6 +178,14 @@ class ParseResult:self._export_pages_cache = deepcopy(self.pages)self._images_cache = dict(images)+ def refresh_export_cache(self, *, preserve_images: bool = False) -> None:+ """调用方原地修改 pages 后刷新导出缓存;必要时保留已绑定的 sidecar 字节。"""+ if preserve_images and self._images_cache is not None:+ self._export_pages_cache = deepcopy(self.pages)+ return+ self._export_pages_cache = None+ self._images_cache = None+def export_pages(self) -> list[PageInfo]:"""返回可导出的页面副本:清理 base64,并把内联图片替换为本地路径。"""export_pages, _ = self._ensure_export_cache()diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.pyindex 9bafc3e9..bd219d9a 100644--- a/mineru/utils/image_payload.py+++ b/mineru/utils/image_payload.py@@ -2,6 +2,7 @@from __future__ import annotationsimport base64+from pathlib import Path, PureWindowsPathimport refrom .hash_utils import str_sha256@@ -50,6 +51,23 @@ def image_path_from_key(path_key: str, image_format: str = "JPEG") -> str:return f"{str_sha256(path_key)}.{ext}"+def validate_image_sidecar_path(image_path: str) -> str:+ """校验图片 sidecar 路径只能是安全的相对子路径,并返回规范化 POSIX 路径。"""+ posix_path = Path(image_path)+ windows_path = PureWindowsPath(image_path)+ if (+ not image_path+ or posix_path.is_absolute()+ or windows_path.is_absolute()+ or windows_path.drive+ or windows_path.root+ or ".." in posix_path.parts+ or ".." in windows_path.parts+ ):+ raise ValueError(f"Unsafe image sidecar path: {image_path}")+ return posix_path.as_posix()++def collect_image_data_uri_bytes(markup: str, images: dict[str, bytes]) -> None:"""只收集文本或 HTML 中的 data URI 图片字节,不修改原始内容。"""if not markup or "data:image/" not in markup:diff --git a/tests/unittest/test_doclib_cache_semantics.py b/tests/unittest/test_doclib_cache_semantics.pyindex cbb60b6e..c06653be 100644--- a/tests/unittest/test_doclib_cache_semantics.py+++ b/tests/unittest/test_doclib_cache_semantics.py@@ -497,6 +497,18 @@ def test_remap_api_result_pages_to_non_contiguous_page_range() -> None:assert [page.page_idx for page in result.pages] == [10, 12, 13]+def test_remap_api_result_pages_refreshes_attached_export_cache() -> None:+ from mineru.doclib.services.parse_svc import _remap_api_result_pages_to_page_range++ result = ParseResult.from_dict({"pages": [{"page_idx": 0}]})+ result.attach_export_images({"images/figure.png": b"figure-bytes"})++ _remap_api_result_pages_to_page_range(result, "5")++ assert result.to_export_dict()["pages"][0]["page_idx"] == 4+ assert result.images() == {"images/figure.png": b"figure-bytes"}++def test_remap_api_result_pages_rejects_count_mismatch() -> None:from mineru.doclib.services.parse_svc import ParseFailure, _remap_api_result_pages_to_page_rangediff --git a/tests/unittest/test_kit_commands.py b/tests/unittest/test_kit_commands.pyindex 4e1be39a..e301d222 100644--- a/tests/unittest/test_kit_commands.py+++ b/tests/unittest/test_kit_commands.py@@ -17,6 +17,11 @@ from mineru.kit.main import apprunner = CliRunner()+def _assert_unsafe_sidecar_error(output: str) -> None:+ """归一化 Typer/Click 自动换行后的错误输出,再匹配 sidecar 安全错误。"""+ assert "Unsafe image sidecar path" in " ".join(output.split())++def test_kit_root_and_models_help() -> None:result = runner.invoke(app, ["--help"])models_result = runner.invoke(app, ["models", "--help"])@@ -399,7 +404,7 @@ def test_parse_single_file_middle_json_rejects_parent_sidecar_paths()assert result.exit_code == 1- assert "Unsafe image sidecar path" in result.output+ _assert_unsafe_sidecar_error(result.output)assert not escaped.exists()@@ -430,7 +435,7 @@ def test_parse_single_file_middle_json_rejects_absolute_sidecar_paths()assert result.exit_code == 1- assert "Unsafe image sidecar path" in result.output+ _assert_unsafe_sidecar_error(result.output)assert not absolute.exists()@@ -460,7 +465,7 @@ def test_parse_single_file_middle_json_rejects_windows_rooted_sidecar_paths()assert result.exit_code == 1- assert "Unsafe image sidecar path" in result.output+ _assert_unsafe_sidecar_error(result.output)assert not (tmp_path / "\\escape.png").exists()@@ -515,7 +520,7 @@ def test_parse_single_file_markdown_rejects_unsafe_sidecar_paths(result = runner.invoke(app, ["parse", str(source), "-o", str(output)])assert result.exit_code == 1- assert "Unsafe image sidecar path" in result.output+ _assert_unsafe_sidecar_error(result.output)assert not escaped.exists()diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex 4ef0ebe2..1990af11 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -90,6 +90,67 @@ def test_api_client_downloads_image_sidecars_and_preserves_pdf_mapping(monkeypatassert result.images() == {"images/chart.png": b"chart-bytes"}[email protected]("image_path", ["../escape.png", "/tmp/escape.png", "\\escape.png", "C:\\escape.png"])+def test_api_client_rejects_unsafe_image_sidecar_paths(+ monkeypatch: pytest.MonkeyPatch,+ image_path: str,+) -> None:+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="standard")+ middle_json = {"schema_version": "1.0.0", "pages": [{"page_idx": 0}]}+ image_ref = {"path": image_path, "file_id": "file-image", "bytes": 11}++ monkeypatch.setattr(api_client, "_download_json", lambda _parser, _outputs: middle_json)++ def _fail_download(*_args: object, **_kwargs: object) -> bytes:+ """危险 sidecar 路径必须在下载图片字节前被拒绝。"""+ raise AssertionError("unsafe sidecar path should be rejected before download")++ monkeypatch.setattr(api_client, "_download_bytes", _fail_download)++ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ _parse_result_from_job(+ {+ "job_id": "job_1",+ "status": "completed",+ "files": [{"output_files": {"middle_json": {"file_id": "file-middle", "bytes": 10}, "images": [image_ref]}}],+ },+ "demo.pdf",+ parser,+ )+++def test_async_api_client_rejects_unsafe_image_sidecar_paths(monkeypatch: pytest.MonkeyPatch) -> None:+ parser = MinerUApiParser(api_url="http://localhost:8000", tier="standard")+ middle_json = {"schema_version": "1.0.0", "pages": [{"page_idx": 0}]}+ image_ref = {"path": "../escape.png", "file_id": "file-image", "bytes": 11}++ async def _download_json(*_args: object, **_kwargs: object) -> dict[str, object]:+ """返回最小 middle_json,聚焦验证 sidecar 路径校验。"""+ return middle_json++ async def _fail_download(*_args: object, **_kwargs: object) -> bytes:+ """异步路径同样必须在下载图片字节前拒绝危险 sidecar。"""+ raise AssertionError("unsafe sidecar path should be rejected before download")++ monkeypatch.setattr(api_client, "_async_download_json", _download_json)+ monkeypatch.setattr(api_client, "_async_download_bytes", _fail_download)++ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ asyncio.run(+ api_client._async_parse_result_from_job(+ {+ "job_id": "job_1",+ "status": "completed",+ "files": [+ {"output_files": {"middle_json": {"file_id": "file-middle", "bytes": 10}, "images": [image_ref]}}+ ],+ },+ "demo.pdf",+ parser,+ )+ )++def test_api_client_omits_tier_when_unspecified(tmp_path: Path) -> None:pdf = tmp_path / "demo.pdf"pdf.write_bytes(b"%PDF-1.7\n")