diff --git a/comms/.env.example b/comms/.env.example index 54a7625..2c7d2f1 100644 --- a/comms/.env.example +++ b/comms/.env.example @@ -4,3 +4,6 @@ SMTP_USER=tu-usuario@gmail.com SMTP_PASSWORD=tu-app-password SMTP_FROM=tu-usuario@gmail.com SMTP_TO=destinatario@example.com +JWT_SECRET=tu-secreto-jwt +JWT_UID=sub +JWT_ALGORITMOS=HS256 diff --git a/comms/README.md b/comms/README.md index f630709..115fd7a 100644 --- a/comms/README.md +++ b/comms/README.md @@ -30,27 +30,46 @@ sbt run El servidor escucha en `http://localhost:8088`. +## Autenticación + +Todas las rutas requieren un header `Authorization` con un JWT válido (firma + expiración): + +```sh +-H 'Authorization: Bearer ' +``` + +El token lo emite el backend (`back`, endpoint `/auth/login`). Config: + +- `JWT_SECRET`: mismo secreto que `JWTString` del back. +- `JWT_UID`: claim que se usa como id (por ahora la verificación de habilitación está comentada, ver `middleware/AuthMiddleware.scala`). +- `JWT_ALGORITMOS`: algoritmos aceptados (ej. `HS256`). + +Respuestas de auth: + +- `403 Forbidden` si falta el header, el token no es Bearer, está mal firmado o expirado. + ## Endpoint ### `POST /email` -Envía un email. `to` es el destinatario (viene en la request, no en el `.env`). +Envía un email. `to` es la lista de destinatarios (viene en la request, no en el `.env`). ```sh curl -X POST http://localhost:8088/email \ -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer ' \ -d '{ "titulo": "Pedido #123", "descripcion": "

Nuevo pedido

", "items": ["Bujía", "Filtro de aceite", "Pastillas de freno"], - "to": "cliente@example.com" + "to": ["cliente@example.com"] }' ``` - `titulo`: asunto del email (string). - `descripcion`: cuerpo del email, se trata como HTML. - `items`: lista de strings, se renderiza como tabla en el email. -- `to`: destinatario (string). +- `to`: lista de destinatarios (array de strings). Respuestas: @@ -62,12 +81,13 @@ Respuestas: ```sh curl -X POST http://localhost:8088/webhook/discord \ -H 'Content-Type: application/json' \ + -H 'Authorization: Bearer ' \ -d '{ "titulo": "Pedido #123", "contenido":"ticket ferreteria", "descripcion": "Nuevo pedido", "items": ["Bujía", "Filtro de aceite", "Pastillas de freno"], - "to": "url a webhook ds" + "to": ["url a webhook ds"] }' ``` diff --git a/comms/build.sbt b/comms/build.sbt index 31c0203..d8d64ce 100644 --- a/comms/build.sbt +++ b/comms/build.sbt @@ -12,15 +12,16 @@ lazy val root = (project in file(".")) version := "0.0.1-SNAPSHOT", scalaVersion := "2.13.18", libraryDependencies ++= Seq( - "org.http4s" %% "http4s-ember-server" % Http4sVersion, - "org.http4s" %% "http4s-ember-client" % Http4sVersion, - "org.http4s" %% "http4s-circe" % Http4sVersion, - "org.http4s" %% "http4s-dsl" % Http4sVersion, - "io.circe" %% "circe-generic" % CirceVersion, - "org.scalameta" %% "munit" % MunitVersion % Test, - "org.typelevel" %% "munit-cats-effect" % MunitCatsEffectVersion % Test, - "com.sun.mail" % "jakarta.mail" % JakartaMailVersion, - "ch.qos.logback" % "logback-classic" % LogbackVersion % Runtime, + "org.http4s" %% "http4s-ember-server" % Http4sVersion, + "org.http4s" %% "http4s-ember-client" % Http4sVersion, + "org.http4s" %% "http4s-circe" % Http4sVersion, + "org.http4s" %% "http4s-dsl" % Http4sVersion, + "com.github.jwt-scala" %% "jwt-core" % "11.0.4", + "io.circe" %% "circe-generic" % CirceVersion, + "org.scalameta" %% "munit" % MunitVersion % Test, + "org.typelevel" %% "munit-cats-effect" % MunitCatsEffectVersion % Test, + "com.sun.mail" % "jakarta.mail" % JakartaMailVersion, + "ch.qos.logback" % "logback-classic" % LogbackVersion % Runtime, ), addCompilerPlugin("org.typelevel" %% "kind-projector" % "0.13.4" cross CrossVersion.full), addCompilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), diff --git a/comms/src/main/scala/com/fede/comms/CommsServer.scala b/comms/src/main/scala/com/fede/comms/CommsServer.scala index 2d794a1..c99a5c6 100644 --- a/comms/src/main/scala/com/fede/comms/CommsServer.scala +++ b/comms/src/main/scala/com/fede/comms/CommsServer.scala @@ -2,7 +2,7 @@ package com.fede.comms import cats.effect.{Async, Resource} import com.comcast.ip4s._ -import com.fede.comms.config.SmtpConfig +import com.fede.comms.config.{AuthConfig, SmtpConfig} import com.fede.comms.routes.AllRoutes // import com.fede.comms.config.WebHookConfig import fs2.io.net.Network @@ -19,10 +19,11 @@ object CommsServer { for { client <- EmberClientBuilder.default[F].build smtpConfig <- Resource.eval(SmtpConfig.load[F]()) + authConfig <- Resource.eval(AuthConfig.load[F]()) email = new SmtpEmail[F](smtpConfig) webhook = new HttpWebHook[F](client) - httpApp = AllRoutes.allRoutes[F](email, webhook).orNotFound + httpApp = AllRoutes.allRoutes[F](email, webhook, authConfig).orNotFound finalHttpApp = Logger.httpApp(true, true)(httpApp) diff --git a/comms/src/main/scala/com/fede/comms/config/AuthConfig.scala b/comms/src/main/scala/com/fede/comms/config/AuthConfig.scala new file mode 100644 index 0000000..5938fa3 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/config/AuthConfig.scala @@ -0,0 +1,22 @@ +package com.fede.comms.config + +import cats.effect.kernel.Sync + +final case class AuthConfig( + secret: String, + campoId: String, + algoritmo: Seq[String]) + +object AuthConfig { + def load[F[_]: Sync] (envFile: String = ".env"): F[AuthConfig] = + Sync[F].delay { + val env = EnvFile.load(envFile) + val required = ConfigUtils.required(env, envFile) _ + + AuthConfig( + secret = required("JWT_SECRET"), + campoId = required("JWT_UID"), + algoritmo = required("JWT_ALGORITMOS").split(",").toSeq + ) + } +} diff --git a/comms/src/main/scala/com/fede/comms/config/ConfigUtils.scala b/comms/src/main/scala/com/fede/comms/config/ConfigUtils.scala new file mode 100644 index 0000000..8782e06 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/config/ConfigUtils.scala @@ -0,0 +1,6 @@ +package com.fede.comms.config + +object ConfigUtils { + def required(env: Map[String, String], envFile: String)(key: String): String = + env.getOrElse(key, sys.error(s"Falta '$key' en $envFile")) +} \ No newline at end of file diff --git a/comms/src/main/scala/com/fede/comms/config/EnvFile.scala b/comms/src/main/scala/com/fede/comms/config/EnvFile.scala new file mode 100644 index 0000000..1e6853d --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/config/EnvFile.scala @@ -0,0 +1,38 @@ +package com.fede.comms.config + +import java.io.File +import scala.io.Source + +object EnvFile { + + def load(path: String): Map[String, String] = { + val file = new File(path) + if (!file.exists()) Map.empty + else { + val lines = Source.fromFile(file).getLines().toList + lines.flatMap(parseLine).toMap + } + } + + private def parseLine(line: String): Option[(String, String)] = { + val trimmed = line.trim + if (trimmed.isEmpty || trimmed.startsWith("#")) None + else { + val withoutExport = trimmed.stripPrefix("export").trim + val idx = withoutExport.indexOf('=') + if (idx <= 0) None + else { + val key = withoutExport.substring(0, idx).trim + val raw = withoutExport.substring(idx + 1).trim + val value = raw match { + case q if q.length >= 2 && q.head == '"' && q.last == '"' => + q.substring(1, q.length - 1) + case q if q.length >= 2 && q.head == '\'' && q.last == '\'' => + q.substring(1, q.length - 1) + case other => other + } + Some(key -> value) + } + } + } +} diff --git a/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala b/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala index 10142c6..577a552 100644 --- a/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala +++ b/comms/src/main/scala/com/fede/comms/config/SmtpConfig.scala @@ -2,9 +2,6 @@ package com.fede.comms.config import cats.effect.Sync -import java.io.File -import scala.io.Source - final case class SmtpConfig( host: String, port: Int, @@ -19,9 +16,9 @@ object SmtpConfig { def load[F[_]: Sync](envFile: String = ".env"): F[SmtpConfig] = Sync[F].delay { val env = EnvFile.load(envFile) + val required = ConfigUtils.required(env, envFile) _ + - def required(key: String): String = - env.getOrElse(key, sys.error(s"Falta $key en $envFile")) SmtpConfig( host = required("SMTP_HOST"), @@ -34,36 +31,4 @@ object SmtpConfig { } } -object EnvFile { - def load(path: String): Map[String, String] = { - val file = new File(path) - if (!file.exists()) Map.empty - else { - val lines = Source.fromFile(file).getLines().toList - lines.flatMap(parseLine).toMap - } - } - - private def parseLine(line: String): Option[(String, String)] = { - val trimmed = line.trim - if (trimmed.isEmpty || trimmed.startsWith("#")) None - else { - val withoutExport = trimmed.stripPrefix("export").trim - val idx = withoutExport.indexOf('=') - if (idx <= 0) None - else { - val key = withoutExport.substring(0, idx).trim - val raw = withoutExport.substring(idx + 1).trim - val value = raw match { - case q if q.length >= 2 && q.head == '"' && q.last == '"' => - q.substring(1, q.length - 1) - case q if q.length >= 2 && q.head == '\'' && q.last == '\'' => - q.substring(1, q.length - 1) - case other => other - } - Some(key -> value) - } - } - } -} diff --git a/comms/src/main/scala/com/fede/comms/emails/Emails.scala b/comms/src/main/scala/com/fede/comms/emails/Emails.scala index 0ae15f4..b3fed40 100644 --- a/comms/src/main/scala/com/fede/comms/emails/Emails.scala +++ b/comms/src/main/scala/com/fede/comms/emails/Emails.scala @@ -6,7 +6,7 @@ import io.circe.generic.semiauto._ import org.http4s.{EntityDecoder, EntityEncoder} import org.http4s.circe._ -final case class Mensaje(titulo: String, descripcion: String, items: List[String], to: String) +final case class Mensaje(titulo: String, descripcion: String, items: List[String], to: List[String]) object Mensaje { implicit val mensajeDecoder: Decoder[Mensaje] = deriveDecoder diff --git a/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala b/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala index dfe7d93..0e55052 100644 --- a/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala +++ b/comms/src/main/scala/com/fede/comms/emails/SmtpEmail.scala @@ -28,10 +28,12 @@ final class SmtpEmail[F[_]: Sync](config: com.fede.comms.config.SmtpConfig) exte val message = new MimeMessage(session) message.setFrom(new InternetAddress(config.from)) - message.setRecipients(Message.RecipientType.TO, m.to) message.setSubject(m.titulo, "UTF-8") message.setContent(htmlBody(m), "text/html; charset=utf-8") - Transport.send(message) + m.to.foreach { recipient => + message.setRecipients(Message.RecipientType.TO, recipient) + Transport.send(message) + } } private def htmlBody(m: Mensaje): String = { diff --git a/comms/src/main/scala/com/fede/comms/middleware/AuthMiddleware.scala b/comms/src/main/scala/com/fede/comms/middleware/AuthMiddleware.scala new file mode 100644 index 0000000..b1ab2a6 --- /dev/null +++ b/comms/src/main/scala/com/fede/comms/middleware/AuthMiddleware.scala @@ -0,0 +1,79 @@ +package com.fede.comms.middleware + +import cats.Monad +import cats.data.{Kleisli, OptionT} +import org.http4s.headers.Authorization +import org.http4s.server.AuthMiddleware +import org.http4s.{AuthScheme, AuthedRoutes, Credentials, HttpRoutes, Request, Response, Status} +import pdi.jwt.algorithms.JwtHmacAlgorithm +import pdi.jwt.{Jwt, JwtClaim} + +/** + * Fuente de "habilitación" (el "xxxx" del pedido original): dado un id + * (por ej. el subject o jti del claim), dice si el token está habilitado. + * Se puede construir desde un Set, un Map, o una función arbitraria + * (consulta a una DB, Redis, etc). + * + * NOTA: la verificación de habilitación está comentada (ver `JwtMiddleware`); + * el middleware solo valida firma + expiración. + */ +object Habilitados { + type Habilitados = String => cats.effect.IO[Boolean] + + def desdeSet(set: Set[String]): Habilitados = + id => cats.effect.IO.pure(set.contains(id)) + + def desdeMapa(mapa: Map[String, Boolean]): Habilitados = + id => cats.effect.IO.pure(mapa.getOrElse(id, false)) + + def desdeFuncion(f: String => cats.effect.IO[Boolean]): Habilitados = f +} + +/** + * Middleware de http4s que verifica que el JWT esté correctamente firmado + * (firma + expiración). Todas las rutas que se le pasan quedan protegidas. + * + * Uso: + * val app = JwtMiddleware(secreto, Seq(JwtAlgorithm.HS256))(rutasProtegidas) + */ +object JwtMiddleware { + + def apply[F[_]: Monad]( + secreto: String, + algoritmos: Seq[JwtHmacAlgorithm] + )(routes: AuthedRoutes[JwtClaim, F]): HttpRoutes[F] = { + + val autenticar: Kleisli[F, Request[F], Either[String, JwtClaim]] = Kleisli { req => + val resultado: Either[String, String] = for { + header <- req.headers.get[Authorization].toRight("Falta header Authorization") + token <- header.credentials match { + case Credentials.Token(AuthScheme.Bearer, token) => Right(token) + case _ => Left("Se esperaba un token Bearer") + } + } yield token + + resultado match { + case Left(err) => Monad[F].pure(Left(err)) + case Right(token) => + Jwt.decode(token, secreto, algoritmos).toEither.left.map(_.getMessage) match { + case Left(err) => Monad[F].pure(Left(s"Token inválido: $err")) + case Right(claim) => + // Parte del claim comentada: acá se podía chequear que el usuario + // esté habilitado leyendo un campo del claim (por ej. "sub", "jti" o "email"). + // + // val id = campoId(claim).getOrElse("") + // habilitados(id).map { ok => + // if (ok) Right(claim) else Left("Token no habilitado") + // } + Monad[F].pure(Right(claim)) + } + } + } + + val onFailure: AuthedRoutes[String, F] = + Kleisli(_ => OptionT.liftF(Monad[F].pure(Response[F](Status.Forbidden)))) + + val middleware: AuthMiddleware[F, JwtClaim] = AuthMiddleware(autenticar, onFailure) + middleware(routes) + } +} diff --git a/comms/src/main/scala/com/fede/comms/routes/AllRoutes.scala b/comms/src/main/scala/com/fede/comms/routes/AllRoutes.scala index 4d473b7..ea06533 100644 --- a/comms/src/main/scala/com/fede/comms/routes/AllRoutes.scala +++ b/comms/src/main/scala/com/fede/comms/routes/AllRoutes.scala @@ -1,13 +1,29 @@ package com.fede.comms.routes import cats.effect.Concurrent -import com.fede.comms.emails.{Email} -import com.fede.comms.routes.WebhookRoutes import cats.syntax.all._ -import org.http4s.HttpRoutes -import com.fede.comms.webhook.HttpWebHook +import com.fede.comms.config.AuthConfig +import com.fede.comms.emails.Email +import com.fede.comms.middleware.JwtMiddleware +import com.fede.comms.webhook.WebHook +import org.http4s.{AuthedRoutes, HttpRoutes} +import pdi.jwt.JwtAlgorithm +import pdi.jwt.JwtClaim +import pdi.jwt.algorithms.JwtHmacAlgorithm object AllRoutes { - def allRoutes[F[_]: Concurrent](email: Email[F], webhook: HttpWebHook[F]): HttpRoutes[F] = - EmailRoutes.emailRoutes(email) <+> WebhookRoutes.webhookRoutes(webhook) + + def allRoutes[F[_]: Concurrent]( + email: Email[F], + webhook: WebHook[F], + auth: AuthConfig + ): HttpRoutes[F] = { + val protegidas: AuthedRoutes[JwtClaim, F] = + EmailRoutes.emailRoutes(email) <+> WebhookRoutes.webhookRoutes(webhook) + + JwtMiddleware(auth.secret, algoritmos(auth))(protegidas) + } + + private def algoritmos(auth: AuthConfig): Seq[JwtHmacAlgorithm] = + auth.algoritmo.map(JwtAlgorithm.fromString).collect { case a: JwtHmacAlgorithm => a } } diff --git a/comms/src/main/scala/com/fede/comms/routes/EmailRoutes.scala b/comms/src/main/scala/com/fede/comms/routes/EmailRoutes.scala index 61a08e4..1112f18 100644 --- a/comms/src/main/scala/com/fede/comms/routes/EmailRoutes.scala +++ b/comms/src/main/scala/com/fede/comms/routes/EmailRoutes.scala @@ -3,16 +3,16 @@ package com.fede.comms.routes import cats.effect.Concurrent import cats.syntax.all._ import com.fede.comms.emails.{Email, Mensaje} -import org.http4s.HttpRoutes -import org.http4s.circe.CirceEntityDecoder._ +import org.http4s._ import org.http4s.dsl.Http4sDsl +import pdi.jwt.JwtClaim object EmailRoutes { - def emailRoutes[F[_]: Concurrent](email: Email[F]): HttpRoutes[F] = { + def emailRoutes[F[_]: Concurrent](email: Email[F]): AuthedRoutes[JwtClaim, F] = { val dsl = new Http4sDsl[F] {} import dsl._ - HttpRoutes.of[F] { - case req @ POST -> Root / "email" => + AuthedRoutes.of[JwtClaim, F] { + case ContextRequest(_, req @ POST -> Root / "email") => req.attemptAs[Mensaje].foldF( _ => BadRequest(), mensaje => email.enviar(mensaje) *> Ok() diff --git a/comms/src/main/scala/com/fede/comms/routes/WebhookRoutes.scala b/comms/src/main/scala/com/fede/comms/routes/WebhookRoutes.scala index d2cee85..45876d9 100644 --- a/comms/src/main/scala/com/fede/comms/routes/WebhookRoutes.scala +++ b/comms/src/main/scala/com/fede/comms/routes/WebhookRoutes.scala @@ -1,18 +1,18 @@ package com.fede.comms.routes import cats.effect.Concurrent -import org.http4s.HttpRoutes -import org.http4s.circe.CirceEntityDecoder._ +import org.http4s._ import cats.syntax.all._ -import com.fede.comms.webhook.{WebHook,Mensaje} +import com.fede.comms.webhook.{Mensaje, WebHook} import org.http4s.dsl.Http4sDsl +import pdi.jwt.JwtClaim object WebhookRoutes { - def webhookRoutes[F[_]: Concurrent](hook: WebHook[F]): HttpRoutes[F] = { + def webhookRoutes[F[_]: Concurrent](hook: WebHook[F]): AuthedRoutes[JwtClaim, F] = { val dsl = new Http4sDsl[F] {} import dsl._ - HttpRoutes.of[F] { - case req @ POST -> Root / "webhook" / "discord"=> + AuthedRoutes.of[JwtClaim, F] { + case ContextRequest(_, req @ POST -> Root / "webhook" / "discord") => req.attemptAs[Mensaje].foldF( _ => BadRequest(), mensaje => hook.enviar(mensaje) *> Ok() diff --git a/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala b/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala index c83822c..59df302 100644 --- a/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala +++ b/comms/src/test/scala/com/fede/comms/CommsRoutesSpec.scala @@ -2,40 +2,119 @@ package com.fede.comms import cats.effect.IO import cats.effect.kernel.Ref -import com.fede.comms.emails.{Email, Mensaje} -import org.http4s._ -import org.http4s.implicits._ +import com.fede.comms.config.AuthConfig +import com.fede.comms.emails.{Email, Mensaje => EmailMensaje} +import com.fede.comms.routes.AllRoutes +import com.fede.comms.webhook.{Mensaje => WebhookMensaje, WebHook} +import io.circe.syntax._ import munit.CatsEffectSuite +import org.http4s._ +import org.http4s.headers.Authorization +import org.http4s.implicits._ +import pdi.jwt.{Jwt, JwtAlgorithm, JwtClaim} + +import java.time.Clock class CommsRoutesSpec extends CatsEffectSuite { - test("POST /email returns 200 and calls enviar") { + implicit val clock: Clock = Clock.systemUTC() + + private val secreto = "test-secret" + private val auth = AuthConfig(secreto, "sub", Seq("HS256")) + + private def token(expiresIn: Long = 60): String = + Jwt.encode( + JwtClaim().issuedNow(clock).expiresIn(expiresIn)(clock), + secreto, + JwtAlgorithm.HS256 + ) + + private val emailMensaje = EmailMensaje("Titulo", "Descripcion", List("a", "b"), List("a@b.com")) + + private def routes(email: Email[IO]): HttpRoutes[IO] = + AllRoutes.allRoutes[IO]( + email, + new WebHook[IO] { def enviar(m: WebhookMensaje): IO[Unit] = IO.unit }, + auth + ) + + private def authorized(req: Request[IO], t: String): Request[IO] = + req.putHeaders(Authorization(Credentials.Token(AuthScheme.Bearer, t))) + + private val webhookBody = + WebhookMensaje("Titulo", "Contenido", "Descripcion", List("a", "b"), List("http://x")).asJson.noSpaces + + test("POST /email sin token devuelve 403") { + val email = new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit } + val req = Request[IO](Method.POST, uri"/email").withEntity(emailMensaje) + assertIO(routes(email).orNotFound(req).map(_.status), Status.Forbidden) + } + + test("POST /email con token inválido devuelve 403") { + val email = new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit } + val req = authorized( + Request[IO](Method.POST, uri"/email").withEntity(emailMensaje), + "token-invalido" + ) + assertIO(routes(email).orNotFound(req).map(_.status), Status.Forbidden) + } + + test("POST /email con token vencido devuelve 403") { + val email = new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit } + val req = authorized( + Request[IO](Method.POST, uri"/email").withEntity(emailMensaje), + token(-60) + ) + assertIO(routes(email).orNotFound(req).map(_.status), Status.Forbidden) + } + + test("POST /email con token válido devuelve 200 y llama enviar") { val testIO = for { - ref <- Ref.of[IO, List[Mensaje]](Nil) - email = new Email[IO] { - def enviar(m: Mensaje): IO[Unit] = ref.update(_ :+ m) - } - req = Request[IO](Method.POST, uri"/email") - .withEntity(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com")) - resp <- CommsRoutes.emailRoutes[IO](email).orNotFound(req) + ref <- Ref.of[IO, List[EmailMensaje]](Nil) + email = new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = ref.update(_ :+ m) } + req = authorized( + Request[IO](Method.POST, uri"/email").withEntity(emailMensaje), + token() + ) + resp <- routes(email).orNotFound(req) sent <- ref.get } yield (resp.status, sent) for { r <- testIO _ <- assertIO(IO.pure(r._1), Status.Ok) - _ <- assertIO(IO.pure(r._2), List(Mensaje("Titulo", "Descripcion", List("a", "b"), "a@b.com"))) + _ <- assertIO(IO.pure(r._2), List(emailMensaje)) } yield () } - test("POST /email with invalid json returns 400") { - val email = new Email[IO] { - def enviar(m: Mensaje): IO[Unit] = IO.unit - } - val req = Request[IO](Method.POST, uri"/email").withEntity("{}") - assertIO( - CommsRoutes.emailRoutes[IO](email).orNotFound(req).map(_.status), - Status.BadRequest + test("POST /email con JSON inválido devuelve 400") { + val email = new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit } + val req = authorized(Request[IO](Method.POST, uri"/email").withEntity("{}"), token()) + assertIO(routes(email).orNotFound(req).map(_.status), Status.BadRequest) + } + + test("POST /webhook/discord sin token devuelve 403") { + val hook = new WebHook[IO] { def enviar(m: WebhookMensaje): IO[Unit] = IO.unit } + val app = AllRoutes.allRoutes[IO]( + new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit }, + hook, + auth ) + val req = Request[IO](Method.POST, uri"/webhook/discord").withEntity(webhookBody) + assertIO(app.orNotFound(req).map(_.status), Status.Forbidden) + } + + test("POST /webhook/discord con token válido devuelve 200") { + val hook = new WebHook[IO] { def enviar(m: WebhookMensaje): IO[Unit] = IO.unit } + val app = AllRoutes.allRoutes[IO]( + new Email[IO] { def enviar(m: EmailMensaje): IO[Unit] = IO.unit }, + hook, + auth + ) + val req = authorized( + Request[IO](Method.POST, uri"/webhook/discord").withEntity(webhookBody), + token() + ) + assertIO(app.orNotFound(req).map(_.status), Status.Ok) } } diff --git a/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala b/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala index 5112a80..7c024fa 100644 --- a/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala +++ b/comms/src/test/scala/com/fede/comms/SmtpEmailSpec.scala @@ -17,7 +17,7 @@ class SmtpEmailSpec extends CatsEffectSuite { titulo = "[comms] prueba", descripcion = "Email de prueba desde el servicio comms", items = List("item 1", "item 2"), - to = to + to = List(to) ) ) } yield () diff --git a/nginx/nginx.conf b/nginx/nginx.conf index 60296a0..e7d85b3 100644 --- a/nginx/nginx.conf +++ b/nginx/nginx.conf @@ -36,7 +36,8 @@ http { } # cliente smtp y webhooks - location /comms { + location /comms/ { + rewrite ^/comms(.*) $1 break; proxy_pass http://avisos; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;