fix(media): accept data URLs that capitalize the base64 token (#6464)
Co-authored-by: chengyongru <chengyongru.ai@gmail.com>
This commit is contained in:
1 parent
9b3af7b66c
commit
acae3e6a65
3 files changed
+99
-42
No files matched your search
@@ -7,7 +7,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import base64
|
import base64
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import re
|
|
||||||
import uuid
|
import uuid
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -16,7 +15,6 @@ from nanobot.utils.helpers import safe_filename
|
|||||||
DEFAULT_MAX_BYTES = 10 * 1024 * 1024
|
DEFAULT_MAX_BYTES = 10 * 1024 * 1024
|
||||||
MAX_FILE_SIZE = DEFAULT_MAX_BYTES
|
MAX_FILE_SIZE = DEFAULT_MAX_BYTES
|
||||||
|
|
||||||
_DATA_URL_RE = re.compile(r"^data:([^;,]+)(?:;[^,]*)*;base64,(.+)$", re.DOTALL)
|
|
||||||
_MIME_EXTENSION_OVERRIDES = {
|
_MIME_EXTENSION_OVERRIDES = {
|
||||||
# Python's ``mimetypes`` maps browser-recorded audio/webm to ``.weba`` and
|
# Python's ``mimetypes`` maps browser-recorded audio/webm to ``.weba`` and
|
||||||
# audio/ogg to ``.oga`` on macOS. Some transcription APIs validate by the
|
# audio/ogg to ``.oga`` on macOS. Some transcription APIs validate by the
|
||||||
@@ -69,10 +67,14 @@ def save_base64_data_url(
|
|||||||
base64 payload itself is malformed. Raises :class:`FileSizeExceeded`
|
base64 payload itself is malformed. Raises :class:`FileSizeExceeded`
|
||||||
when the decoded payload is larger than ``max_bytes`` (default 10 MB).
|
when the decoded payload is larger than ``max_bytes`` (default 10 MB).
|
||||||
"""
|
"""
|
||||||
m = _DATA_URL_RE.match(data_url)
|
# Parse delimiters directly so malformed MIME parameters cannot trigger regex backtracking.
|
||||||
if not m:
|
header, separator, b64_payload = data_url.partition(",")
|
||||||
|
if not separator or header[:5].lower() != "data:" or header[-7:].lower() != ";base64":
|
||||||
return None
|
return None
|
||||||
mime_type, b64_payload = m.group(1).strip().lower(), m.group(2)
|
mime_type = header[5:-7].partition(";")[0]
|
||||||
|
if not mime_type:
|
||||||
|
return None
|
||||||
|
mime_type = mime_type.strip().lower()
|
||||||
try:
|
try:
|
||||||
raw = base64.b64decode(b64_payload, validate=True)
|
raw = base64.b64decode(b64_payload, validate=True)
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
from io import BytesIO
|
from io import BytesIO
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
@@ -128,6 +130,33 @@ def test_parse_json_content_extracts_text_and_media(tmp_path) -> None:
|
|||||||
os.chdir(original_cwd)
|
os.chdir(original_cwd)
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_json_content_rejects_malformed_parameter_header_without_stalling(tmp_path) -> None:
|
||||||
|
# Isolate the parser so a backtracking regression cannot hang the test runner.
|
||||||
|
code = """
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from nanobot.api.server import _parse_json_content
|
||||||
|
|
||||||
|
media_dir = Path(sys.argv[1])
|
||||||
|
url = "data:image/png" + ";a" * 128 + ",eA=="
|
||||||
|
body = {"messages": [{"role": "user", "content": [
|
||||||
|
{"type": "text", "text": "describe this"},
|
||||||
|
{"type": "image_url", "image_url": {"url": url}},
|
||||||
|
]}]}
|
||||||
|
with patch("nanobot.api.server.get_media_dir", return_value=media_dir):
|
||||||
|
assert _parse_json_content(body) == ("describe this", [])
|
||||||
|
assert list(media_dir.iterdir()) == []
|
||||||
|
"""
|
||||||
|
result = subprocess.run(
|
||||||
|
[sys.executable, "-c", code, str(tmp_path)],
|
||||||
|
cwd=Path(__file__).resolve().parents[1],
|
||||||
|
capture_output=True, text=True, timeout=10,
|
||||||
|
)
|
||||||
|
assert result.returncode == 0, result.stderr
|
||||||
|
|
||||||
|
|
||||||
def test_parse_json_content_plain_text_only() -> None:
|
def test_parse_json_content_plain_text_only() -> None:
|
||||||
"""Plain text string content returns no media."""
|
"""Plain text string content returns no media."""
|
||||||
body = {"messages": [{"role": "user", "content": "hello"}]}
|
body = {"messages": [{"role": "user", "content": "hello"}]}
|
||||||
@@ -378,40 +407,40 @@ async def test_plain_text_backward_compat(aiohttp_client, mock_agent) -> None:
|
|||||||
|
|
||||||
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_json_base64_image_upload(aiohttp_client, mock_agent, tmp_path) -> None:
|
@pytest.mark.parametrize("marker", ["base64", "BASE64", "Base64"])
|
||||||
|
async def test_json_base64_image_upload(
|
||||||
|
aiohttp_client, mock_agent, tmp_path, monkeypatch, marker: str,
|
||||||
|
) -> None:
|
||||||
"""JSON request with base64 data URL saves file and passes path."""
|
"""JSON request with base64 data URL saves file and passes path."""
|
||||||
import os
|
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: tmp_path)
|
||||||
original_cwd = os.getcwd()
|
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
||||||
os.chdir(tmp_path)
|
client = await aiohttp_client(app)
|
||||||
|
|
||||||
try:
|
# Use valid base64 for a tiny PNG (1x1 transparent pixel)
|
||||||
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
|
tiny_png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
|
||||||
client = await aiohttp_client(app)
|
|
||||||
|
|
||||||
# Use valid base64 for a tiny PNG (1x1 transparent pixel)
|
resp = await client.post(
|
||||||
tiny_png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
|
"/v1/chat/completions",
|
||||||
|
headers=AUTH_HEADERS,
|
||||||
resp = await client.post(
|
json={
|
||||||
"/v1/chat/completions",
|
"messages": [
|
||||||
headers=AUTH_HEADERS,
|
{
|
||||||
json={
|
"role": "user",
|
||||||
"messages": [
|
"content": [
|
||||||
{
|
{"type": "text", "text": "what is this"},
|
||||||
"role": "user",
|
{"type": "image_url", "image_url": {"url": f"data:image/png;{marker},{tiny_png_b64}"}},
|
||||||
"content": [
|
],
|
||||||
{"type": "text", "text": "what is this"},
|
}
|
||||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{tiny_png_b64}"}},
|
]
|
||||||
],
|
},
|
||||||
}
|
)
|
||||||
]
|
assert resp.status == 200
|
||||||
},
|
mock_agent.process_direct.assert_awaited_once()
|
||||||
)
|
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
||||||
assert resp.status == 200
|
assert call_kwargs["content"] == "what is this"
|
||||||
call_kwargs = mock_agent.process_direct.call_args.kwargs
|
saved, = call_kwargs["media"]
|
||||||
assert call_kwargs["content"] == "what is this"
|
assert Path(saved).parent == tmp_path
|
||||||
assert len(call_kwargs.get("media", [])) == 1
|
assert Path(saved).read_bytes() == base64.b64decode(tiny_png_b64)
|
||||||
finally:
|
|
||||||
os.chdir(original_cwd)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -26,8 +26,12 @@ def test_saves_png_with_correct_extension(tmp_path) -> None:
|
|||||||
assert (tmp_path / result.split("/")[-1]).read_bytes() == b"fake png"
|
assert (tmp_path / result.split("/")[-1]).read_bytes() == b"fake png"
|
||||||
|
|
||||||
|
|
||||||
def test_saves_data_url_with_mime_parameters(tmp_path) -> None:
|
@pytest.mark.parametrize("mime", [
|
||||||
result = save_base64_data_url(_data_url(b"voice", mime="audio/webm;codecs=opus"), tmp_path)
|
"audio/webm;codecs=opus",
|
||||||
|
"audio/webm;codecs=opus;name=voice.webm",
|
||||||
|
])
|
||||||
|
def test_saves_data_url_with_mime_parameters(tmp_path, mime: str) -> None:
|
||||||
|
result = save_base64_data_url(_data_url(b"voice", mime=mime), tmp_path)
|
||||||
assert result is not None
|
assert result is not None
|
||||||
assert result.endswith(".webm")
|
assert result.endswith(".webm")
|
||||||
assert (tmp_path / result.split("/")[-1]).read_bytes() == b"voice"
|
assert (tmp_path / result.split("/")[-1]).read_bytes() == b"voice"
|
||||||
@@ -93,13 +97,35 @@ def test_document_filename_cannot_escape_media_dir(tmp_path) -> None:
|
|||||||
assert saved.read_bytes() == b"%PDF-1.4"
|
assert saved.read_bytes() == b"%PDF-1.4"
|
||||||
|
|
||||||
|
|
||||||
def test_returns_none_for_malformed_data_url(tmp_path) -> None:
|
@pytest.mark.parametrize("data_url", [
|
||||||
assert save_base64_data_url("not-a-data-url", tmp_path) is None
|
"not-a-data-url",
|
||||||
|
"data:;base64,eA==",
|
||||||
|
"data:image/png,eA==",
|
||||||
|
"data:image/png;base64=1,eA==",
|
||||||
|
"data:image/png;base64",
|
||||||
|
])
|
||||||
|
def test_returns_none_for_malformed_data_url(tmp_path, data_url: str) -> None:
|
||||||
|
assert save_base64_data_url(data_url, tmp_path) is None
|
||||||
|
assert list(tmp_path.iterdir()) == []
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("marker", ["BASE64", "Base64"])
|
||||||
|
def test_saves_data_url_when_base64_marker_case_varies(tmp_path: Path, marker: str) -> None:
|
||||||
|
"""RFC 2397 treats the base64 token as case-insensitive."""
|
||||||
|
payload = b"hello"
|
||||||
|
encoded = base64.b64encode(payload).decode()
|
||||||
|
result = save_base64_data_url(
|
||||||
|
f"data:text/plain;charset=utf-8;{marker},{encoded}",
|
||||||
|
tmp_path,
|
||||||
|
)
|
||||||
|
assert result is not None
|
||||||
|
assert Path(result).read_bytes() == payload
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("marker", ["base64", "BASE64"])
|
||||||
@pytest.mark.parametrize("payload", ["not-valid-base64!!!", "@@@@"])
|
@pytest.mark.parametrize("payload", ["not-valid-base64!!!", "@@@@"])
|
||||||
def test_returns_none_for_broken_base64(tmp_path, payload: str) -> None:
|
def test_returns_none_for_broken_base64(tmp_path, payload: str, marker: str) -> None:
|
||||||
assert save_base64_data_url(f"data:image/png;base64,{payload}", tmp_path) is None
|
assert save_base64_data_url(f"data:image/png;{marker},{payload}", tmp_path) is None
|
||||||
assert list(tmp_path.iterdir()) == []
|
assert list(tmp_path.iterdir()) == []
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user