Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
65 changes: 64 additions & 1 deletion src/backend/core/api/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@
"SCHEMA_CUSTOM_ATTRIBUTES_MAILDOMAIN": {
"type": "object",
"readOnly": true
},
"MAX_OUTGOING_ATTACHMENT_SIZE": {
"type": "integer",
"description": "Maximum size in bytes for outgoing email attachments",
"readOnly": true
},
"MAX_OUTGOING_BODY_SIZE": {
"type": "integer",
"description": "Maximum size in bytes for outgoing email body (text + HTML)",
"readOnly": true
}
},
"required": [
Expand All @@ -207,7 +217,9 @@
"FEATURE_AI_SUMMARY",
"FEATURE_AI_AUTOLABELS",
"SCHEMA_CUSTOM_ATTRIBUTES_USER",
"SCHEMA_CUSTOM_ATTRIBUTES_MAILDOMAIN"
"SCHEMA_CUSTOM_ATTRIBUTES_MAILDOMAIN",
"MAX_OUTGOING_ATTACHMENT_SIZE",
"MAX_OUTGOING_BODY_SIZE"
]
}
}
Expand Down Expand Up @@ -2384,6 +2396,57 @@
}
}
},
"/api/v1.0/mailboxes/{mailbox_id}/image-proxy/": {
"get": {
"operationId": "mailboxes_image_proxy_list",
"description": "Proxy an external image through the server.\n\n This endpoint fetches images from external sources and serves them\n through the application to protect user privacy. Requires the\n PROXY_EXTERNAL_IMAGES environment variable to be set to true.\n ",
"parameters": [
{
"in": "path",
"name": "mailbox_id",
"schema": {
"type": "string"
},
"description": "ID of the mailbox",
"required": true
},
{
"in": "query",
"name": "url",
"schema": {
"type": "string"
},
"description": "The external image URL to proxy",
"required": true
}
],
"tags": [
"mailboxes"
],
"security": [
{
"cookieAuth": []
}
],
"responses": {
"200": {
"description": "Image content"
},
"400": {
"description": "Invalid request"
},
"403": {
"description": "Forbidden"
},
"413": {
"description": "Image too large"
},
"502": {
"description": "Failed to fetch external image"
}
}
}
},
"/api/v1.0/mailboxes/{mailbox_id}/message-templates/": {
"get": {
"operationId": "mailboxes_message_templates_list",
Expand Down
16 changes: 16 additions & 0 deletions src/backend/core/api/viewsets/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ class ConfigView(drf.views.APIView):
"type": "object",
"readOnly": True,
},
"MAX_OUTGOING_ATTACHMENT_SIZE": {
"type": "integer",
"description": "Maximum size in bytes for outgoing email attachments",
"readOnly": True,
},
"MAX_OUTGOING_BODY_SIZE": {
"type": "integer",
"description": "Maximum size in bytes for outgoing email body (text + HTML)",
"readOnly": True,
},
},
"required": [
"ENVIRONMENT",
Expand All @@ -72,6 +82,8 @@ class ConfigView(drf.views.APIView):
"FEATURE_AI_AUTOLABELS",
"SCHEMA_CUSTOM_ATTRIBUTES_USER",
"SCHEMA_CUSTOM_ATTRIBUTES_MAILDOMAIN",
"MAX_OUTGOING_ATTACHMENT_SIZE",
"MAX_OUTGOING_BODY_SIZE",
],
},
)
Expand Down Expand Up @@ -100,6 +112,10 @@ def get(self, request):
dict_settings["FEATURE_AI_SUMMARY"] = is_ai_summary_enabled()
dict_settings["FEATURE_AI_AUTOLABELS"] = is_auto_labels_enabled()

# Email size limits
dict_settings["MAX_OUTGOING_ATTACHMENT_SIZE"] = settings.MAX_OUTGOING_ATTACHMENT_SIZE
dict_settings["MAX_OUTGOING_BODY_SIZE"] = settings.MAX_OUTGOING_BODY_SIZE

# Drive service
if base_url := settings.DRIVE_CONFIG.get("base_url"):
dict_settings.update(
Expand Down
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
67 changes: 64 additions & 3 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 All @@ -220,8 +222,28 @@ def update_draft(
except models.Blob.DoesNotExist:
pass
if update_data["draftBody"]:
draft_body_bytes = update_data["draftBody"].encode("utf-8")

# Validate body size before creating blob
if len(draft_body_bytes) > settings.MAX_OUTGOING_BODY_SIZE:
body_mb = len(draft_body_bytes) / 1_000_000
max_body_mb = settings.MAX_OUTGOING_BODY_SIZE / 1_000_000

raise drf.exceptions.ValidationError(
{
"draftBody": _(
"Message body size (%(body_size)s MB) exceeds the %(max_size)s MB limit. "
"Please reduce message content."
)
% {
"body_size": f"{body_mb:.1f}",
"max_size": f"{max_body_mb:.0f}",
}
}
)

message.draft_blob = mailbox.create_blob(
content=update_data["draftBody"].encode("utf-8"),
content=draft_body_bytes,
content_type="application/json",
)
updated_fields.append("draft_blob")
Expand Down Expand Up @@ -292,6 +314,45 @@ 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 attachment limit
total_attachment_size = current_total_size + new_total_size
if total_attachment_size > settings.MAX_OUTGOING_ATTACHMENT_SIZE:
# Convert to MB for better readability
total_mb = total_attachment_size / 1_000_000
max_mb = settings.MAX_OUTGOING_ATTACHMENT_SIZE / 1_000_000
current_mb = current_total_size / 1_000_000
new_mb = new_total_size / 1_000_000

raise drf.exceptions.ValidationError(
{
"attachments": _(
"Cannot add attachment(s) (%(new_size)s MB). "
"Total attachments would be %(total_size)s MB, exceeding the %(max_size)s MB limit. "
"Current attachments: %(current_size)s MB."
)
% {
"new_size": f"{new_mb:.1f}",
"total_size": f"{total_mb:.1f}",
"max_size": f"{max_mb:.0f}",
"current_size": f"{current_mb:.1f}",
}
}
)

# Remove attachments no longer in the list
if to_remove:
message.attachments.remove(*to_remove)
Expand Down
68 changes: 67 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 @@ -147,12 +150,48 @@ def prepare_outbound_message(
"message_id": message.mime_id,
}

# Calculate body size (raw text/HTML bytes) before MIME encoding
body_size = 0
if text_body:
body_size += len(text_body.encode('utf-8'))
if html_body:
body_size += len(html_body.encode('utf-8'))

# Validate body size against limit
if body_size > settings.MAX_OUTGOING_BODY_SIZE:
body_mb = body_size / 1_000_000
max_body_mb = settings.MAX_OUTGOING_BODY_SIZE / 1_000_000

logger.error(
"Message body size for message %s exceeds limit: %d bytes (limit: %d bytes)",
message.id,
body_size,
settings.MAX_OUTGOING_BODY_SIZE,
)
raise drf.exceptions.ValidationError(
{
"message": _(
"Message body size (%(body_size)s MB) exceeds the %(max_size)s MB limit. "
"Please reduce message content."
)
% {
"body_size": f"{body_mb:.1f}",
"max_size": f"{max_body_mb:.0f}",
}
}
)

# Calculate total content size (attachments + body)
total_content_size = body_size

# Add attachments if present
if message.attachments.exists():
attachments = []

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

# Add the attachment to the MIME data
attachments.append(
Expand All @@ -169,6 +208,31 @@ def prepare_outbound_message(
if attachments:
mime_data["attachments"] = attachments

# Validate total attachment size (before MIME encoding)
attachment_size = total_content_size - body_size
if attachment_size > settings.MAX_OUTGOING_ATTACHMENT_SIZE:
attachment_mb = attachment_size / 1_000_000
max_mb = settings.MAX_OUTGOING_ATTACHMENT_SIZE / 1_000_000

logger.error(
"Total attachment size for message %s exceeds limit: %d bytes (limit: %d bytes)",
message.id,
attachment_size,
settings.MAX_OUTGOING_ATTACHMENT_SIZE,
)
raise drf.exceptions.ValidationError(
{
"message": _(
"Total attachment size (%(total_size)s MB) exceeds the %(max_size)s MB limit. "
"Please reduce attachments."
)
% {
"total_size": f"{attachment_mb:.1f}",
"max_size": f"{max_mb:.0f}",
}
}
)

# Assemble the raw mime message
try:
raw_mime = compose_email(
Expand All @@ -178,7 +242,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 Down
Loading
Loading