Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/backend/core/api/viewsets/inbound/mta.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,21 @@ def deliver(self, request):
status=status.HTTP_400_BAD_REQUEST,
)

# Validate incoming email size against configured limit
if len(raw_data) > settings.MAX_INCOMING_EMAIL_SIZE:
logger.error(
"Incoming email exceeds size limit: %d bytes (limit: %d bytes)",
len(raw_data),
settings.MAX_INCOMING_EMAIL_SIZE,
)
return Response(
{
"status": "error",
"detail": f"Email size exceeds maximum allowed size of {settings.MAX_INCOMING_EMAIL_SIZE} bytes",
},
status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
)

logger.info(
"Raw email received: %d bytes for %s",
len(raw_data),
Expand Down
8 changes: 2 additions & 6 deletions src/backend/core/api/viewsets/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,18 +106,14 @@ def post(self, request):

self.check_object_permissions(request, message)

prepared = prepare_outbound_message(
# Prepare the message (raises ValidationError if size limits exceeded)
prepare_outbound_message(
mailbox_sender,
message,
request.data.get("textBody"),
request.data.get("htmlBody"),
request.user,
)
if not prepared:
raise drf_exceptions.APIException(
"Failed to prepare message for sending.",
code=status.HTTP_500_INTERNAL_SERVER_ERROR,
)

# Launch async task for sending the message
task = send_message_task.delay(str(message.id), must_archive=must_archive)
Expand Down
38 changes: 36 additions & 2 deletions src/backend/core/mda/draft.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
import uuid
from typing import Optional

from django.conf import settings
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

import rest_framework as drf

Expand Down Expand Up @@ -48,7 +50,7 @@ def create_draft(

# Get or create sender contact
mailbox_email = f"{mailbox.local_part}@{mailbox.domain.name}"
sender_contact, _ = models.Contact.objects.get_or_create(
sender_contact, _created = models.Contact.objects.get_or_create(
email=mailbox_email,
mailbox=mailbox,
defaults={
Expand Down Expand Up @@ -195,7 +197,7 @@ def update_draft(
# Create new recipients
emails = update_data.get(recipient_type) or []
for email in emails:
contact, _ = models.Contact.objects.get_or_create(
contact, _created = models.Contact.objects.get_or_create(
email=email,
mailbox=mailbox,
defaults={
Expand Down Expand Up @@ -292,6 +294,38 @@ def update_draft(
to_add = new_attachments - current_attachment_ids
to_remove = current_attachment_ids - new_attachments

# Validate total attachment size before adding
if to_add:
# Calculate current total (excluding attachments about to be removed)
current_attachments = message.attachments.exclude(id__in=to_remove)
current_total_size = sum(
att.blob.size for att in current_attachments.select_related("blob")
)

# Calculate size of new attachments being added
new_attachments_objs = models.Attachment.objects.filter(
id__in=to_add
).select_related("blob")
new_total_size = sum(att.blob.size for att in new_attachments_objs)

# Check if adding these would exceed the limit
total_size = current_total_size + new_total_size
if total_size > settings.MAX_OUTGOING_EMAIL_SIZE:
raise drf.exceptions.ValidationError(
{
"attachments": _(
"Total attachment size (%(total_size)s bytes) exceeds maximum "
"allowed size of %(max_size)s bytes. Current attachments: "
"%(current_size)s bytes."
)
% {
"total_size": total_size,
"max_size": settings.MAX_OUTGOING_EMAIL_SIZE,
"current_size": current_total_size,
}
}
)

# Remove attachments no longer in the list
if to_remove:
message.attachments.remove(*to_remove)
Expand Down
32 changes: 31 additions & 1 deletion src/backend/core/mda/outbound.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
from django.conf import settings
from django.core.cache import cache
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

import rest_framework as drf

from core import models
from core.enums import MessageDeliveryStatusChoices
Expand Down Expand Up @@ -150,9 +153,12 @@ def prepare_outbound_message(
# Add attachments if present
if message.attachments.exists():
attachments = []
total_attachment_size = 0

for attachment in message.attachments.select_related("blob").all():
# Get the blob data
blob = attachment.blob
total_attachment_size += blob.size

# Add the attachment to the MIME data
attachments.append(
Expand All @@ -178,7 +184,9 @@ def prepare_outbound_message(
)
except Exception as e:
logger.error("Failed to compose MIME for message %s: %s", message.id, e)
return False
raise drf.exceptions.APIException(
_("Failed to compose email message.")
) from e

# Sign the message with DKIM
dkim_signature_header: Optional[bytes] = sign_message_dkim(
Expand All @@ -190,6 +198,28 @@ def prepare_outbound_message(
# Prepend the signature header
raw_mime_signed = dkim_signature_header + b"\r\n" + raw_mime

# Validate total outgoing email size against configured limit
total_message_size = len(raw_mime_signed)
if total_message_size > settings.MAX_OUTGOING_EMAIL_SIZE:
logger.error(
"Total message size for message %s exceeds limit: %d bytes (limit: %d bytes)",
message.id,
total_message_size,
settings.MAX_OUTGOING_EMAIL_SIZE,
)
raise drf.exceptions.ValidationError(
{
"message": _(
"Total message size (%(total_size)s bytes) exceeds maximum "
"allowed size of %(max_size)s bytes."
)
% {
"total_size": total_message_size,
"max_size": settings.MAX_OUTGOING_EMAIL_SIZE,
}
}
)

# Create a blob to store the raw MIME content
blob = mailbox_sender.create_blob(
content=raw_mime_signed,
Expand Down
Loading
Loading