Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
upload: Do not stream whole contents to guess ASCII charsets.
Alex Vandiver3c7326492633
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.pyindex 428a2d404e1..1cc06d411c5 100644--- a/zerver/lib/upload/__init__.py+++ b/zerver/lib/upload/__init__.py@@ -59,20 +59,35 @@ def maybe_add_charset(content_type: str, file_data: bytes | StreamingSourceWithS):return content_type+ early_abort = Falseif isinstance(file_data, bytes):detected = chardet.detect(file_data)else:+ chunk_size = 4096reader = file_data.reader()detector = chardet.universaldetector.UniversalDetector()+ total_read = 0while True:- data = reader.read(4096)+ data = reader.read(chunk_size)detector.feed(data)- if detector.done or len(data) < 4096:+ if detector.done or len(data) < chunk_size:+ break+ total_read += chunk_size+ if total_read >= 32 * 1024:+ # If there's no BOM and no high bytes, the detector+ # never says "done" before EOF -- we bail out+ # arbitrarily at 32k.+ early_abort = Truebreakdetector.close()reader.close()detected = detector.result- if detected["confidence"] >= 0.90 and detected["encoding"]:+ if early_abort and detected["confidence"] == 1.0 and detected["encoding"] == "ascii":+ # An early abort which didn't see high-byte characters is not+ # a confident "ASCII", as they may come later in the file; we+ # would prefer to leave off the charset rather than be wrong.+ pass+ elif detected["confidence"] >= 0.90 and detected["encoding"]:fake_msg.set_param("charset", detected["encoding"], replace=True)elif detected["confidence"] >= 0.73 and detected["encoding"] == "ISO-8859-1":# ISO-8859-1 detection maxes out at 73%, so if that's whatdiff --git a/zerver/tests/test_tusd.py b/zerver/tests/test_tusd.pyindex 76e06c62fba..57ba30de607 100644--- a/zerver/tests/test_tusd.py+++ b/zerver/tests/test_tusd.py@@ -1,4 +1,5 @@import os+from unittest import mockimport orjsonfrom django.conf import settings@@ -673,55 +674,73 @@ class TusdPreFinishTest(ZulipTestCase):self.assertEqual(response["ContentType"], "binary/octet-stream")@use_s3_backend- def test_s3_upload_chardet(self) -> None:+ def test_s3_upload_streaming_chardet(self) -> None:assert settings.LOCAL_FILES_DIR is Noneself.login("hamlet")hamlet = self.example_user("hamlet")bucket = create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)[0]upload_backend = S3UploadBackend()- filename = "text-file.txt"- path_id = upload_backend.generate_message_upload_path(- str(hamlet.realm.id), sanitize_name(filename, strict=True)- )- content = "zulip!"- info = TusUpload(- id=path_id,- size=len(content),- offset=0,- size_is_deferred=False,- meta_data={- "filename": filename,- "filetype": "text/plain",- "name": filename,- "type": "text/plain",- },- is_final=False,- is_partial=False,- partial_uploads=None,- storage=None,- )- bucket.Object(path_id).put(- Body=content.encode(),- ContentType="application/octet-stream",- Metadata={k: v.encode("ascii", "replace").decode() for k, v in info.meta_data.items()},- )- bucket.Object(f"{path_id}.info").put(- Body=info.model_dump_json().encode(),- )- # Post the hook saying the file is in place- result = self.client_post(- "/api/internal/tusd",- self.request(info).model_dump(),- content_type="application/json",- )- self.assertEqual(result.status_code, 200)+ def upload_text_file(filename: str, size: int) -> str:+ path_id = upload_backend.generate_message_upload_path(+ str(hamlet.realm.id), sanitize_name(filename, strict=True)+ )+ content = "a" * (size)+ info = TusUpload(+ id=path_id,+ size=len(content),+ offset=0,+ size_is_deferred=False,+ meta_data={+ "filename": filename,+ "filetype": "text/plain",+ "name": filename,+ "type": "text/plain",+ },+ is_final=False,+ is_partial=False,+ partial_uploads=None,+ storage=None,+ )+ bucket.Object(path_id).put(+ Body=content.encode(),+ ContentType="application/octet-stream",+ Metadata={+ k: v.encode("ascii", "replace").decode() for k, v in info.meta_data.items()+ },+ )+ bucket.Object(f"{path_id}.info").put(+ Body=info.model_dump_json().encode(),+ )++ # Post the hook saying the file is in place+ result = self.client_post(+ "/api/internal/tusd",+ self.request(info).model_dump(),+ content_type="application/json",+ )+ self.assertEqual(result.status_code, 200)+ return path_id+ path_id = upload_text_file("short-ascii.txt", 2048)attachment = Attachment.objects.get(path_id=path_id)- self.assertEqual(attachment.size, len(content))+ self.assertEqual(attachment.size, 2048)self.assertEqual(attachment.content_type, 'text/plain; charset="ascii"')self.assertEqual(bucket.Object(path_id).get()["ContentType"], 'text/plain; charset="ascii"')+ with mock.patch("zerver.views.tusd.attachment_source") as mock_attachment_source:+ mock_attachment_source.return_value.size = 40 * 1024+ reader = mock_attachment_source.return_value.reader.return_value+ # We set up 10 possible reads, but should not consume them all+ reader.read.side_effect = (b"a" * 4096,) * 10+ path_id = upload_text_file("big-ascii.txt", 4096 * 10)+ # 32k / 4k reads = 8 reads total before bailing out+ self.assertEqual(reader.read.call_count, 8)+ attachment = Attachment.objects.get(path_id=path_id)+ self.assertEqual(attachment.size, 40 * 1024)+ self.assertEqual(attachment.content_type, "text/plain")+ self.assertEqual(bucket.Object(path_id).get()["ContentType"], "text/plain")+class TusdPreTerminateTest(ZulipTestCase):def request(self, info: TusUpload) -> TusHook: