Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

upload: Resolve avatar upload content type in the callers.

Agnish Bauri1853682e24fb
diff --git a/tools/screenshots/generate-integration-docs-screenshot b/tools/screenshots/generate-integration-docs-screenshot
index 8c85d0bbca0..8bd41f94bef 100755
--- a/tools/screenshots/generate-integration-docs-screenshot
+++ b/tools/screenshots/generate-integration-docs-screenshot
@@ -96,7 +96,7 @@ def create_integration_bot(integration: Integration, bot_name: str | None = None
bot_avatar_path = static_path(bot_avatar_path)
if os.path.isfile(bot_avatar_path):
with open(bot_avatar_path, "rb") as f:
- upload_avatar_image(f, bot)
+ upload_avatar_image(f, bot, content_type="image/png")
do_change_avatar_fields(bot, UserProfile.AVATAR_FROM_USER, acting_user=owner)
else:
raise ValueError(f"Bot avatar file {bot_avatar_path} does not exist.")
diff --git a/tools/screenshots/generate-user-messages-screenshot b/tools/screenshots/generate-user-messages-screenshot
index 4172559837f..f4f965036c3 100755
--- a/tools/screenshots/generate-user-messages-screenshot
+++ b/tools/screenshots/generate-user-messages-screenshot
@@ -42,6 +42,7 @@ from zerver.actions.user_groups import check_add_user_group
from zerver.actions.user_settings import do_change_avatar_fields
from zerver.lib.emoji import get_emoji_data
from zerver.lib.message import SendMessageRequest, access_message
+from zerver.lib.mime_types import guess_type
from zerver.lib.stream_subscription import get_active_subscriptions_for_stream_id
from zerver.lib.streams import access_stream_by_id, ensure_stream
from zerver.lib.timestamp import datetime_to_timestamp
@@ -97,8 +98,10 @@ def create_user(full_name: str, avatar_filename: str | None) -> None:
def set_avatar(user: UserProfile, filename: str) -> None:
+ content_type = guess_type(filename)[0]
+ assert content_type is not None
with open(filename, "rb") as f:
- upload_avatar_image(f, user)
+ upload_avatar_image(f, user, content_type=content_type)
do_change_avatar_fields(user, UserProfile.AVATAR_FROM_USER, acting_user=DEFAULT_USER)
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.py
index 140ac7b2034..fad7e9ac6c7 100644
--- a/zerver/lib/upload/__init__.py
+++ b/zerver/lib/upload/__init__.py
@@ -432,12 +432,10 @@ def write_jdenticon_avatars(
def upload_avatar_image(
user_file: IO[bytes],
user_profile: UserProfile,
- content_type: str | None = None,
+ content_type: str,
backend: ZulipUploadBackend | None = None,
future: bool = True,
) -> None:
- if content_type is None:
- content_type = guess_type(user_file.name)[0]
if content_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES:
raise BadImageError(_("Invalid image format"))
file_path = user_avatar_path(user_profile, future=future)
diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.py
index 58359d30ed0..118beb81d76 100644
--- a/zerver/tests/test_import_export.py
+++ b/zerver/tests/test_import_export.py
@@ -205,7 +205,7 @@ class ExportFile(ZulipTestCase):
)
with get_test_image_file("img.png") as img_file:
- upload_avatar_image(img_file, user_profile, future=False)
+ upload_avatar_image(img_file, user_profile, content_type="image/png", future=False)
user_profile.avatar_source = "U"
user_profile.save()
diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py
index 6d6271588b9..180f1f7e54b 100644
--- a/zerver/tests/test_realm.py
+++ b/zerver/tests/test_realm.py
@@ -3625,7 +3625,7 @@ class ScrubRealmTest(ZulipTestCase):
do_change_avatar_fields(iago, UserProfile.AVATAR_FROM_GRAVATAR, acting_user=iago)
continue
with get_test_image_file("img.png") as img_file:
- upload_avatar_image(img_file, iago)
+ upload_avatar_image(img_file, iago, content_type="image/png")
do_change_avatar_fields(iago, UserProfile.AVATAR_FROM_USER, acting_user=iago)
avatar_files = [
*glob.glob(f"{settings.LOCAL_AVATARS_DIR}/{zulip.id}/*.original"),
diff --git a/zerver/tests/test_upload.py b/zerver/tests/test_upload.py
index 868ee980b9d..19a1b77a3ca 100644
--- a/zerver/tests/test_upload.py
+++ b/zerver/tests/test_upload.py
@@ -1668,6 +1668,32 @@ class AvatarTest(UploadSerializeMixin, ZulipTestCase):
self.assertFalse(os.path.isfile(avatar_original_path_id))
self.assertFalse(os.path.isfile(avatar_medium_path_id))
+ def test_avatar_empty_content_type(self) -> None:
+ """
+ An avatar upload with an empty content type should succeed by
+ guessing the type from the filename.
+ """
+ self.login("hamlet")
+ with get_test_image_file("img.png") as fp:
+ uploaded_file = SimpleUploadedFile("img.png", fp.read(), content_type="")
+ result = self.client_post("/json/users/me/avatar", {"file": uploaded_file})
+ response_dict = self.assert_json_success(result)
+ self.assertIn("avatar_url", response_dict)
+
+ # With no filename extension to guess from, the upload is rejected.
+ with get_test_image_file("img.png") as fp:
+ uploaded_file = SimpleUploadedFile("img", fp.read(), content_type="")
+ result = self.client_post("/json/users/me/avatar", {"file": uploaded_file})
+ self.assert_json_error(result, "Invalid image format")
+
+ # A non-empty content type is used as-is, not overridden by the guess.
+ with get_test_image_file("img.png") as fp:
+ uploaded_file = SimpleUploadedFile(
+ "img.png", fp.read(), content_type="application/octet-stream"
+ )
+ result = self.client_post("/json/users/me/avatar", {"file": uploaded_file})
+ self.assert_json_error(result, "Invalid image format")
+
def test_invalid_avatars(self) -> None:
"""
A PUT request to /json/users/me/avatar with an invalid file should fail.
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index f466f8be76d..61f55ef3b80 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -420,7 +420,9 @@ class S3Test(ZulipTestCase):
medium_path_id = path_id + "-medium.png"
with get_test_image_file("img.png") as image_file:
- zerver.lib.upload.upload_avatar_image(image_file, user_profile, future=False)
+ zerver.lib.upload.upload_avatar_image(
+ image_file, user_profile, content_type="image/png", future=False
+ )
user_profile.avatar_source = UserProfile.AVATAR_FROM_USER
user_profile.save()
test_image_data = read_test_image_file("img.png")
@@ -506,7 +508,9 @@ class S3Test(ZulipTestCase):
medium_file_path = base_file_path + "-medium.png"
with get_test_image_file("img.png") as image_file:
- zerver.lib.upload.upload_avatar_image(image_file, user_profile, future=False)
+ zerver.lib.upload.upload_avatar_image(
+ image_file, user_profile, content_type="image/png", future=False
+ )
user_profile.avatar_source = UserProfile.AVATAR_FROM_USER
user_profile.save()
diff --git a/zerver/tests/test_users.py b/zerver/tests/test_users.py
index bc85890af12..c31aa63bc38 100644
--- a/zerver/tests/test_users.py
+++ b/zerver/tests/test_users.py
@@ -1729,7 +1729,7 @@ class UserProfileTest(ZulipTestCase):
# Upload cordelia's avatar
with get_test_image_file("img.png") as image_file:
- upload_avatar_image(image_file, cordelia, future=False)
+ upload_avatar_image(image_file, cordelia, content_type="image/png", future=False)
OnboardingStep.objects.filter(user=cordelia).delete()
OnboardingStep.objects.filter(user=iago).delete()
diff --git a/zerver/views/user_settings.py b/zerver/views/user_settings.py
index 3e66dc91d55..71f4204bd14 100644
--- a/zerver/views/user_settings.py
+++ b/zerver/views/user_settings.py
@@ -66,7 +66,7 @@ from zerver.lib.typed_endpoint_validators import (
parse_enum_from_string_value,
timezone_validator,
)
-from zerver.lib.upload import upload_avatar_image
+from zerver.lib.upload import get_file_info, upload_avatar_image
from zerver.lib.user_groups import (
get_recursive_group_members_union_for_groups,
user_group_ids_to_user_groups,
@@ -563,7 +563,8 @@ def set_avatar_backend(request: HttpRequest, user_profile: UserProfile) -> HttpR
max_size=settings.MAX_AVATAR_FILE_SIZE_MIB,
)
)
- upload_avatar_image(user_file, user_profile, content_type=user_file.content_type)
+ _filename, content_type = get_file_info(user_file)
+ upload_avatar_image(user_file, user_profile, content_type=content_type)
do_change_avatar_fields(user_profile, UserProfile.AVATAR_FROM_USER, acting_user=user_profile)
user_avatar_url = avatar_url(user_profile)
diff --git a/zerver/views/users.py b/zerver/views/users.py
index 2d586a1e873..51eb9648845 100644
--- a/zerver/views/users.py
+++ b/zerver/views/users.py
@@ -74,7 +74,7 @@ from zerver.lib.typed_endpoint import (
)
from zerver.lib.typed_endpoint_validators import check_int_in_validator, check_url
from zerver.lib.types import ProfileDataElementUpdateDict
-from zerver.lib.upload import upload_avatar_image
+from zerver.lib.upload import get_file_info, upload_avatar_image
from zerver.lib.url_encoding import append_url_query_string
from zerver.lib.user_groups import UserGroupMembershipDetails
from zerver.lib.users import (
@@ -574,7 +574,8 @@ def patch_bot_backend(
[user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
assert user_file.size is not None
- upload_avatar_image(user_file, bot, content_type=user_file.content_type)
+ _filename, content_type = get_file_info(user_file)
+ upload_avatar_image(user_file, bot, content_type=content_type)
avatar_source = UserProfile.AVATAR_FROM_USER
do_change_avatar_fields(bot, avatar_source, acting_user=user_profile)
else:
@@ -735,9 +736,8 @@ def add_bot_backend(
[user_file] = request.FILES.values()
assert isinstance(user_file, UploadedFile)
assert user_file.size is not None
- upload_avatar_image(
- user_file, bot_profile, content_type=user_file.content_type, future=False
- )
+ _filename, content_type = get_file_info(user_file)
+ upload_avatar_image(user_file, bot_profile, content_type=content_type, future=False)
if bot_type in (UserProfile.OUTGOING_WEBHOOK_BOT, UserProfile.EMBEDDED_BOT):
assert isinstance(service_name, str)
diff --git a/zilencer/management/commands/add_mock_conversation.py b/zilencer/management/commands/add_mock_conversation.py
index 5f0b023d951..2ffadd326dd 100644
--- a/zilencer/management/commands/add_mock_conversation.py
+++ b/zilencer/management/commands/add_mock_conversation.py
@@ -37,7 +37,7 @@ From image editing program:
def set_avatar(self, user: UserProfile, filename: str) -> None:
with open(filename, "rb") as f:
- upload_avatar_image(f, user)
+ upload_avatar_image(f, user, content_type="image/png")
do_change_avatar_fields(user, UserProfile.AVATAR_FROM_USER, acting_user=None)
def add_message_formatting_conversation(self) -> None: