You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by bt...@apache.org on 2020/11/16 01:50:44 UTC

[james-project] 04/05: JAMES-3432 Enforce the usage of RFC-7807 (problem details) for HTTP level errors

This is an automated email from the ASF dual-hosted git repository.

btellier pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git

commit 8bdf6254886301ae9a8fac6bf3dfc9af5badb751
Author: Benoit Tellier <bt...@linagora.com>
AuthorDate: Fri Nov 13 10:44:57 2020 +0700

    JAMES-3432 Enforce the usage of RFC-7807 (problem details) for HTTP level errors
    
    Covers API, session, upload, download routes.
    
    Also I took this opportunity to make a distinction between 401
    (authentication issues) and 403 (forbidden)
    
    Some error messages were enhanced as well...
---
 .../rfc8621/contract/AuthenticationContract.scala  | 24 +++++++++++++
 .../jmap/rfc8621/contract/DownloadContract.scala   | 39 +++++++++++++++++++--
 .../jmap/rfc8621/contract/UploadContract.scala     | 27 +++++++++------
 .../apache/james/jmap/core/ProblemDetails.scala    | 20 ++++++-----
 .../james/jmap/core/RequestLevelErrorType.scala    |  1 +
 .../org/apache/james/jmap/core/StatusCode.scala    | 27 ---------------
 .../james/jmap/json/ResponseSerializer.scala       |  2 ++
 .../apache/james/jmap/routes/DownloadRoutes.scala  | 40 +++++++++++++++++-----
 .../apache/james/jmap/routes/JMAPApiRoutes.scala   | 31 +++++++++++------
 .../apache/james/jmap/routes/SessionRoutes.scala   | 28 +++++++++++----
 .../apache/james/jmap/routes/UploadRoutes.scala    | 40 +++++++++++++++++-----
 .../org/apache/james/jmap/http/Authenticator.java  |  2 +-
 12 files changed, 196 insertions(+), 85 deletions(-)

diff --git a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/AuthenticationContract.scala b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/AuthenticationContract.scala
index 247ad48..5cb8956 100644
--- a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/AuthenticationContract.scala
+++ b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/AuthenticationContract.scala
@@ -28,6 +28,7 @@ import org.apache.james.GuiceJamesServer
 import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ALICE, ALICE_PASSWORD, AUTHORIZATION_HEADER, BOB, BOB_BASIC_AUTH_HEADER, BOB_PASSWORD, DOMAIN, DOMAIN_WITH_SPACE, ECHO_REQUEST_OBJECT, INVALID_JWT_TOKEN, UNKNOWN_USER_TOKEN, USER_TOKEN, getHeadersWith, toBase64, _}
 import org.apache.james.jmap.rfc8621.contract.tags.CategoryTags
 import org.apache.james.utils.DataProbeImpl
+import org.hamcrest.Matchers.{containsString, equalTo}
 import org.junit.jupiter.api.{BeforeAll, Nested, Tag, Test}
 
 object AuthenticationContract {
@@ -61,6 +62,8 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_BAD_REQUEST)
+        .body("status", equalTo(400))
+        .body("detail", containsString("Only one set of credential is allowed"))
     }
   }
 
@@ -75,6 +78,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("No valid authentication methods provided"))
     }
 
     @Test
@@ -99,6 +105,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("Username is not valid"))
     }
 
     @Test
@@ -123,6 +132,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("No valid authentication methods provided"))
     }
 
     @Test
@@ -135,6 +147,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("No valid authentication methods provided"))
     }
 
     @Test
@@ -148,6 +163,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("No valid authentication methods provided"))
     }
   }
 
@@ -176,6 +194,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("Failed Jwt verification"))
     }
 
     @Test
@@ -188,6 +209,9 @@ trait AuthenticationContract {
         .post
       .`then`
         .statusCode(SC_UNAUTHORIZED)
+        .body("status", equalTo(401))
+        .body("type", equalTo("about:blank"))
+        .body("detail", equalTo("Failed Jwt verification"))
     }
   }
 }
diff --git a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/DownloadContract.scala b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/DownloadContract.scala
index f10ef4d..ef200a3 100644
--- a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/DownloadContract.scala
+++ b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/DownloadContract.scala
@@ -25,7 +25,7 @@ import java.nio.charset.StandardCharsets
 import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
 import io.restassured.RestAssured.{`given`, requestSpecification}
 import org.apache.commons.io.IOUtils
-import org.apache.http.HttpStatus.{SC_NOT_FOUND, SC_OK, SC_UNAUTHORIZED}
+import org.apache.http.HttpStatus.{SC_FORBIDDEN, SC_NOT_FOUND, SC_OK, SC_UNAUTHORIZED}
 import org.apache.james.GuiceJamesServer
 import org.apache.james.jmap.http.UserCredential
 import org.apache.james.jmap.rfc8621.contract.DownloadContract.accountId
@@ -36,7 +36,7 @@ import org.apache.james.mailbox.model.{MailboxACL, MailboxPath, MessageId}
 import org.apache.james.modules.{ACLProbeImpl, MailboxProbeImpl}
 import org.apache.james.utils.DataProbeImpl
 import org.assertj.core.api.Assertions.assertThat
-import org.hamcrest.Matchers.containsString
+import org.hamcrest.Matchers.{containsString, equalTo}
 import org.junit.jupiter.api.{BeforeEach, Test}
 
 object DownloadContract {
@@ -103,6 +103,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}")
     .`then`
       .statusCode(SC_UNAUTHORIZED)
+      .body("status", equalTo(401))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("No valid authentication methods provided"))
   }
 
   @Test
@@ -150,6 +153,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -167,7 +173,10 @@ trait DownloadContract {
     .when
       .get(s"/download/$ALICE_ACCOUNT_ID/${messageId.serialize}")
     .`then`
-      .statusCode(SC_UNAUTHORIZED)
+      .statusCode(SC_FORBIDDEN)
+      .body("status", equalTo(403))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("You cannot upload in others accounts"))
   }
 
   @Test
@@ -220,6 +229,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}_3")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -393,6 +405,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}_333")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -411,6 +426,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}_invalid")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -428,6 +446,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/invalid")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -445,6 +466,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${randomMessageId.serialize()}")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -462,6 +486,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${randomMessageId.serialize()}_3")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -479,6 +506,9 @@ trait DownloadContract {
       .get(s"/download/$accountId/${randomMessageId.serialize()}_2")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 
   @Test
@@ -497,5 +527,8 @@ trait DownloadContract {
       .get(s"/download/$accountId/${messageId.serialize()}_3_3")
     .`then`
       .statusCode(SC_NOT_FOUND)
+      .body("status", equalTo(404))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("The resource could not be found"))
   }
 }
diff --git a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/UploadContract.scala b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/UploadContract.scala
index fe35d0f..c28696d 100644
--- a/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/UploadContract.scala
+++ b/server/protocols/jmap-rfc-8621-integration-tests/jmap-rfc-8621-integration-tests-common/src/main/scala/org/apache/james/jmap/rfc8621/contract/UploadContract.scala
@@ -25,13 +25,14 @@ import io.netty.handler.codec.http.HttpHeaderNames.ACCEPT
 import io.restassured.RestAssured.{`given`, requestSpecification}
 import io.restassured.http.ContentType
 import org.apache.commons.io.IOUtils
-import org.apache.http.HttpStatus.{SC_BAD_REQUEST, SC_CREATED, SC_OK, SC_UNAUTHORIZED}
+import org.apache.http.HttpStatus.{SC_BAD_REQUEST, SC_CREATED, SC_FORBIDDEN, SC_OK, SC_UNAUTHORIZED}
 import org.apache.james.GuiceJamesServer
 import org.apache.james.jmap.http.UserCredential
-import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ACCOUNT_ID, ALICE, ALICE_ACCOUNT_ID, ALICE_PASSWORD, BOB, BOB_PASSWORD, DOMAIN, RFC8621_VERSION_HEADER, _2_DOT_DOMAIN, authScheme, baseRequestSpecBuilder}
+import org.apache.james.jmap.rfc8621.contract.Fixture.{ACCEPT_RFC8621_VERSION_HEADER, ACCOUNT_ID, ALICE, ALICE_ACCOUNT_ID, ALICE_PASSWORD, BOB, BOB_PASSWORD, DOMAIN, _2_DOT_DOMAIN, authScheme, baseRequestSpecBuilder}
 import org.apache.james.jmap.rfc8621.contract.UploadContract.{BIG_INPUT_STREAM, VALID_INPUT_STREAM}
 import org.apache.james.utils.DataProbeImpl
 import org.assertj.core.api.Assertions.assertThat
+import org.hamcrest.Matchers.equalTo
 import org.junit.jupiter.api.{BeforeEach, Test}
 import play.api.libs.json.{JsString, Json}
 
@@ -97,7 +98,10 @@ trait UploadContract {
     .when
       .post(s"/upload/$ALICE_ACCOUNT_ID/")
     .`then`
-      .statusCode(SC_UNAUTHORIZED)
+      .statusCode(SC_FORBIDDEN)
+      .body("status", equalTo(403))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("Upload to other accounts is forbidden"))
   }
 
   @Test
@@ -124,11 +128,14 @@ trait UploadContract {
       .get(s"/download/$ALICE_ACCOUNT_ID/$blobId")
     .`then`
       .statusCode(SC_UNAUTHORIZED)
+      .body("status", equalTo(401))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("No valid authentication methods provided"))
   }
 
   @Test
   def shouldRejectWhenUploadFileTooBig(): Unit = {
-    val response: String = `given`
+    `given`
       .basePath("")
       .header(ACCEPT.toString, ACCEPT_RFC8621_VERSION_HEADER)
       .contentType(ContentType.BINARY)
@@ -137,12 +144,9 @@ trait UploadContract {
       .post(s"/upload/$ACCOUNT_ID/")
     .`then`
       .statusCode(SC_BAD_REQUEST)
-      .extract
-      .body
-      .asString
-
-    assertThat(response)
-      .contains("Attempt to upload exceed max size")
+      .body("status", equalTo(400))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("Attempt to upload exceed max size"))
   }
 
   @Test
@@ -158,5 +162,8 @@ trait UploadContract {
       .post(s"/upload/$ACCOUNT_ID/")
     .`then`
       .statusCode(SC_UNAUTHORIZED)
+      .body("status", equalTo(401))
+      .body("type", equalTo("about:blank"))
+      .body("detail", equalTo("No valid authentication methods provided"))
   }
 }
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/ProblemDetails.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/ProblemDetails.scala
index 4d864d9..9547f00 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/ProblemDetails.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/ProblemDetails.scala
@@ -18,21 +18,23 @@
  ****************************************************************/
 package org.apache.james.jmap.core
 
-import eu.timepit.refined.auto._
-import org.apache.http.HttpStatus.SC_BAD_REQUEST
-import org.apache.james.jmap.core.RequestLevelErrorType.ErrorTypeIdentifier
-import org.apache.james.jmap.core.StatusCode.ErrorStatus
+import io.netty.handler.codec.http.HttpResponseStatus
+import io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST
+import org.apache.james.jmap.core.RequestLevelErrorType.{DEFAULT_ERROR_TYPE, ErrorTypeIdentifier}
 
 /**
  * Problem Details for HTTP APIs within the JMAP context
  * https://tools.ietf.org/html/rfc7807
  * see https://jmap.io/spec-core.html#errors
  */
-case class ProblemDetails(`type`: ErrorTypeIdentifier, status: ErrorStatus, limit: Option[String], detail: String)
+case class ProblemDetails(`type`: ErrorTypeIdentifier = DEFAULT_ERROR_TYPE,
+                          status: HttpResponseStatus,
+                          limit: Option[String] = None,
+                          detail: String)
 
 object ProblemDetails {
-  def notRequestProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.NOT_REQUEST, SC_BAD_REQUEST, None, message)
-  def notJSONProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.NOT_JSON, SC_BAD_REQUEST, None, message)
-  def unknownCapabilityProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.UNKNOWN_CAPABILITY, SC_BAD_REQUEST, None, message)
-  def invalidResultReference(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.UNKNOWN_CAPABILITY, SC_BAD_REQUEST, None, message)
+  def notRequestProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.NOT_REQUEST, BAD_REQUEST, None, message)
+  def notJSONProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.NOT_JSON, BAD_REQUEST, None, message)
+  def unknownCapabilityProblem(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.UNKNOWN_CAPABILITY, BAD_REQUEST, None, message)
+  def invalidResultReference(message: String): ProblemDetails = ProblemDetails(RequestLevelErrorType.UNKNOWN_CAPABILITY, BAD_REQUEST, None, message)
 }
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/RequestLevelErrorType.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/RequestLevelErrorType.scala
index 9fc0e43..1397a16 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/RequestLevelErrorType.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/RequestLevelErrorType.scala
@@ -28,4 +28,5 @@ object RequestLevelErrorType {
   val NOT_JSON: ErrorTypeIdentifier = "urn:ietf:params:jmap:error:notJSON"
   val NOT_REQUEST: ErrorTypeIdentifier = "urn:ietf:params:jmap:error:notRequest"
   val LIMIT: ErrorTypeIdentifier = "urn:ietf:params:jmap:error:limit"
+  val DEFAULT_ERROR_TYPE: ErrorTypeIdentifier = "about:blank"
 }
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/StatusCode.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/StatusCode.scala
deleted file mode 100644
index 64661d5..0000000
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/core/StatusCode.scala
+++ /dev/null
@@ -1,27 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one   *
- * or more contributor license agreements.  See the NOTICE file *
- * distributed with this work for additional information        *
- * regarding copyright ownership.  The ASF licenses this file   *
- * to you under the Apache License, Version 2.0 (the            *
- * "License"); you may not use this file except in compliance   *
- * with the License.  You may obtain a copy of the License at   *
- *                                                              *
- *   http://www.apache.org/licenses/LICENSE-2.0                 *
- *                                                              *
- * Unless required by applicable law or agreed to in writing,   *
- * software distributed under the License is distributed on an  *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
- * KIND, either express or implied.  See the License for the    *
- * specific language governing permissions and limitations      *
- * under the License.                                           *
- ****************************************************************/
-
-package org.apache.james.jmap.core
-
-import eu.timepit.refined.api.Refined
-import eu.timepit.refined.numeric.Interval.Closed
-
-object StatusCode {
-  type ErrorStatus = Int Refined Closed[100, 599]
-}
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/json/ResponseSerializer.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/json/ResponseSerializer.scala
index 6d69b4e..2afc1bb 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/json/ResponseSerializer.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/json/ResponseSerializer.scala
@@ -23,6 +23,7 @@ import java.io.InputStream
 import java.net.URL
 
 import eu.timepit.refined.refineV
+import io.netty.handler.codec.http.HttpResponseStatus
 import org.apache.james.core.Username
 import org.apache.james.jmap.core
 import org.apache.james.jmap.core.CapabilityIdentifier.CapabilityIdentifier
@@ -60,6 +61,7 @@ object ResponseSerializer {
 
   private implicit val invocationWrite: Writes[Invocation] = (invocation: Invocation) =>
     Json.arr(invocation.methodName, invocation.arguments, invocation.methodCallId)
+  private implicit val statusWrite: Writes[HttpResponseStatus] = status => JsNumber(status.code())
 
   // RequestObject
   private implicit val requestObjectRead: Format[RequestObject] = Json.format[RequestObject]
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/DownloadRoutes.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/DownloadRoutes.scala
index 6188757..dedc483 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/DownloadRoutes.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/DownloadRoutes.scala
@@ -19,6 +19,7 @@
 package org.apache.james.jmap.routes
 
 import java.io.{ByteArrayInputStream, ByteArrayOutputStream, InputStream}
+import java.nio.charset.StandardCharsets
 import java.util.stream
 import java.util.stream.Stream
 
@@ -27,15 +28,16 @@ import eu.timepit.refined.numeric.NonNegative
 import eu.timepit.refined.refineV
 import io.netty.buffer.Unpooled
 import io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE
-import io.netty.handler.codec.http.HttpResponseStatus.OK
-import io.netty.handler.codec.http.{HttpMethod, QueryStringDecoder}
+import io.netty.handler.codec.http.HttpResponseStatus.{BAD_REQUEST, FORBIDDEN, INTERNAL_SERVER_ERROR, NOT_FOUND, OK, UNAUTHORIZED}
+import io.netty.handler.codec.http.{HttpMethod, HttpResponseStatus, QueryStringDecoder}
 import javax.inject.{Inject, Named}
-import org.apache.http.HttpStatus.SC_NOT_FOUND
+import org.apache.james.jmap.HttpConstants.JSON_CONTENT_TYPE
 import org.apache.james.jmap.core.Id.Id
-import org.apache.james.jmap.core.{AccountId, Id}
+import org.apache.james.jmap.core.{AccountId, Id, ProblemDetails}
 import org.apache.james.jmap.exceptions.UnauthorizedException
 import org.apache.james.jmap.http.Authenticator
 import org.apache.james.jmap.http.rfc8621.InjectionKeys
+import org.apache.james.jmap.json.ResponseSerializer
 import org.apache.james.jmap.mail.Email.Size
 import org.apache.james.jmap.mail.{BlobId, EmailBodyPart, PartId}
 import org.apache.james.jmap.routes.DownloadRoutes.{BUFFER_SIZE, LOGGER}
@@ -84,6 +86,7 @@ trait Blob {
 }
 
 case class BlobNotFoundException(blobId: BlobId) extends RuntimeException
+case class ForbiddenException() extends RuntimeException
 
 case class MessageBlob(blobId: BlobId, message: MessageResult) extends Blob {
   override def contentType: ContentType = new ContentType("message/rfc822")
@@ -212,11 +215,24 @@ class DownloadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator:
     SMono(authenticator.authenticate(request))
       .flatMap(mailboxSession => getIfOwner(request, response, mailboxSession))
       .onErrorResume {
-        case e: UnauthorizedException => SMono.fromPublisher(handleAuthenticationFailure(response, LOGGER, e)).`then`
-        case _: BlobNotFoundException => SMono.fromPublisher(response.status(SC_NOT_FOUND).send).`then`
+        case e: ForbiddenException =>
+          respondDetails(response,
+            ProblemDetails(status = FORBIDDEN, detail = "You cannot upload in others accounts"),
+            FORBIDDEN)
+        case e: UnauthorizedException =>
+          LOGGER.warn("Unauthorized", e)
+          respondDetails(response,
+            ProblemDetails(status = UNAUTHORIZED, detail = e.getMessage),
+            UNAUTHORIZED)
+        case _: BlobNotFoundException =>
+          respondDetails(response,
+            ProblemDetails(status = NOT_FOUND, detail = "The resource could not be found"),
+            NOT_FOUND)
         case e =>
-          LOGGER.error("Unexpected error", e)
-          SMono.fromPublisher(handleInternalError(response, LOGGER, e)).`then`
+          LOGGER.error("Unexpected error upon downloads", e)
+          respondDetails(response,
+            ProblemDetails(status = INTERNAL_SERVER_ERROR, detail = e.getMessage),
+            INTERNAL_SERVER_ERROR)
       }
       .subscribeOn(Schedulers.elastic)
       .asJava()
@@ -245,7 +261,7 @@ class DownloadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator:
             value => if (value) {
               get(request, response, mailboxSession)
             } else {
-              SMono.raiseError(new UnauthorizedException("You cannot upload to others"))
+              SMono.raiseError(ForbiddenException())
             })
       }
 
@@ -295,4 +311,10 @@ class DownloadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator:
       .toList
       .flatMap(_.asScala)
       .headOption
+
+  private def respondDetails(httpServerResponse: HttpServerResponse, details: ProblemDetails, statusCode: HttpResponseStatus = BAD_REQUEST): SMono[Unit] =
+    SMono.fromPublisher(httpServerResponse.status(statusCode)
+      .header(CONTENT_TYPE, JSON_CONTENT_TYPE)
+      .sendString(SMono.fromCallable(() => ResponseSerializer.serialize(details).toString), StandardCharsets.UTF_8)
+      .`then`).`then`
 }
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/JMAPApiRoutes.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/JMAPApiRoutes.scala
index 1e34ed7..af001c3 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/JMAPApiRoutes.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/JMAPApiRoutes.scala
@@ -25,10 +25,9 @@ import java.util.stream.Stream
 
 import com.fasterxml.jackson.core.JsonParseException
 import io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE
-import io.netty.handler.codec.http.HttpMethod
-import io.netty.handler.codec.http.HttpResponseStatus.OK
+import io.netty.handler.codec.http.HttpResponseStatus.{BAD_REQUEST, INTERNAL_SERVER_ERROR, OK, UNAUTHORIZED}
+import io.netty.handler.codec.http.{HttpMethod, HttpResponseStatus}
 import javax.inject.{Inject, Named}
-import org.apache.http.HttpStatus.SC_BAD_REQUEST
 import org.apache.james.jmap.HttpConstants.JSON_CONTENT_TYPE
 import org.apache.james.jmap.JMAPUrls.JMAP
 import org.apache.james.jmap.core.CapabilityIdentifier.CapabilityIdentifier
@@ -40,6 +39,7 @@ import org.apache.james.jmap.http.rfc8621.InjectionKeys
 import org.apache.james.jmap.http.{Authenticator, MailboxesProvisioner, UserProvisioning}
 import org.apache.james.jmap.json.ResponseSerializer
 import org.apache.james.jmap.method.{InvocationWithContext, Method}
+import org.apache.james.jmap.routes.DownloadRoutes.LOGGER
 import org.apache.james.jmap.{Endpoint, JMAPRoute, JMAPRoutes}
 import org.apache.james.mailbox.MailboxSession
 import org.slf4j.{Logger, LoggerFactory}
@@ -175,21 +175,30 @@ class JMAPApiRoutes (val authenticator: Authenticator,
     }
   }
 
-  private def handleError(throwable: Throwable, httpServerResponse: HttpServerResponse): SMono[Void] = throwable match {
-    case exception: IllegalArgumentException => respondDetails(httpServerResponse,
+  private def handleError(throwable: Throwable, response: HttpServerResponse): SMono[Void] = throwable match {
+    case exception: IllegalArgumentException => respondDetails(response,
       notRequestProblem(
         s"The request was successfully parsed as JSON but did not match the type signature of the Request object: ${exception.getMessage}"))
-    case exception: UnauthorizedException => SMono(handleAuthenticationFailure(httpServerResponse, JMAPApiRoutes.LOGGER, exception))
-    case exception: JsonParseException => respondDetails(httpServerResponse,
+
+    case e: UnauthorizedException =>
+      LOGGER.warn("Unauthorized", e)
+      respondDetails(response,
+        ProblemDetails(status = UNAUTHORIZED, detail = e.getMessage),
+        UNAUTHORIZED)
+    case exception: JsonParseException => respondDetails(response,
       notJSONProblem(
         s"The content type of the request was not application/json or the request did not parse as I-JSON: ${exception.getMessage}"))
-    case exception: UnsupportedCapabilitiesException => respondDetails(httpServerResponse,
+    case exception: UnsupportedCapabilitiesException => respondDetails(response,
       unknownCapabilityProblem(s"The request used unsupported capabilities: ${exception.capabilities}"))
-    case _ => SMono.fromPublisher(handleInternalError(httpServerResponse, JMAPApiRoutes.LOGGER, throwable))
+    case e =>
+      LOGGER.error("Unexpected error upon API request", e)
+      respondDetails(response,
+        ProblemDetails(status = INTERNAL_SERVER_ERROR, detail = e.getMessage),
+        INTERNAL_SERVER_ERROR)
   }
 
-  private def respondDetails(httpServerResponse: HttpServerResponse, details: ProblemDetails): SMono[Void] =
-    SMono.fromPublisher(httpServerResponse.status(SC_BAD_REQUEST)
+  private def respondDetails(httpServerResponse: HttpServerResponse, details: ProblemDetails, statusCode: HttpResponseStatus = BAD_REQUEST): SMono[Void] =
+    SMono.fromPublisher(httpServerResponse.status(statusCode)
       .header(CONTENT_TYPE, JSON_CONTENT_TYPE)
       .sendString(SMono.fromCallable(() => ResponseSerializer.serialize(details).toString),
         StandardCharsets.UTF_8)
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/SessionRoutes.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/SessionRoutes.scala
index 080029d..4c20cea 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/SessionRoutes.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/SessionRoutes.scala
@@ -19,15 +19,16 @@
 
 package org.apache.james.jmap.routes
 
+import java.nio.charset.StandardCharsets
 import java.util.stream.Stream
 
 import io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE
-import io.netty.handler.codec.http.HttpMethod
-import io.netty.handler.codec.http.HttpResponseStatus.OK
+import io.netty.handler.codec.http.HttpResponseStatus.{BAD_REQUEST, INTERNAL_SERVER_ERROR, OK, UNAUTHORIZED}
+import io.netty.handler.codec.http.{HttpMethod, HttpResponseStatus}
 import javax.inject.{Inject, Named}
-import org.apache.james.jmap.HttpConstants.JSON_CONTENT_TYPE_UTF8
+import org.apache.james.jmap.HttpConstants.{JSON_CONTENT_TYPE, JSON_CONTENT_TYPE_UTF8}
 import org.apache.james.jmap.JMAPRoutes.CORS_CONTROL
-import org.apache.james.jmap.core.Session
+import org.apache.james.jmap.core.{ProblemDetails, Session}
 import org.apache.james.jmap.exceptions.UnauthorizedException
 import org.apache.james.jmap.http.Authenticator
 import org.apache.james.jmap.http.rfc8621.InjectionKeys
@@ -88,7 +89,22 @@ class SessionRoutes @Inject() (@Named(InjectionKeys.RFC_8621) val authenticator:
 
   def errorHandling(throwable: Throwable, response: HttpServerResponse): Mono[Void] =
     throwable match {
-      case _: UnauthorizedException => handleAuthenticationFailure(response, LOGGER, throwable)
-      case _ => handleInternalError(response, LOGGER, throwable)
+      case e: UnauthorizedException =>
+        LOGGER.warn("Unauthorized", e)
+        respondDetails(response,
+          ProblemDetails(status = UNAUTHORIZED, detail = e.getMessage),
+          UNAUTHORIZED)
+      case e =>
+        LOGGER.error("Unexpected error upon requesting session", e)
+        respondDetails(response,
+          ProblemDetails(status = INTERNAL_SERVER_ERROR, detail = e.getMessage),
+          INTERNAL_SERVER_ERROR)
     }
+
+
+  private def respondDetails(httpServerResponse: HttpServerResponse, details: ProblemDetails, statusCode: HttpResponseStatus = BAD_REQUEST): Mono[Void] =
+    httpServerResponse.status(statusCode)
+      .header(CONTENT_TYPE, JSON_CONTENT_TYPE)
+      .sendString(SMono.fromCallable(() => ResponseSerializer.serialize(details).toString), StandardCharsets.UTF_8)
+      .`then`
 }
diff --git a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/UploadRoutes.scala b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/UploadRoutes.scala
index 2f084c6..5617079 100644
--- a/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/UploadRoutes.scala
+++ b/server/protocols/jmap-rfc-8621/src/main/scala/org/apache/james/jmap/routes/UploadRoutes.scala
@@ -20,6 +20,7 @@
 package org.apache.james.jmap.routes
 
 import java.io.InputStream
+import java.nio.charset.StandardCharsets
 import java.util.stream
 import java.util.stream.Stream
 
@@ -28,16 +29,17 @@ import eu.timepit.refined.auto._
 import eu.timepit.refined.numeric.NonNegative
 import eu.timepit.refined.refineV
 import io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE
-import io.netty.handler.codec.http.HttpMethod
-import io.netty.handler.codec.http.HttpResponseStatus.{BAD_REQUEST, CREATED}
+import io.netty.handler.codec.http.HttpResponseStatus.{BAD_REQUEST, CREATED, FORBIDDEN, INTERNAL_SERVER_ERROR, UNAUTHORIZED}
+import io.netty.handler.codec.http.{HttpMethod, HttpResponseStatus}
 import javax.inject.{Inject, Named}
 import org.apache.commons.fileupload.util.LimitedInputStream
+import org.apache.james.jmap.HttpConstants.JSON_CONTENT_TYPE
 import org.apache.james.jmap.core.Id.Id
-import org.apache.james.jmap.core.{AccountId, Id, JmapRfc8621Configuration}
+import org.apache.james.jmap.core.{AccountId, Id, JmapRfc8621Configuration, ProblemDetails}
 import org.apache.james.jmap.exceptions.UnauthorizedException
 import org.apache.james.jmap.http.Authenticator
 import org.apache.james.jmap.http.rfc8621.InjectionKeys
-import org.apache.james.jmap.json.UploadSerializer
+import org.apache.james.jmap.json.{ResponseSerializer, UploadSerializer}
 import org.apache.james.jmap.mail.BlobId
 import org.apache.james.jmap.mail.Email.Size
 import org.apache.james.jmap.routes.UploadRoutes.{LOGGER, sanitizeSize}
@@ -101,9 +103,24 @@ class UploadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator: A
         authenticator.authenticate(request))
         .flatMap(session => post(request, response, ContentType.of(contentType), session))
         .onErrorResume {
-          case e: TooBigUploadException => SMono.fromPublisher(response.status(BAD_REQUEST).sendString(SMono.just("Attempt to upload exceed max size")).`then`())
-          case e: UnauthorizedException => SMono.fromPublisher(handleAuthenticationFailure(response, LOGGER, e))
-          case e: Throwable => SMono.fromPublisher(handleInternalError(response, LOGGER, e))
+          case e: UnauthorizedException =>
+            LOGGER.warn("Unauthorized", e)
+            respondDetails(response,
+              ProblemDetails(status = UNAUTHORIZED, detail = e.getMessage),
+              UNAUTHORIZED)
+          case _: TooBigUploadException =>
+            respondDetails(response,
+              ProblemDetails(status = BAD_REQUEST, detail = "Attempt to upload exceed max size"),
+              BAD_REQUEST)
+          case _: ForbiddenException =>
+            respondDetails(response,
+              ProblemDetails(status = FORBIDDEN, detail = "Upload to other accounts is forbidden"),
+              FORBIDDEN)
+          case e =>
+            LOGGER.error("Unexpected error upon uploads", e)
+            respondDetails(response,
+              ProblemDetails(status = INTERNAL_SERVER_ERROR, detail = e.getMessage),
+              INTERNAL_SERVER_ERROR)
         }
         .asJava()
         .subscribeOn(Schedulers.elastic())
@@ -123,7 +140,7 @@ class UploadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator: A
               SMono.fromCallable(() => ReactorUtils.toInputStream(request.receive.asByteBuffer))
               .flatMap(content => handle(targetAccountId, contentType, content, session, response))
             } else {
-              SMono.raiseError(new UnauthorizedException("Attempt to upload in another account"))
+              SMono.raiseError(ForbiddenException())
             })
 
       case Left(throwable: Throwable) => SMono.raiseError(throwable)
@@ -144,7 +161,6 @@ class UploadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator: A
               .sendString(SMono.just(serializer.serialize(uploadResponse).toString()))))
   }
 
-
   def uploadContent(accountId: AccountId, contentType: ContentType, inputStream: InputStream, session: MailboxSession): SMono[UploadResponse] =
     SMono
       .fromPublisher(attachmentManager.storeAttachment(contentType, inputStream, session))
@@ -156,4 +172,10 @@ class UploadRoutes @Inject()(@Named(InjectionKeys.RFC_8621) val authenticator: A
         `type` = ContentType.of(attachmentMetadata.getType.asString),
         size = sanitizeSize(attachmentMetadata.getSize),
         accountId = accountId)
+
+  private def respondDetails(httpServerResponse: HttpServerResponse, details: ProblemDetails, statusCode: HttpResponseStatus = BAD_REQUEST): SMono[Void] =
+    SMono.fromPublisher(httpServerResponse.status(statusCode)
+      .header(CONTENT_TYPE, JSON_CONTENT_TYPE)
+      .sendString(SMono.fromCallable(() => ResponseSerializer.serialize(details).toString), StandardCharsets.UTF_8)
+      .`then`)
 }
diff --git a/server/protocols/jmap/src/main/java/org/apache/james/jmap/http/Authenticator.java b/server/protocols/jmap/src/main/java/org/apache/james/jmap/http/Authenticator.java
index 0a7fe3d..cc9ab60 100644
--- a/server/protocols/jmap/src/main/java/org/apache/james/jmap/http/Authenticator.java
+++ b/server/protocols/jmap/src/main/java/org/apache/james/jmap/http/Authenticator.java
@@ -54,6 +54,6 @@ public class Authenticator {
             Flux.fromIterable(authMethods)
                 .concatMap(auth -> auth.createMailboxSession(request))
                 .next()
-                .switchIfEmpty(Mono.error(new UnauthorizedException("Unexpected error")))));
+                .switchIfEmpty(Mono.error(new UnauthorizedException("No valid authentication methods provided")))));
     }
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org