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.

custom_emails: Prevent duplicate emails from send_custom_email command.

The Dancea028a6b9fd88
diff --git a/zerver/lib/send_email.py b/zerver/lib/send_email.py
index 7a5d95098dd..8e9ed844006 100644
--- a/zerver/lib/send_email.py
+++ b/zerver/lib/send_email.py
@@ -35,7 +35,8 @@ from django.utils.translation import override as override_language
from confirmation.models import generate_key
from zerver.lib.logging_util import log_to_file
from zerver.lib.queue import queue_event_on_commit
-from zerver.models import Realm, ScheduledEmail, UserProfile
+from zerver.models import Realm, RealmAuditLog, ScheduledEmail, UserProfile
+from zerver.models.realm_audit_logs import AuditLogEventType
from zerver.models.scheduled_jobs import EMAIL_TYPES
from zerver.models.users import get_user_profile_by_id
from zproject.email_backends import EmailLogBackEnd, get_forward_address
@@ -604,7 +605,7 @@ def custom_email_sender(
from_name: str | None = None,
reply_to: str | None = None,
**kwargs: Any,
-) -> Callable[..., None]:
+) -> tuple[Callable[..., None], str]:
with open(markdown_template_path) as f:
text = f.read()
parsed_email_template = Parser(_class=EmailMessage, policy=default).parsestr(text)
@@ -657,9 +658,9 @@ def custom_email_sender(
already_printed_once = False
def send_one_email(
- context: dict[str, Any], to_user_id: int | None = None, to_email: str | None = None
+ context: dict[str, Any], to_user: UserProfile | None = None, to_email: str | None = None
) -> None:
- assert to_user_id is not None or to_email is not None
+ assert to_user is not None or to_email is not None
if dry_run:
nonlocal already_printed_once
if already_printed_once:
@@ -669,7 +670,7 @@ def custom_email_sender(
with suppress(EmailNotDeliveredError):
send_immediate_email(
email_id,
- to_user_ids=[to_user_id] if to_user_id is not None else None,
+ to_user_ids=[to_user.id] if to_user is not None else None,
to_emails=[to_email] if to_email is not None else None,
from_address=from_address,
reply_to_email=reply_to,
@@ -677,8 +678,22 @@ def custom_email_sender(
context=context,
dry_run=dry_run,
)
-
- return send_one_email
+ if to_user is not None and not dry_run:
+ RealmAuditLog.objects.create(
+ realm=to_user.realm,
+ acting_user=None,
+ modified_user=to_user,
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT,
+ event_time=timezone_now(),
+ extra_data={
+ "email_id": email_template_hash,
+ "email_subject": get_header(
+ subject, parsed_email_template.get("subject"), "subject"
+ ),
+ },
+ )
+
+ return send_one_email, email_template_hash
def send_custom_email(
@@ -699,17 +714,49 @@ def send_custom_email(
from_name="Sender Name")
)
"""
- email_sender = custom_email_sender(**options, dry_run=dry_run)
+ email_sender, email_template_hash = custom_email_sender(**options, dry_run=dry_run)
users = users.select_related("realm")
+
+ # Filter out users who already received this email.
if distinct_email:
+ # This deduplication logic is unsound, because the audit logs
+ # get attached to one USER who received the email, but we
+ # deduplicate based on the CURRENT email address of that user.
+ #
+ # Email addresses change rarely, so we expect failures to be
+ # rare, and the impact of failures is likely to be minor.
+ already_sent_emails = (
+ RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT,
+ extra_data__email_id=email_template_hash,
+ modified_user__isnull=False,
+ )
+ .annotate(lower_email=Lower("modified_user__delivery_email"))
+ .values_list("lower_email", flat=True)
+ .distinct()
+ )
+
+ already_sent_count = already_sent_emails.count()
users = (
users.annotate(lower_email=Lower("delivery_email"))
+ .exclude(lower_email__in=already_sent_emails)
.distinct("lower_email")
.order_by("lower_email", "id")
)
else:
+ # For regular emails: exclude by user ID
+ already_sent_users = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT, extra_data__email_id=email_template_hash
+ ).values_list("modified_user_id", flat=True)
+
+ already_sent_count = already_sent_users.count()
+ users = users.exclude(id__in=already_sent_users)
users = users.order_by("id")
+
+ if already_sent_count:
+ print(f"Excluded {already_sent_count} users who already received this email")
+
for user_profile in users:
context: dict[str, object] = {
"realm": user_profile.realm,
@@ -720,7 +767,7 @@ def send_custom_email(
if add_context is not None:
add_context(context, user_profile)
email_sender(
- to_user_id=user_profile.id,
+ to_user=user_profile,
context=context,
)
return users
@@ -741,7 +788,7 @@ def send_custom_server_email(
email_sender = custom_email_sender(
**options, dry_run=dry_run, from_address=BILLING_SUPPORT_EMAIL
- )
+ )[0]
for server in remote_servers:
context = {
diff --git a/zerver/management/commands/send_custom_email.py b/zerver/management/commands/send_custom_email.py
index 63fa4a0584d..3626e6176d1 100644
--- a/zerver/management/commands/send_custom_email.py
+++ b/zerver/management/commands/send_custom_email.py
@@ -161,7 +161,7 @@ class Command(ZulipBaseCommand):
# This does an implicit "distinct"
all_emails = server_users.union(realm_users).values_list("email", flat=True)
del options["from_address"]
- email_sender = custom_email_sender(
+ email_sender, _ = custom_email_sender(
dry_run=dry_run, from_address=BILLING_SUPPORT_EMAIL, **options
)
diff --git a/zerver/models/realm_audit_logs.py b/zerver/models/realm_audit_logs.py
index 9d76de71278..981d8d76a0c 100644
--- a/zerver/models/realm_audit_logs.py
+++ b/zerver/models/realm_audit_logs.py
@@ -119,6 +119,8 @@ class AuditLogEventType(IntEnum):
SAVED_SNIPPET_CREATED = 800
+ CUSTOM_EMAIL_SENT = 810
+
NAVIGATION_VIEW_CREATED = 850
NAVIGATION_VIEW_UPDATED = 851
NAVIGATION_VIEW_DELETED = 852
diff --git a/zerver/tests/test_management_commands.py b/zerver/tests/test_management_commands.py
index 805e30df0fb..6ffa91cf3f5 100644
--- a/zerver/tests/test_management_commands.py
+++ b/zerver/tests/test_management_commands.py
@@ -1,3 +1,4 @@
+import hashlib
import os
import re
from datetime import timedelta
@@ -10,6 +11,8 @@ from django.apps import apps
from django.conf import settings
from django.core.management import call_command, find_commands
from django.core.management.base import CommandError
+from django.db.models import Q
+from django.db.models.functions import Lower
from django.test import override_settings
from typing_extensions import override
@@ -19,7 +22,8 @@ from zerver.actions.user_settings import do_change_user_setting
from zerver.lib.management import ZulipBaseCommand, check_config
from zerver.lib.test_classes import ZulipTestCase
from zerver.lib.test_helpers import most_recent_message, stdout_suppressed
-from zerver.models import Realm, Recipient, UserProfile
+from zerver.models import Realm, RealmAuditLog, Recipient, UserProfile
+from zerver.models.realm_audit_logs import AuditLogEventType
from zerver.models.realms import get_realm
from zerver.models.streams import get_stream
from zerver.models.users import get_user_profile_by_email
@@ -593,6 +597,210 @@ class TestSendCustomEmail(ZulipTestCase):
],
)
+ # Verify log entries not created in dry-run
+ audit_logs = RealmAuditLog.objects.filter(event_type=AuditLogEventType.CUSTOM_EMAIL_SENT)
+ self.assert_length(audit_logs, 0)
+
+ def test_custom_email_duplicate_prevention_by_user(self) -> None:
+ path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_custom_test.md"
+
+ # Generate email hash
+ with open(path) as f:
+ text = f.read()
+ email_template_hash = hashlib.sha256(text.encode()).hexdigest()[0:32]
+
+ iago = self.example_user("iago")
+ prospero = self.example_user("prospero")
+ othello = self.example_user("othello")
+
+ call_command(
+ self.COMMAND_NAME,
+ f"--path={path}",
+ f"-u={iago.delivery_email},{prospero.delivery_email}",
+ )
+
+ # Verify RealmAuditLog entries were created
+ audit_logs = RealmAuditLog.objects.filter(event_type=AuditLogEventType.CUSTOM_EMAIL_SENT)
+ self.assert_length(audit_logs, 2)
+ self.assertEqual(email_template_hash, audit_logs[0].extra_data["email_id"])
+ self.assertEqual("Test subject", audit_logs[0].extra_data["email_subject"])
+
+ # Second send attempt - should send one email and exclude the two users that already received the email
+
+ with patch("builtins.print") as mock_print:
+ call_command(
+ self.COMMAND_NAME,
+ f"--path={path}",
+ f"-u={iago.delivery_email},{prospero.delivery_email},{othello.delivery_email}",
+ )
+
+ self.assertEqual(
+ mock_print.mock_calls[0:],
+ [
+ call("Excluded 2 users who already received this email"),
+ ],
+ )
+ new_audit_logs = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT
+ )
+ self.assert_length(new_audit_logs, 3)
+ self.assertEqual(email_template_hash, new_audit_logs[0].extra_data["email_id"])
+ self.assertEqual("Test subject", audit_logs[0].extra_data["email_subject"])
+
+ othello_audit_log = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT, modified_user=othello
+ )
+ self.assert_length(othello_audit_log, 1)
+
+ def test_custom_marketing_email_duplicate_prevention_by_email(self) -> None:
+ path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_custom_test.md"
+
+ # Ensure that marketing includes two users with two different realms and different roles
+ realm1 = get_realm("lear")
+ realm2 = get_realm("zephyr")
+
+ shared_email = "[email protected]"
+
+ admin_user = do_create_user(
+ email=shared_email,
+ password="password",
+ realm=realm1,
+ full_name="Admin User",
+ role=UserProfile.ROLE_REALM_ADMINISTRATOR,
+ acting_user=None,
+ tos_version=settings.TERMS_OF_SERVICE_VERSION,
+ )
+ admin_user.save()
+
+ owner_user = do_create_user(
+ email=shared_email.lower(),
+ password="password",
+ realm=realm2,
+ full_name="Owner User",
+ role=UserProfile.ROLE_REALM_OWNER,
+ acting_user=None,
+ tos_version=settings.TERMS_OF_SERVICE_VERSION,
+ )
+
+ owner_user.save()
+
+ # Get the total number of marketing emails to be sent
+ users = UserProfile.objects.filter(
+ is_active=True,
+ is_bot=False,
+ is_mirror_dummy=False,
+ realm__deactivated=False,
+ enable_marketing_emails=True,
+ ).filter(
+ Q(long_term_idle=False)
+ | Q(
+ role__in=[
+ UserProfile.ROLE_REALM_OWNER,
+ UserProfile.ROLE_REALM_ADMINISTRATOR,
+ ]
+ )
+ )
+
+ users = users.annotate(lower_email=Lower("delivery_email")).distinct("lower_email")
+
+ users_count = users.count()
+ users_emails = users.values_list("lower_email", flat=True)
+
+ # Get the email hash
+ with open(path) as f:
+ text = f.read()
+ email_template_hash = hashlib.sha256(text.encode()).hexdigest()[0:32]
+
+ call_command(
+ self.COMMAND_NAME,
+ f"--path={path}",
+ "--marketing",
+ )
+
+ # Verify RealmAuditLog entries were created
+ audit_logs = RealmAuditLog.objects.filter(event_type=AuditLogEventType.CUSTOM_EMAIL_SENT)
+ self.assert_length(audit_logs, users_count)
+
+ # Verify the email_id
+ self.assertEqual(email_template_hash, audit_logs[0].extra_data["email_id"])
+
+ # Verify modified_user email
+ modified_users_email = audit_logs.annotate(
+ lower_email=Lower("modified_user__delivery_email")
+ ).values_list("lower_email", flat=True)
+ self.assertEqual(set(users_emails), set(modified_users_email))
+
+ # Verify only one email was sent (to one of the two users created before)
+ audit_logs_duplicate = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT,
+ modified_user__in=[admin_user, owner_user],
+ )
+ self.assert_length(audit_logs_duplicate, 1)
+
+ # Verify the email addresses match (case-insensitive)
+ assert audit_logs_duplicate[0].modified_user is not None
+ self.assertEqual(
+ audit_logs_duplicate[0].modified_user.delivery_email.lower(),
+ shared_email.lower(),
+ )
+
+ # Verify the second call prevents sending duplication emails
+ with patch("builtins.print") as mock_print:
+ call_command(
+ self.COMMAND_NAME,
+ f"--path={path}",
+ "--marketing",
+ )
+
+ self.assertEqual(
+ mock_print.mock_calls[0:],
+ [
+ call(f"Excluded {users_count} users who already received this email"),
+ ],
+ )
+
+ # Verify no additional audit logs were created for these users
+ audit_logs_after_second_send = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT,
+ modified_user__in=[admin_user, owner_user],
+ )
+ self.assert_length(audit_logs_after_second_send, 1) # Still only 1
+
+ def test_email_sending_failure_does_not_create_audit_log(self) -> None:
+ """Test that audit log entries are not created when email sending fails"""
+ path = "zerver/tests/fixtures/email/custom_emails/email_base_headers_custom_test.md"
+ hamlet = self.example_user("hamlet")
+ cordelia = self.example_user("cordelia")
+
+ # Verify no audit logs exist initially
+ initial_audit_count = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT
+ ).count()
+
+ # Mock email sending to raise an exception
+ with patch("zerver.lib.send_email.send_immediate_email") as mock_send:
+ # Configure mock to raise EmailNotDeliveredError
+ from zerver.lib.send_email import EmailNotDeliveredError
+
+ mock_send.side_effect = EmailNotDeliveredError("SMTP connection failed")
+
+ # Attempt to send emails (should fail silently due to suppress() in send_one_email)
+ call_command(
+ self.COMMAND_NAME,
+ f"--path={path}",
+ "-r=zulip",
+ f"-u={hamlet.delivery_email},{cordelia.delivery_email}",
+ )
+
+ # Verify that email sending was attempted
+ self.assertEqual(mock_send.call_count, 2) # Once for each user
+
+ # Verify no audit log entries were created
+ final_audit_count = RealmAuditLog.objects.filter(
+ event_type=AuditLogEventType.CUSTOM_EMAIL_SENT
+ ).count()
+ self.assertEqual(final_audit_count, initial_audit_count)
+
class TestSendZulipUpdateAnnouncements(ZulipTestCase):
COMMAND_NAME = "send_zulip_update_announcements"