Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
108 changes: 108 additions & 0 deletions src/backend/core/api/viewsets/inbound/widget.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
"""Widget channel implementation for receiving messages from web widgets."""

# Attachment handling imports.
import mimetypes
import uuid
from pathlib import Path
import base64

import logging
import re
from html import escape as html_escape
Expand Down Expand Up @@ -28,6 +34,35 @@
# Referer hosts we accept to put in the subject line: DNS names and IPv4.
_HOSTNAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9._-]{0,251}[a-z0-9])?$", re.IGNORECASE)

# Size limit for each attachment.
# Could be set in settings.
MAX_ATTACHMENT_SIZE = 5 * 1024 * 1024 # 5 MB per file

# Attachment handling helpers to compute filename and mime-type from incoming infos.
#
# resolve_mime_type("photo.jpg", "image/png") # 'image/png' (given type wins)
# resolve_mime_type("photo.jpg", None) # 'image/jpeg' (from extension)
# resolve_mime_type("photo", None) # 'application/octet-stream'
# resolve_mime_type(None, "") # 'application/octet-stream'
def resolve_mime_type(filename: str | None, mime_type: str | None) -> str:
if mime_type:
return mime_type
if filename:
guessed, _ = mimetypes.guess_type(filename)
if guessed:
return guessed
return "application/octet-stream"

# resolve_attachment(None, None) # ('3f2b8c…a6b.bin', 'application/octet-stream')
# resolve_attachment("report", "application/pdf") # ('report.pdf', 'application/pdf')
# resolve_attachment("photo.jpg", None) # ('photo.jpg', 'image/jpeg')
def resolve_attachment(filename: str | None, mime_type: str | None) -> tuple[str, str]:
mime = resolve_mime_type(filename, mime_type)
name = Path((filename or "").replace("\\", "/")).name or uuid.uuid4().hex
if not Path(name).suffix:
name += mimetypes.guess_extension(mime) or ".bin"
return name, mime
# [END] Attachment handling helpers

def _is_plausible_hostname(hostname: str) -> bool:
"""True when a Referer host is safe to render as the ticket source."""
Expand Down Expand Up @@ -245,6 +280,77 @@ def sanitize_header(header: str) -> str:
# Sanitize subject to prevent header injection (strip newlines/carriage returns)
subject = subject.replace("\r", "").replace("\n", "")

# Add attachments if any.
# Received attachments are structured as follow:
# [{ "type": "application/octet-stream",
# "name": pdf.name,
# "disposition": "attachment",
# "content": base64_encoded_content(),}]
#
# JMAP attachements must be structured as follow:
# [{
# "name": "invoice.pdf",
# "type": "application/pdf",
# "content": raw_bytes_content(),
# "disposition": "attachment",
# }]

# Get optional attachments, fallback to empty list if no attachments exist.
incoming_attachments = data.get("attachments") or []
Comment thread
NicolasBuquet marked this conversation as resolved.
Resolved
# Check that incoming_attachments is a list.
if not isinstance(incoming_attachments, list):
return Response(
{"detail": "Invalid attachments"}, status=status.HTTP_400_BAD_REQUEST
)
# prepare outgoing attachments list that will stay empty if no attachment exists.
outgoing_attachments = []
attachments_total_bytes = 0

for src_att in incoming_attachments:
# Check that each incoming attachment is a dict and their content is a string.
if not isinstance(src_att, dict) or not isinstance(src_att.get("content"), str):
return Response(
{"detail": "Invalid attachment"}, status=status.HTTP_400_BAD_REQUEST
)
name = src_att.get("name") if isinstance(src_att.get("name"), str) else None
mime = src_att.get("type") if isinstance(src_att.get("type"), str) else None
b64_encoded_content = src_att["content"]

# Check if attachment size exceeds the limit.
# base64 is ~4/3 the decoded size: reject early without decoding a huge string
# Django has its own DATA_UPLOAD_MAX_MEMORY_SIZE that will reject large uploads if exceeded.
if len(b64_encoded_content) * 3 // 4 > MAX_ATTACHMENT_SIZE:
Comment thread
NicolasBuquet marked this conversation as resolved.
Resolved
return Response(
{"detail": "Attachment too large"}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
)
try:
base64_decoded_content = base64.b64decode(b64_encoded_content, validate=True)
except ValueError: # binascii.Error subclasses ValueError
return Response(
{"detail": "Invalid attachment encoding"}, status=status.HTTP_400_BAD_REQUEST,
)
# Reject empty attachment.
if not base64_decoded_content:
return Response(
{"detail": "Attachment is empty"}, status=status.HTTP_400_BAD_REQUEST
)

# Reject if this attachment or total attachments size is too big.
attachments_total_bytes += len(base64_decoded_content)
if len(base64_decoded_content) > MAX_ATTACHMENT_SIZE or attachments_total_bytes > settings.MAX_INCOMING_EMAIL_SIZE:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return Response(
{"detail": "Attachment too large"}, status=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
)

att_name, att_type = resolve_attachment(name, mime)
outgoing_attachments.append({
"name": att_name,
"type": att_type,
"disposition": "attachment",
# raw bytes as `Mailbox.create_blob()` method (called by `_process_attachments`) expects.
"content": base64_decoded_content,
})

# Build a JMAP-like structured format that we could have got from parse_email()

parsed_email = {
Expand All @@ -254,6 +360,8 @@ def sanitize_header(header: str) -> str:
"sentAt": current_sent_at(),
"htmlBody": [{"content": html_escape(message_text).replace("\n", "<br/>")}],
"textBody": [{"content": message_text}],
# Add attachments if any.
"attachments": outgoing_attachments,
}

# A widget submission is delivered to a local mailbox, never
Expand Down
74 changes: 37 additions & 37 deletions src/backend/core/mda/inbound_create.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,8 +591,8 @@ def _create_message_from_inbound( # pylint: disable=too-many-arguments
# Log and continue

# --- 7. Process Attachments if present --- #
# if parsed_email.get("attachments"):
# _process_attachments(message, parsed_email["attachments"], mailbox)
if parsed_email.get("attachments"):
_process_attachments(message, parsed_email["attachments"], mailbox)

# --- 8. Final Updates --- #
try:
Expand Down Expand Up @@ -646,38 +646,38 @@ def _create_message_from_inbound( # pylint: disable=too-many-arguments
return message # Return created Message on success (truthy), None on failure


# def _process_attachments(
# message: models.Message, attachment_data: list[Dict], mailbox: models.Mailbox
# ) -> None:
# """
# Process attachments found during email parsing.

# Creates Blob records for each attachment and links them to the message.

# Args:
# message: The message object to link attachments to
# attachment_data: List of attachment data dictionaries from parsing
# mailbox: The mailbox that owns these attachments
# """
# for attachment_info in attachment_data:
# try:
# # Check if we have content to store
# if "content" in attachment_info and attachment_info["content"]:
# # Create a blob for this attachment using the mailbox method
# content = attachment_info["content"]
# blob = mailbox.create_blob(
# content=content,
# content_type=attachment_info["type"],
# )

# # Create an attachment record linking to this blob
# attachment = models.Attachment.objects.create(
# name=attachment_info.get("name", "unnamed"),
# blob=blob,
# mailbox=mailbox,
# )

# # Link the attachment to the message
# message.attachments.add(attachment)
# except Exception as e:
# logger.exception("Error processing attachment: %s", e)
def _process_attachments(
message: models.Message, attachment_data: list[dict], mailbox: models.Mailbox
) -> None:
"""
Process attachments found during email parsing.

Creates Blob records for each attachment and links them to the message.

Args:
message: The message object to link attachments to
attachment_data: List of attachment data dictionaries from parsing
mailbox: The mailbox that owns these attachments
"""
for attachment_info in attachment_data:
try:
# Check if we have content to store
if "content" in attachment_info and attachment_info["content"]:
# Create a blob for this attachment using the mailbox method
content = attachment_info["content"]
blob = mailbox.create_blob(
content=content,
content_type=attachment_info["type"],
Comment thread
NicolasBuquet marked this conversation as resolved.
Resolved
)

# Create an attachment record linking to this blob
attachment = models.Attachment.objects.create(
name=attachment_info.get("name", "unnamed"),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
blob=blob,
mailbox=mailbox,
)
Comment thread
NicolasBuquet marked this conversation as resolved.
Resolved

# Link the attachment to the message
message.attachments.add(attachment)
except Exception as e:
logger.exception("Error processing attachment: %s", e)