From e8c2b22a14f194502e08492372f60b96e88dcdaa Mon Sep 17 00:00:00 2001 From: Francesco Serra Date: Mon, 8 Jul 2024 18:34:26 +0100 Subject: [PATCH] NOJIRA make request body strict, * request body is now consumed in one go and stored in memory * prevent occurrences of BodyAlreadyConsumedError --- .../mdsol/mauth/http4s/MAuthMiddleware.scala | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/modules/mauth-authenticator-http4s/src/main/scala/com/mdsol/mauth/http4s/MAuthMiddleware.scala b/modules/mauth-authenticator-http4s/src/main/scala/com/mdsol/mauth/http4s/MAuthMiddleware.scala index 3adf167..b440e11 100644 --- a/modules/mauth-authenticator-http4s/src/main/scala/com/mdsol/mauth/http4s/MAuthMiddleware.scala +++ b/modules/mauth-authenticator-http4s/src/main/scala/com/mdsol/mauth/http4s/MAuthMiddleware.scala @@ -78,27 +78,25 @@ object MAuthMiddleware { else extractAll(V2) orElse extractAll(V1) - fk(request.as[Array[Byte]].flatMap { byteArray => - authHeaderTimeHeader.flatMap { authCtx: MAuthContext => - val mAuthRequest: MAuthRequest = new MAuthRequest( - authCtx.authHeader, - byteArray, - request.method.name, - authCtx.timeHeader.toString, - request.uri.path.renderString, - request.uri.query.renderString - ) - - // this mimics MAuthDirectives in the akka package - really needed? - val req = if (!authenticator.isV2OnlyAuthenticate) { - mAuthRequest.setXmwsSignature(getHeaderValOrEmpty(V1.authHeaderName)) // dreadful mutating type - mAuthRequest.setXmwsTime(getHeaderValOrEmpty(V1.timeHeaderName)) - mAuthRequest - } else mAuthRequest - - authenticator.authenticate(req)(requestValidationTimeout).map(res => (res, authCtx)) - } - }).flatMap { case (b, ctx) => + fk(for { + strictBody <- request.toStrict(none) + byteArray <- strictBody.as[Array[Byte]] + authCtx <- authHeaderTimeHeader + mAuthRequest = new MAuthRequest( + authCtx.authHeader, + byteArray, + request.method.name, + authCtx.timeHeader.toString, + request.uri.path.renderString, + request.uri.query.renderString + ) + req = if (!authenticator.isV2OnlyAuthenticate) { + mAuthRequest.setXmwsSignature(getHeaderValOrEmpty(V1.authHeaderName)) // dreadful mutating type + mAuthRequest.setXmwsTime(getHeaderValOrEmpty(V1.timeHeaderName)) + mAuthRequest + } else mAuthRequest + res <- authenticator.authenticate(req)(requestValidationTimeout).map(res => (res, authCtx)) + } yield res).flatMap { case (b, ctx) => if (b) http(AuthedRequest(ctx, request)) else logAndReturnDefaultUnauthorizedReq(s"Rejecting request as authentication failed") }.recoverWith { case MdsolAuthMissingHeaderRejection(hn) =>