Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(upload): fall back to a deterministic ASCII name for non-Latin upload filenames (#6118)

LearningCircuit1dae807d74ca
diff --git a/changelog.d/6108.bugfix.md b/changelog.d/6108.bugfix.md
new file mode 100644
index 0000000000..314964368e
--- /dev/null
+++ b/changelog.d/6108.bugfix.md
@@ -0,0 +1 @@
+Uploads (PDF and collection uploads of .txt/.docx/.epub) now receive a deterministic safe fallback name when a stem containing non-Latin letters or digits loses all characters during ASCII sanitization. Over-long filenames that only fit an extension, or leave no room for one, are now rejected instead of being silently truncated past the length limit.
diff --git a/src/local_deep_research/security/filename_sanitizer.py b/src/local_deep_research/security/filename_sanitizer.py
index 91f3a36797..4af3da835f 100644
--- a/src/local_deep_research/security/filename_sanitizer.py
+++ b/src/local_deep_research/security/filename_sanitizer.py
@@ -7,6 +7,7 @@ importing secure_filename directly.
from __future__ import annotations
+import hashlib
from typing import Optional
from werkzeug.utils import secure_filename
@@ -35,14 +36,24 @@ def sanitize_filename(
max_length: Maximum allowed filename length.
Returns:
- Sanitized filename safe for filesystem use.
+ Sanitized filename safe for filesystem use. If the stem (the
+ part before the last dot) sanitizes to nothing but still
+ contains letters or digits — as happens for non-Latin scripts
+ such as CJK or Cyrillic, which werkzeug's secure_filename()
+ drops entirely — the stem is replaced with a deterministic
+ ``upload-<12 hex chars>`` name derived from a hash of the
+ original filename, and the sanitized extension is preserved.
Raises:
UnsafeFilenameError: If the filename is empty, becomes empty
- after sanitization, or has a disallowed extension.
+ after sanitization, has a disallowed extension,
+ ``max_length`` is not positive, or the extension alone
+ exceeds ``max_length`` (leaving no room for a stem).
"""
if not filename:
raise UnsafeFilenameError("No filename provided")
+ if max_length < 1:
+ raise UnsafeFilenameError("Maximum filename length must be positive")
# Strip null bytes before passing to secure_filename
cleaned = filename.replace("\x00", "")
@@ -50,6 +61,27 @@ def sanitize_filename(
# Apply werkzeug's path traversal protection
safe_name = secure_filename(cleaned)
+ raw_stem, separator, raw_extension = cleaned.rpartition(".")
+ if not separator:
+ raw_stem = cleaned
+
+ if not secure_filename(raw_stem) and any(
+ character.isalnum() for character in raw_stem
+ ):
+ extension = ""
+ if separator:
+ extension_source = secure_filename(f"x.{raw_extension}")
+ extension_index = extension_source.rfind(".")
+ if extension_index > 0:
+ extension = extension_source[extension_index:]
+
+ # A surrogate can occur in a filesystem-derived or decoded name.
+ # It only contributes to the digest; the generated name stays ASCII.
+ digest = hashlib.sha256(
+ cleaned.encode("utf-8", errors="surrogatepass")
+ ).hexdigest()[:12]
+ safe_name = f"upload-{digest}{extension}"
+
if not safe_name:
raise UnsafeFilenameError(
"Filename contains no safe characters after sanitization"
@@ -61,7 +93,12 @@ def sanitize_filename(
dot_idx = safe_name.rfind(".")
if dot_idx > 0:
ext = safe_name[dot_idx:]
- safe_name = safe_name[: max_length - len(ext)] + ext
+ stem_length = max_length - len(ext)
+ if stem_length < 1:
+ raise UnsafeFilenameError(
+ "Filename extension exceeds maximum length"
+ )
+ safe_name = safe_name[:stem_length] + ext
else:
safe_name = safe_name[:max_length]
diff --git a/tests/security/test_filename_sanitizer.py b/tests/security/test_filename_sanitizer.py
index 23c3ed1464..95cd65eb8c 100644
--- a/tests/security/test_filename_sanitizer.py
+++ b/tests/security/test_filename_sanitizer.py
@@ -19,6 +19,83 @@ class TestSanitizeFilename:
assert ".." not in result
assert result == "etc_passwd.pdf"
+ @pytest.mark.parametrize(
+ "filename",
+ ("研究報告.pdf", "отчёт.pdf", "έρευνα.pdf"),
+ )
+ def test_non_latin_stem_gets_deterministic_safe_fallback(self, filename):
+ first = sanitize_filename(filename, allowed_extensions={".pdf"})
+ second = sanitize_filename(filename, allowed_extensions={".pdf"})
+
+ assert first == second
+ assert first.startswith("upload-")
+ assert first.endswith(".pdf")
+ assert first.isascii()
+
+ def test_non_latin_fallback_removes_traversal_and_controls(self):
+ result = sanitize_filename(
+ "../研究\r\n\x00.pdf",
+ allowed_extensions={".pdf"},
+ )
+
+ assert result.startswith("upload-")
+ assert result.endswith(".pdf")
+ assert not {"/", "\\", "\r", "\n"} & set(result)
+
+ def test_non_latin_fallback_names_differ_by_input(self):
+ first = sanitize_filename("研究報告.pdf", allowed_extensions={".pdf"})
+ second = sanitize_filename("отчёт.pdf", allowed_extensions={".pdf"})
+
+ assert first != second
+
+ def test_non_latin_fallback_still_rejects_disallowed_extension(self):
+ # Both the stem AND the extension are non-Latin, so on the base
+ # implementation secure_filename() of the whole string drops
+ # everything and fails before the extension is ever checked
+ # ("no safe characters"). The fallback must instead reconstruct a
+ # named candidate and still enforce the extension allowlist against
+ # it.
+ with pytest.raises(UnsafeFilenameError, match="not allowed") as exc:
+ sanitize_filename("研究報告.文書", allowed_extensions={".pdf"})
+
+ assert "no safe characters" not in str(exc.value)
+
+ @pytest.mark.parametrize("surrogate", ("\ud800", "\udcff"))
+ def test_non_latin_fallback_handles_surrogate_codepoints(self, surrogate):
+ filename = f"研究{surrogate}.pdf"
+ result = sanitize_filename(filename, allowed_extensions={".pdf"})
+ assert result.startswith("upload-")
+ assert result.endswith(".pdf")
+ assert result.isascii()
+ assert result == sanitize_filename(
+ filename, allowed_extensions={".pdf"}
+ )
+
+ @pytest.mark.parametrize("stem", ("研究", "report"))
+ def test_overlong_extension_is_rejected(self, stem):
+ with pytest.raises(UnsafeFilenameError, match="extension exceeds"):
+ sanitize_filename(f"{stem}." + "a" * 300)
+
+ @pytest.mark.parametrize(
+ "filename,max_length,match",
+ (
+ ("研究.pdf", 0, "must be positive"),
+ ("研究.pdf", -1, "must be positive"),
+ ("研究.pdf", 4, "extension exceeds"),
+ ("report", 0, "must be positive"),
+ ),
+ )
+ def test_length_limit_must_allow_a_stem_and_extension(
+ self, filename, max_length, match
+ ):
+ with pytest.raises(UnsafeFilenameError, match=match):
+ sanitize_filename(filename, max_length=max_length)
+
+ def test_fallback_truncation_retains_pdf_extension(self):
+ result = sanitize_filename("研究.pdf", max_length=12)
+ assert len(result) == 12
+ assert result.endswith(".pdf")
+
def test_null_bytes_stripped(self):
result = sanitize_filename("file\x00name.pdf")
assert "\x00" not in result
diff --git a/tests/web/test_multipart_upload_boundary.py b/tests/web/test_multipart_upload_boundary.py
index 0717f15280..170dc33f67 100644
--- a/tests/web/test_multipart_upload_boundary.py
+++ b/tests/web/test_multipart_upload_boundary.py
@@ -228,25 +228,6 @@ class TestFilenameSanitisationOverTheWire:
)
assert _reported_name(errors[0]) == "cafe.pdf", errors
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (pre-dates the port, still live): a filename with no "
- "Latin characters at all is rejected as unsafe. Mechanism: "
- "sanitize_filename -> werkzeug.secure_filename NFKD-normalises "
- "then does .encode('ascii', 'ignore'), which deletes every CJK "
- "codepoint; '研究報告.pdf' collapses to '.pdf' and the trailing "
- "strip('._') leaves 'pdf'. With no dot left, the extension "
- "check computes ext='' , which is not in {'.pdf'}, so "
- "UnsafeFilenameError is raised and the handler answers "
- "'Rejected file: invalid or disallowed filename'. Net effect: "
- "no user whose filenames are entirely CJK/Cyrillic/Greek can "
- "upload a PDF at all. Fix belongs in "
- "security/filename_sanitizer.py (derive the extension from the "
- "ORIGINAL name before ASCII-folding, and fall back to a "
- "generated stem when folding empties the name)."
- ),
- )
def test_non_latin_name_should_not_be_rejected_outright(
self, upload_client
):
@@ -256,7 +237,12 @@ class TestFilenameSanitisationOverTheWire:
)
assert resp.status_code == 400, resp.text
- assert FILENAME_REJECTED not in _errors(resp)
+ errors = _errors(resp)
+ assert FILENAME_REJECTED not in errors
+ assert len(errors) == 1, errors
+ reported_name = _reported_name(errors[0])
+ assert reported_name.startswith("upload-"), errors
+ assert reported_name.endswith(".pdf"), errors
def test_duplicate_filenames_are_processed_independently(
self, upload_client