Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JMAP Email/send create should use tooLarge when attempt to create an oversize mail #358

Merged
merged 2 commits into from
Mar 24, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
package com.linagora.tmail.james.common

import java.nio.charset.StandardCharsets
import java.time.Duration
import java.util.concurrent.TimeUnit

vttranlina marked this conversation as resolved.
Show resolved Hide resolved
import com.linagora.tmail.james.common.EncryptHelper.uploadPublicKey
import com.linagora.tmail.james.common.LinagoraEmailSendMethodContract.{BOB_INBOX_PATH, HTML_BODY}
import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
Expand Down Expand Up @@ -33,6 +29,9 @@ import org.awaitility.core.ConditionFactory
import org.junit.jupiter.api.{BeforeEach, Test}
import play.api.libs.json.{JsString, JsValue, Json}

import java.nio.charset.StandardCharsets
import java.time.Duration
import java.util.concurrent.TimeUnit
import scala.jdk.CollectionConverters._

object LinagoraEmailSendMethodContract {
Expand Down Expand Up @@ -1704,6 +1703,91 @@ trait LinagoraEmailSendMethodContract {
.inPath("methodResponses[1]")
.isAbsent()
}

@Test
def tooBigEmailsShouldBeRejected(server: GuiceJamesServer): Unit = {
val request: String =
s"""
|{
| "using": [
| "urn:ietf:params:jmap:core",
| "urn:ietf:params:jmap:mail",
| "urn:ietf:params:jmap:submission",
| "com:linagora:params:jmap:pgp"
| ],
| "methodCalls": [
| [
| "Email/send",
| {
| "accountId": "$ACCOUNT_ID",
| "create": {
| "K87": {
| "email/create": {
| "mailboxIds": {
| "${getBobInboxId(server).serialize}": true
| },
| "subject": "World domination",
| "htmlBody": [
| {
| "partId": "a49d",
| "type": "text/html"
| }
| ],
| "bodyValues": {
| "a49d": {
| "value": "${"0123456789\\r\\n".repeat(1024 * 1024)}",
| "isTruncated": false,
| "isEncodingProblem": false
| }
| }
| },
| "emailSubmission/set": {
| "envelope": {
| "mailFrom": {
| "email": "${BOB.asString}"
| },
| "rcptTo": [
| {
| "email": "${BOB.asString}"
| }
| ]
| }
| }
| }
| }
| },
| "c1"
| ]
| ]
|}""".stripMargin

val response: String = `given`
.body(request)
.when()
.post()
.`then`
.statusCode(HttpStatus.SC_OK)
.contentType(JSON)
.extract()
.body()
.asString()

assertThatJson(response)
.whenIgnoringPaths("methodResponses[0][1].notCreated.K87.description")
.inPath("methodResponses[0][1].notCreated.K87")
.isEqualTo(
s"""{
| "type": "tooLarge"
|}""".stripMargin)

val description = assertThatJson(response)
.withIgnorePlaceholder("@")
.inPath("methodResponses[0][1].notCreated.K87.description")
.asString()
description.endsWith(" bytes while the maximum allowed is 10485760")
description.startsWith("Attempt to create a message of ")
}

//endregion

//region basic valid request
Expand Down
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
package com.linagora.tmail.james.jmap.method

import java.time.ZonedDateTime
import java.util.Date

import com.google.inject.multibindings.{Multibinder, ProvidesIntoSet}
import com.google.inject.{AbstractModule, Scopes}
import com.linagora.tmail.james.jmap.json.EmailSendSerializer
import com.linagora.tmail.james.jmap.method.CapabilityIdentifier.LINAGORA_PGP
import com.linagora.tmail.james.jmap.model.EmailSubmissionHelper.resolveEnvelope
import com.linagora.tmail.james.jmap.model.{EmailSendCreationId, EmailSendCreationRequest, EmailSendCreationRequestInvalidException, EmailSendCreationResponse, EmailSendRequest, EmailSendResults, EmailSetCreationFailure, EmailSetCreationResult, EmailSetCreationSuccess, EmailSubmissionCreationRequest, MimeMessageSourceImpl}
import eu.timepit.refined.auto._
import javax.annotation.PreDestroy
import javax.inject.Inject
import javax.mail.Flags
import javax.mail.internet.{InternetAddress, MimeMessage}
import org.apache.james.core.{MailAddress, Username}
import org.apache.james.jmap.JMAPConfiguration
import org.apache.james.jmap.api.model.Size
import org.apache.james.jmap.core.CapabilityIdentifier.{CapabilityIdentifier, EMAIL_SUBMISSION, JMAP_CORE, JMAP_MAIL}
import org.apache.james.jmap.core.Invocation.{Arguments, MethodName}
import org.apache.james.jmap.core.{Invocation, UTCDate, UuidState}
import org.apache.james.jmap.json.{EmailSetSerializer, ResponseSerializer}
import org.apache.james.jmap.mail.{BlobId, EmailCreationRequest, EmailCreationResponse, EmailSubmissionId, Envelope, ThreadId}
import org.apache.james.jmap.method.EmailSubmissionSetMethod.{LOGGER, MAIL_METADATA_USERNAME_ATTRIBUTE}
import org.apache.james.jmap.method.{EmailSetMethod, ForbiddenFromException, ForbiddenMailFromException, InvocationWithContext, Method, MethodRequiringAccountId, NoRecipientException}
import org.apache.james.jmap.method.{EmailSetMethod, ForbiddenFromException, ForbiddenMailFromException, InvocationWithContext, Method, MethodRequiringAccountId, NoRecipientException, SizeExceededException}
import org.apache.james.jmap.routes.{BlobResolvers, ProcessingContext, SessionSupplier}
import org.apache.james.lifecycle.api.{LifecycleUtil, Startable}
import org.apache.james.mailbox.MessageManager.AppendCommand
Expand All @@ -36,13 +44,8 @@ import play.api.libs.json.{JsError, JsObject, JsSuccess}
import reactor.core.scala.publisher.{SFlux, SMono}
import reactor.core.scheduler.Schedulers

import java.time.ZonedDateTime
import java.util.Date
import javax.annotation.PreDestroy
import javax.inject.Inject
import javax.mail.Flags
import javax.mail.internet.{InternetAddress, MimeMessage}
import scala.jdk.CollectionConverters._
import scala.jdk.OptionConverters._
import scala.util.{Failure, Success, Try}

class EmailSendMethodModule extends AbstractModule {
Expand Down Expand Up @@ -70,6 +73,7 @@ class EmailSendMethod @Inject()(emailSetSerializer: EmailSetSerializer,
htmlTextExtractor: HtmlTextExtractor,
mailboxManager: MailboxManager,
emailSetMethod: EmailSetMethod,
configuration: JMAPConfiguration,
val metricFactory: MetricFactory,
val sessionSupplier: SessionSupplier) extends MethodRequiringAccountId[EmailSendRequest] with Startable {

Expand Down Expand Up @@ -203,7 +207,10 @@ class EmailSendMethod @Inject()(emailSetSerializer: EmailSetSerializer,
mailImpl.setMessageNoCopy(message)
mailImpl
})
_ <- SMono(queue.enqueueReactive(mail)).`then`(SMono.just(submissionId))
_ <- SMono(queue.enqueueReactive(mail))
.`then`(SMono.fromCallable(() => LifecycleUtil.dispose(mail))
.subscribeOn(Schedulers.elastic()))
.`then`(SMono.just(submissionId))
chibenwa marked this conversation as resolved.
Show resolved Hide resolved
} yield {
EmailSendCreationResponse(
emailSubmissionId = submissionId,
Expand Down Expand Up @@ -238,6 +245,7 @@ class EmailSendMethod @Inject()(emailSetSerializer: EmailSetSerializer,
}
}


private def append(clientId: EmailSendCreationId,
request: EmailCreationRequest,
message: Message,
Expand All @@ -246,12 +254,19 @@ class EmailSendMethod @Inject()(emailSetSerializer: EmailSetSerializer,
for {
mailbox <- SMono(mailboxManager.getMailboxReactive(mailboxIds.head, mailboxSession))
messageAsBytes = DefaultMessageWriter.asBytes(message)
appendCommand = AppendCommand.builder()
appendCommandEither = Right(AppendCommand.builder()
.recent()
.withFlags(request.keywords.map(_.asFlags).getOrElse(new Flags()))
.withInternalDate(Date.from(request.receivedAt.getOrElse(UTCDate(ZonedDateTime.now())).asUTC.toInstant))
.build(messageAsBytes)
appendResult <- SMono(mailbox.appendMessageReactive(appendCommand, mailboxSession))
.build(messageAsBytes))
.flatMap(appendCommand =>
configuration.getMaximumSendSize.toScala
.filter(limit => appendCommand.getMsgIn.size() > limit)
.map(limit => Left(SizeExceededException(appendCommand.getMsgIn.size(), limit)))
.getOrElse(Right(appendCommand)))

appendResult <- appendCommandEither.fold(SMono.error(_),
appendCommand => SMono(mailbox.appendMessageReactive(appendCommand, mailboxSession)))
} yield {
val blobId: Option[BlobId] = BlobId.of(appendResult.getId.getMessageId).toOption
val threadId: ThreadId = ThreadId.fromJava(appendResult.getThreadId)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import org.apache.james.jmap.core.SetError.SetErrorDescription
import org.apache.james.jmap.core.{AccountId, Id, Properties, SetError, UTCDate, UuidState}
import org.apache.james.jmap.json.EmailSetSerializer
import org.apache.james.jmap.mail.{BlobId, DestroyIds, EmailCreationRequest, EmailCreationResponse, EmailSet, EmailSetRequest, EmailSubmissionId, Envelope, ThreadId, UnparsedMessageId}
import org.apache.james.jmap.method.WithAccountId
import org.apache.james.jmap.method.{SizeExceededException, WithAccountId}
import org.apache.james.mailbox.MessageManager.AppendCommand
import org.apache.james.mailbox.model.MessageId
import org.apache.james.mime4j.dom.Message
Expand Down Expand Up @@ -221,7 +221,8 @@ object EmailSendResults {

def notCreated(emailSendCreationId: EmailSendCreationId, throwable: Throwable): EmailSendResults = {
val setError: SetError = throwable match {
case invalidException: EmailSendCreationRequestInvalidException =>invalidException.error
case invalidException: EmailSendCreationRequestInvalidException => invalidException.error
case exceededException: SizeExceededException => SetError.tooLarge(SetErrorDescription(exceededException.getMessage))
case error: Throwable => SetError.serverFail(SetErrorDescription(error.getMessage))
}
EmailSendResults(None, Some(Map(emailSendCreationId -> setError)), Map.empty)
Expand Down