From b4f381ca5581d28ce3f6f3545993db075befcd27 Mon Sep 17 00:00:00 2001 From: Shoaib Date: Fri, 16 Oct 2026 14:53:05 +0500 Subject: [PATCH] fix(media): keep upload filenames within the UTF-8 byte limit The 80-character stem limit can still produce a filename longer than 255 bytes when a document name contains CJK characters or emoji. Adding the upload ID then makes an otherwise valid document name fail on disk. Retain the character limit and trim only stems that exceed the remaining byte budget after the ID, separator, and extension. Decode at a character boundary so the saved name remains valid Unicode. Add file-write regressions for CJK and emoji document names. Validation: 38 media and attachment-store tests; Ruff; BasedPyright; import-boundary checks; git diff --check. --- nanobot/utils/media_decode.py | 3 +++ tests/utils/test_media_decode.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/nanobot/utils/media_decode.py b/nanobot/utils/media_decode.py index cc8494bbe..5d39226f4 100644 --- a/nanobot/utils/media_decode.py +++ b/nanobot/utils/media_decode.py @@ -92,5 +92,8 @@ def media_destination(media_dir: Path, mime_type: str, *, filename: str | None = ext = _MIME_EXTENSION_OVERRIDES.get(mime_type) or mimetypes.guess_extension(mime_type) or ".bin" base = safe_filename(filename or "") stem = Path(base).stem[:80] if base else "" + # Leave room for the 12-character ID, separator, and extension. + max_stem_bytes = 255 - 13 - len(ext.encode("utf-8")) + stem = stem.encode("utf-8")[:max_stem_bytes].decode("utf-8", errors="ignore") saved_name = f"{uuid.uuid4().hex[:12]}_{stem}{ext}" if stem else f"{uuid.uuid4().hex[:12]}{ext}" return media_dir / safe_filename(saved_name) diff --git a/tests/utils/test_media_decode.py b/tests/utils/test_media_decode.py index cbe6cd187..3df6bfa5c 100644 --- a/tests/utils/test_media_decode.py +++ b/tests/utils/test_media_decode.py @@ -62,6 +62,24 @@ def test_saves_document_with_safe_original_name(tmp_path) -> None: assert Path(result).read_bytes() == b"%PDF-1.4" +@pytest.mark.parametrize("stem", ["报告" * 40, "📄" * 60], ids=["cjk", "emoji"]) +def test_saves_document_with_long_unicode_name(tmp_path: Path, stem: str) -> None: + payload = b"%PDF-1.4" + result = save_base64_data_url( + _data_url(payload, mime="application/pdf"), + tmp_path, + filename=f"{stem}.pdf", + ) + + assert result is not None + saved = Path(result) + assert saved.parent == tmp_path + assert saved.suffix == ".pdf" + assert len(saved.name.encode("utf-8")) <= 255 + assert "�" not in saved.name + assert saved.read_bytes() == payload + + def test_document_filename_cannot_escape_media_dir(tmp_path) -> None: result = save_base64_data_url( _data_url(b"%PDF-1.4", mime="application/pdf"),