Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
upload: Don't hold a read open on S3 objects during self-copy.
bhuvan-somisettyf317e656b5e5
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.pyindex 164544d858b..58238974db8 100644--- a/zerver/lib/upload/__init__.py+++ b/zerver/lib/upload/__init__.py@@ -70,8 +70,11 @@ def needs_charset_detection(content_type: str) -> bool:def maybe_add_charset(content_type: str, file_data: bytes | StreamingSourceWithSize) -> str:- if not needs_charset_detection(content_type):- return content_type+ # Callers must gate on needs_charset_detection(content_type) first,+ # so that they can avoid opening file_data at all when it won't be+ # inspected -- with the S3 backend, opening a source starts an open+ # GetObject read immediately, rather than lazily on first read.+ assert needs_charset_detection(content_type)fake_msg = EmailMessage()fake_msg["content-type"] = content_type@@ -81,23 +84,25 @@ def maybe_add_charset(content_type: str, file_data: bytes | StreamingSourceWithSelse:chunk_size = 4096reader = file_data.reader()- detector = chardet.UniversalDetector()- total_read = 0- while True:- data = reader.read(chunk_size)- detector.feed(data)- 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 = True- break- detector.close()- reader.close()- detected = detector.result+ try:+ detector = chardet.UniversalDetector()+ total_read = 0+ while True:+ data = reader.read(chunk_size)+ detector.feed(data)+ 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 = True+ break+ detector.close()+ detected = detector.result+ finally:+ reader.close()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; wediff --git a/zerver/tests/test_tusd.py b/zerver/tests/test_tusd.pyindex fc32938427c..8a22b7a2ded 100644--- a/zerver/tests/test_tusd.py+++ b/zerver/tests/test_tusd.py@@ -12,6 +12,7 @@ from zerver.lib.test_helpers import create_s3_buckets, find_key_by_email, use_s3from zerver.lib.upload import (create_attachment,generate_message_upload_path,+ get_upload_backend,sanitize_name,store_message_attachment,upload_message_attachment,@@ -730,6 +731,103 @@ class TusdPreFinishTest(ZulipTestCase):self.assertEqual(attachment.content_type, "text/plain")self.assertEqual(bucket.Object(path_id).get()["ContentType"], "text/plain")+ @use_s3_backend+ def test_s3_upload_no_read_open_during_self_copy(self) -> None:+ # Regression test for the pre-finish hook holding a read of+ # the object open while issuing the self-CopyObject which sets+ # the object's Content-Type. S3 itself does not mind, but+ # S3-compatible backends which lock per object (e.g. MinIO)+ # hold a read lock for the duration of an open GetObject, so+ # the copy blocked until the idle reader hit the backend's+ # write deadline, tens of seconds later.+ assert settings.LOCAL_FILES_DIR is None+ self.login("hamlet")+ hamlet = self.example_user("hamlet")+ create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)+ upload_backend = get_upload_backend()+ assert isinstance(upload_backend, S3UploadBackend)+ bucket = upload_backend.uploads_bucket++ def upload_file(filename: str, filetype: str) -> list[str]:+ path_id = upload_backend.generate_message_upload_path(+ str(hamlet.realm.id), sanitize_name(filename, strict=True)+ )+ info = TusUpload(+ id=path_id,+ size=len("zulip!"),+ offset=0,+ size_is_deferred=False,+ meta_data={+ "filename": filename,+ "filetype": filetype,+ "name": filename,+ "type": filetype,+ },+ is_final=False,+ is_partial=False,+ partial_uploads=None,+ storage=None,+ )+ bucket.Object(path_id).put(+ Body=b"zulip!",+ 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(),+ )++ # Reads of the object and the self-copy of it go through+ # unrelated objects, so we attach both to one parent mock+ # to observe the order they happen in.+ calls = mock.Mock()+ client = bucket.meta.client+ with (+ mock.patch("zerver.views.tusd.attachment_source") as mock_attachment_source,+ mock.patch.object(+ client, "copy_object", wraps=client.copy_object+ ) as mock_copy_object,+ ):+ calls.attach_mock(mock_attachment_source, "attachment_source")+ calls.attach_mock(mock_copy_object, "copy_object")+ mock_attachment_source.return_value.size = len("zulip!")+ mock_attachment_source.return_value.reader.return_value.read.return_value = b""+ result = self.client_post(+ "/api/internal/tusd",+ self.request(info).model_dump(),+ content_type="application/json",+ )+ self.assertEqual(result.status_code, 200)+ return [name for name, _args, _kwargs in calls.mock_calls]++ # A bare text/plain needs sniffing, so the object is opened+ # before the copy -- but that read is closed again before the+ # copy is issued, and a fresh one opened for create_attachment+ # and maybe_thumbnail afterwards.+ self.assertEqual(+ upload_file("zulip.txt", "text/plain"),+ [+ "attachment_source",+ "attachment_source().reader",+ "attachment_source().reader().read",+ "attachment_source().reader().close",+ "copy_object",+ "attachment_source",+ ],+ )++ # A Content-Type which already declares a charset needs no+ # sniffing, so the object is not opened until after the copy.+ # This is the case where nothing but the read being skipped+ # keeps it from spanning the copy, since maybe_add_charset is+ # not called at all.+ self.assertEqual(+ upload_file("utf8.txt", 'text/plain; charset="utf-8"'),+ ["copy_object", "attachment_source"],+ )+class TusdPreTerminateTest(ZulipTestCase):def request(self, info: TusUpload) -> TusHook:diff --git a/zerver/views/tusd.py b/zerver/views/tusd.pyindex e50fe130ebc..4a37143efe2 100644--- a/zerver/views/tusd.py+++ b/zerver/views/tusd.py@@ -26,6 +26,7 @@ from zerver.lib.upload import (generate_message_upload_path,get_upload_backend,maybe_add_charset,+ needs_charset_detection,sanitize_name,)from zerver.models import ArchivedAttachment, Attachment, PreregistrationRealm, Realm, UserProfile@@ -156,8 +157,16 @@ def handle_upload_pre_finish_hook(content_type = guess_type(filename)[0]if content_type is None:content_type = "application/octet-stream"- file_data = attachment_source(path_id)- content_type = maybe_add_charset(content_type, file_data)++ # Only open the object at all when charset detection actually needs to+ # inspect its bytes. With the S3 backend, opening it starts a+ # GetObject read that we'd otherwise hold open across the self-copy+ # below. AWS S3 doesn't mind, but S3-compatible backends that lock per+ # object (e.g. MinIO) hold a read lock for the life of an open+ # GetObject, so the copy would block until that idle reader is torn+ # down -- tens of seconds later.+ if needs_charset_detection(content_type):+ content_type = maybe_add_charset(content_type, attachment_source(path_id))if settings.LOCAL_UPLOADS_DIR is None:# We "copy" the file to itself to update the Content-Type,@@ -200,6 +209,10 @@ def handle_upload_pre_finish_hook(StorageClass=settings.S3_UPLOADS_STORAGE_CLASS,)+ # Open a fresh source for create_attachment/maybe_thumbnail to+ # read from, now that the self-copy above (if any) has finished.+ file_data = attachment_source(path_id)+with transaction.atomic(durable=True):create_attachment(filename,