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.
This commit is contained in:
Shoaib authored and Xubin Ren committed 2026-10-18 15:23:07 +08:00
1 parent c49d84b4e5
commit b4f381ca55
2 files changed
+21

No files matched your search

+3
View File
@@ -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)
+18
View File
@@ -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"),