feat: añadido skeleton de auth para el comms

This commit is contained in:
fede committed 2026-08-05 22:32:05 -03:00
1 parent e4c062e130
commit e9cfb1adba
17 files changed
+327 -94

No files matched your search

@@ -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)
@@ -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
)
}
}
@@ -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"))
}
@@ -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)
}
}
}
}
@@ -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)
}
}
}
}
@@ -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
@@ -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 = {
@@ -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)
}
}
@@ -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 }
}
@@ -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()
@@ -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()