From 809c44f29bc05eb747ee5334900bd1a23b29ee51 Mon Sep 17 00:00:00 2001 From: Muhammed Salim K T <60375799+salimkt@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:46:27 +0530 Subject: [PATCH] fix(mcp): classify existing absolute paths before Base64 (#18412) Absolute paths made only of Base64-alphabet characters (e.g. /etc/passwd, /usr/bin/env) were classified as Base64 and then rejected or silently decoded into garbage. - classify_input() now returns ABSOLUTE_PATH for an existing absolute path before trying the Base64 check. - is_base64() requires a length that is a multiple of 4 and a successful strict decode. - infer_file_type_from_bytes() returns None for unidentifiable bytes instead of leaking puremagic.PureError. - The unsupported-content error hints that a '/'-prefixed input may be a missing file. Co-Authored-By: Claude Opus 5.5 --- .../inference/shared/input_contract.py | 15 +++- mcp_server/paddleocr_mcp/utils.py | 14 ++- tests/unit/test_mcp_input_contract.py | 90 +++++++++++++++++++ 3 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 tests/unit/test_mcp_input_contract.py diff --git a/mcp_server/paddleocr_mcp/inference/shared/input_contract.py b/mcp_server/paddleocr_mcp/inference/shared/input_contract.py index 58b2bd5443b..bd143e98c02 100644 --- a/mcp_server/paddleocr_mcp/inference/shared/input_contract.py +++ b/mcp_server/paddleocr_mcp/inference/shared/input_contract.py @@ -16,6 +16,7 @@ from __future__ import annotations +import os import tempfile from contextlib import contextmanager from enum import Enum @@ -75,6 +76,11 @@ def looks_like_file_path(value: str) -> bool: return Path(value).suffix.lower() in _INPUT_EXTENSIONS +def _is_existing_absolute_path(value: str) -> bool: + path = os.path.expanduser(value) + return os.path.isabs(path) and os.path.exists(path) + + def classify_input(value: str) -> InputKind: if is_url(value): return InputKind.URL @@ -83,6 +89,10 @@ def classify_input(value: str) -> InputKind: if not is_base64(payload): raise ValueError("Invalid data URL: payload is not valid Base64.") return InputKind.DATA_URL + # Base64 and POSIX paths share the "/" character, so an existing absolute + # path such as "/etc/passwd" may also pass the Base64 check. + if _is_existing_absolute_path(value): + return InputKind.ABSOLUTE_PATH if is_base64(value): return InputKind.BASE64 if looks_like_file_path(value): @@ -121,9 +131,12 @@ def validate_external_contract(input_data: str) -> InputKind: data = decode_base64_payload(payload) file_type = infer_file_type_from_bytes(data) if file_type not in ("image", "pdf"): + hint = "" + if kind is InputKind.BASE64 and value.startswith("/"): + hint = f" If {value!r} is a file path, the file does not exist." raise ValueError( "Unsupported Base64 content type. Only image and PDF inputs are " - "supported." + f"supported.{hint}" ) return kind diff --git a/mcp_server/paddleocr_mcp/utils.py b/mcp_server/paddleocr_mcp/utils.py index 619e8a77df3..3c1f658b05f 100644 --- a/mcp_server/paddleocr_mcp/utils.py +++ b/mcp_server/paddleocr_mcp/utils.py @@ -17,6 +17,7 @@ from __future__ import annotations import base64 +import binascii import re from typing import Optional from urllib.parse import urlparse @@ -32,7 +33,13 @@ def is_url(value: str) -> bool: def is_base64(value: str) -> bool: pattern = r"^[A-Za-z0-9+/]+={0,2}$" - return bool(re.fullmatch(pattern, value)) + if len(value) % 4 != 0 or not re.fullmatch(pattern, value): + return False + try: + base64.b64decode(value, validate=True) + except (binascii.Error, ValueError): + return False + return True def extract_base64_payload(input_data: str) -> str: @@ -56,7 +63,10 @@ def decode_base64_payload(payload: str) -> bytes: def infer_file_type_from_bytes(data: bytes) -> Optional[str]: import puremagic - mime = puremagic.from_string(data, mime=True) + try: + mime = puremagic.from_string(data, mime=True) + except puremagic.PureError: + return None if mime.startswith("image/"): return "image" if mime == "application/pdf": diff --git a/tests/unit/test_mcp_input_contract.py b/tests/unit/test_mcp_input_contract.py new file mode 100644 index 00000000000..d63729a6450 --- /dev/null +++ b/tests/unit/test_mcp_input_contract.py @@ -0,0 +1,90 @@ +# Copyright (c) 2026 PaddlePaddle Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for MCP input classification of file paths vs. Base64 (issue #18412).""" + +import base64 +import io +import os + +import pytest + +pytest.importorskip("fastmcp") +pytest.importorskip("puremagic") + +from paddleocr_mcp.inference.shared.input_contract import ( # noqa: E402 + InputKind, + classify_input, + validate_external_contract, +) +from paddleocr_mcp.utils import is_base64 # noqa: E402 + +pytestmark = pytest.mark.py38_incompatible + + +def _png_base64() -> str: + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (8, 8)).save(buf, format="PNG") + return base64.b64encode(buf.getvalue()).decode() + + +@pytest.mark.parametrize( + "value, expected", + [ + ("aGVsbG8=", True), + ("aGVsbG8gd29ybGQ=", True), + ("/9j/4AAQ", True), # JPEG prefix starts with "/" + ("aGVsbG8", False), # length not a multiple of 4 + ("/etc/passwd", False), # length 11 + ("aGVs=G8=", False), # padding in the middle + ("aGVsbG8*", False), # character outside the alphabet + ("", False), + ], +) +def test_is_base64(value, expected): + assert is_base64(value) is expected + + +# Existing absolute paths made only of Base64-alphabet characters. +# "/usr/bin/env" is 12 characters long, so it is also decodable Base64. +@pytest.mark.parametrize("path", ["/etc/passwd", "/usr/bin/env", "/bin/sh"]) +def test_existing_alphabet_only_path_is_classified_as_path(path): + if not os.path.exists(path): + pytest.skip(f"{path} does not exist on this platform") + assert classify_input(path) is InputKind.ABSOLUTE_PATH + assert validate_external_contract(path) is InputKind.ABSOLUTE_PATH + + +def test_raw_base64_is_still_classified_as_base64(): + value = _png_base64() + assert classify_input(value) is InputKind.BASE64 + assert validate_external_contract(value) is InputKind.BASE64 + + +def test_base64_starting_with_slash_is_still_base64(): + # JPEG data encodes to a string starting with "/9j/", which also looks + # like an absolute path; it must not be treated as one unless it exists. + value = base64.b64encode(b"\xff\xd8\xff\xe0" + b"\x00" * 32).decode() + assert value.startswith("/9j/") + assert classify_input(value) is InputKind.BASE64 + + +def test_missing_alphabet_only_path_error_mentions_path(): + # 32 Base64-alphabet characters: decodable, but not an image or PDF. + missing = "/nonexistent0dir/uploads/receipt" + assert not os.path.exists(missing) + with pytest.raises(ValueError, match="the file does not exist"): + validate_external_contract(missing)