Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
email_mirror: Handle invalid `charset="..."` values.
Alex Vandivera6d1c41827ca
diff --git a/zerver/lib/email_mirror.py b/zerver/lib/email_mirror.pyindex a380e4518ea..75a17f7adbb 100644--- a/zerver/lib/email_mirror.py+++ b/zerver/lib/email_mirror.py@@ -241,11 +241,17 @@ def get_message_part_by_type(message: EmailMessage, content_type: str) -> Optioncontent = part.get_payload(decode=True)assert isinstance(content, bytes)if charsets[idx]:- return content.decode(charsets[idx], errors="ignore")+ try:+ return content.decode(charsets[idx], errors="ignore")+ except LookupError:+ # The RFCs do not define how to handle unknown+ # charsets, but treating as US-ASCII seems+ # reasonable; fall through to below.+ pass+# If no charset has been specified in the header, assume us-ascii,# by RFC6657: https://tools.ietf.org/html/rfc6657- else:- return content.decode("us-ascii", errors="ignore")+ return content.decode("us-ascii", errors="ignore")return Nonediff --git a/zerver/tests/test_email_mirror.py b/zerver/tests/test_email_mirror.pyindex 759a725b986..ef495db19cf 100644--- a/zerver/tests/test_email_mirror.py+++ b/zerver/tests/test_email_mirror.py@@ -1496,6 +1496,31 @@ class TestContentTypeUnspecifiedCharset(ZulipTestCase):self.assertEqual(message.content, "Email fixture 1.txt body")+class TestContentTypeInvalidCharset(ZulipTestCase):+ def test_unknown_charset(self) -> None:+ message_as_string = self.fixture_data("1.txt", type="email")+ message_as_string = message_as_string.replace(+ 'Content-Type: text/plain; charset="us-ascii"',+ 'Content-Type: text/plain; charset="bogus"',+ )+ incoming_message = message_from_string(message_as_string, policy=email.policy.default)+ # https://github.com/python/typeshed/issues/2417+ assert isinstance(incoming_message, EmailMessage)++ user_profile = self.example_user("hamlet")+ self.login_user(user_profile)+ self.subscribe(user_profile, "Denmark")+ stream = get_stream("Denmark", user_profile.realm)+ stream_to_address = encode_email_address(stream)++ del incoming_message["To"]+ incoming_message["To"] = stream_to_address+ process_message(incoming_message)+ message = most_recent_message(user_profile)++ self.assertEqual(message.content, "Email fixture 1.txt body")++class TestEmailMirrorProcessMessageNoValidRecipient(ZulipTestCase):def test_process_message_no_valid_recipient(self) -> None:incoming_valid_message = EmailMessage()