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
Harden image payload cache paths
myhloli715f173d450a
diff --git a/mineru/utils/image_payload.py b/mineru/utils/image_payload.pyindex f8fc4acd..7302ef3a 100644--- a/mineru/utils/image_payload.py+++ b/mineru/utils/image_payload.py@@ -239,7 +239,9 @@ class ImagePayloadCache:"""保存运行时图片载荷,public middle_json 只通过 image_path 引用图片。"""def __init__(self, images: dict[str, bytes] | None = None) -> None:- self._images: dict[str, bytes] = dict(images or {})+ self._images: dict[str, bytes] = {}+ if images:+ self.update(images)def register_bytes(self,@@ -258,6 +260,7 @@ class ImagePayloadCache:ext = normalize_image_extension(image_format)payload_key = base64.b64encode(img_bytes).decode("ascii")img_path = f"{hashlib.sha256(payload_key.encode('utf-8')).hexdigest()}.{ext}"+ img_path = validate_image_sidecar_path(img_path)self._images[img_path] = img_bytesreturn img_path@@ -273,14 +276,20 @@ class ImagePayloadCache:def validate_image_sidecar_path(image_path: str) -> str:"""校验图片 sidecar 路径只能是安全的相对子路径,并返回规范化 POSIX 路径。"""- posix_path = Path(image_path)- windows_path = PureWindowsPath(image_path)if (not image_pathor image_path == "."- or "\x00" in image_pathor "\\" in image_path- or posix_path.is_absolute()+ or any(ord(char) < 0x20 or ord(char) == 0x7F for char in image_path)+ ):+ raise ValueError(f"Unsafe image sidecar path: {image_path}")+ parsed = urlsplit(image_path)+ if parsed.scheme or parsed.netloc:+ raise ValueError(f"Unsafe image sidecar path: {image_path}")+ posix_path = Path(image_path)+ windows_path = PureWindowsPath(image_path)+ if (+ posix_path.is_absolute()or windows_path.is_absolute()or windows_path.driveor windows_path.rootdiff --git a/tests/unittest/test_image_payload_cache.py b/tests/unittest/test_image_payload_cache.pynew file mode 100644index 00000000..e03e2ed8--- /dev/null+++ b/tests/unittest/test_image_payload_cache.py@@ -0,0 +1,109 @@+from __future__ import annotations++import pytest++from mineru.utils.image_payload import ImagePayloadCache, validate_image_sidecar_path+++ ("image_path", "expected"),+ [+ ("chart.png", "chart.png"),+ ("images/chart.png", "images/chart.png"),+ ("images/./chart.png", "images/chart.png"),+ ],+)+def test_image_payload_cache_registers_safe_explicit_paths(image_path: str, expected: str) -> None:+ """验证显式图片路径进入缓存时会被统一校验并规范化。"""+ cache = ImagePayloadCache()++ registered = cache.register_bytes(b"image-bytes", "png", image_path=image_path)++ assert registered == expected+ assert cache.images() == {expected: b"image-bytes"}+++def test_image_payload_cache_validates_constructor_and_update_paths() -> None:+ """验证构造函数和 update 不再绕过 sidecar 路径校验。"""+ cache = ImagePayloadCache({"images/./constructor.png": b"constructor"})++ cache.update({"updated.png": b"updated"})++ assert cache.images() == {+ "images/constructor.png": b"constructor",+ "updated.png": b"updated",+ }+++def test_image_payload_cache_validates_path_key_and_generated_hash_paths() -> None:+ """验证 path_key 和哈希路径也会经过统一校验。"""+ cache = ImagePayloadCache()++ keyed_path = cache.register_bytes(b"keyed", "jpeg", path_key="images/page_0")+ hashed_path = cache.register_bytes(b"hashed", "png")++ assert keyed_path == "images/page_0.jpg"+ assert hashed_path.endswith(".png")+ assert "/" not in hashed_path+ assert cache.images()[keyed_path] == b"keyed"+ assert cache.images()[hashed_path] == b"hashed"+++ "image_path",+ [+ "../escape.png",+ "/tmp/escape.png",+ "C:\\escape.png",+ "\\escape.png",+ "data:image/png;base64,AAAA",+ "http://example.test/escape.png",+ "//example.test/escape.png",+ "images/control\nname.png",+ "images/control\x00name.png",+ ],+)+def test_image_payload_cache_rejects_unsafe_explicit_paths(image_path: str) -> None:+ """验证不安全显式路径不能进入图片缓存。"""+ cache = ImagePayloadCache()++ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ cache.register_bytes(b"image-bytes", "png", image_path=image_path)+++ "image_path",+ [+ "../constructor.png",+ "http://example.test/constructor.png",+ ],+)+def test_image_payload_cache_rejects_unsafe_constructor_and_update_paths(image_path: str) -> None:+ """验证构造函数和 update 对不安全路径采用 fail-fast。"""+ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ ImagePayloadCache({image_path: b"constructor"})++ cache = ImagePayloadCache()+ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ cache.update({image_path: b"updated"})++[email protected]("path_key", ["../escape", "http://example.test/escape"])+def test_image_payload_cache_rejects_unsafe_path_keys(path_key: str) -> None:+ """验证由 path_key 派生出的不安全路径也会被拒绝。"""+ cache = ImagePayloadCache()++ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ cache.register_bytes(b"image-bytes", "png", path_key=path_key)+++ ("image_path", "expected"),+ [+ ("chart.png", "chart.png"),+ ("images/./chart.png", "images/chart.png"),+ ],+)+def test_validate_image_sidecar_path_returns_normalized_posix_path(image_path: str, expected: str) -> None:+ """验证底层路径校验器返回规范化 POSIX 相对路径。"""+ assert validate_image_sidecar_path(image_path) == expecteddiff --git a/tests/unittest/test_parse_result_contract.py b/tests/unittest/test_parse_result_contract.pyindex 7f433e5e..094e84a8 100644--- a/tests/unittest/test_parse_result_contract.py+++ b/tests/unittest/test_parse_result_contract.py@@ -234,3 +234,20 @@ def test_parse_result_export_pages_returns_defensive_copy() -> None:assert image_path in second_contentassert result.images() == {image_path: b"defensive-table-image"}assert "mutated by caller" not in exported_json+++def test_parse_result_attach_export_images_rejects_unsafe_paths() -> None:+ """验证远端 sidecar 绑定入口继承 ImagePayloadCache 的路径安全边界。"""+ result = ParseResult(+ middle_json=MiddleJson(+ pages=[PageInfo(page_idx=0)],+ is_full_document=True,+ file_suffix="pdf",+ effort="medium",+ parse_mode="txt",+ mineru_version=__version__,+ )+ )++ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ result.attach_export_images({"../escape.png": b"bad-image"})diff --git a/tests/unittest/test_parser_api_contract.py b/tests/unittest/test_parser_api_contract.pyindex ff5e2fff..ed9ddc98 100644--- a/tests/unittest/test_parser_api_contract.py+++ b/tests/unittest/test_parser_api_contract.py@@ -2094,17 +2094,28 @@ def test_api_server_zip_includes_model_output_when_parse_result_has_it(assert "\n " in model_output_text+def test_parse_result_rejects_unsafe_image_cache_path() -> None:+ """验证 ParseResult 绑定外部图片缓存时立即拒绝不安全路径。"""+ with pytest.raises(ValueError, match="Unsafe image sidecar path"):+ ParseResult(+ middle_json=_full_middle_json(PageInfo(page_idx=0)),+ _image_cache={"../escape.png": b"bad-image"},+ )++def test_api_server_zip_rejects_unsafe_image_sidecar_path(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,) -> None:- parse_result = ParseResult(- middle_json=_full_middle_json(PageInfo(page_idx=0)),- _image_cache={"../escape.png": b"bad-image"},- )+ class _UnsafeResult:+ """模拟非标准解析结果,验证 ZIP writer 的下游路径防护仍生效。"""- async def fake_parse_async(*args: object, **kwargs: object) -> ParseResult:- return parse_result+ def save(self, writer: Any) -> None:+ """尝试写出不安全 sidecar 路径。"""+ writer.write("../escape.png", b"bad-image")++ async def fake_parse_async(*args: object, **kwargs: object) -> Any:+ return _UnsafeResult()monkeypatch.setattr("mineru.parser.api_server.parse_async", fake_parse_async)file_store = FileStore(tmp_path / "api-files")