CSRF

Http4s provides Middleware, named CSRF, to prevent Cross-site request forgery attacks. This middleware is modeled after the double submit cookie pattern.

Examples in this document have the following dependencies.

libraryDependencies ++= Seq(
  "org.http4s" %% "http4s-dsl" % http4sVersion,
  "org.http4s" %% "http4s-server" % http4sVersion
)

And we need some imports.

import cats.effect._
import org.http4s._
import org.http4s.dsl.io._
import org.http4s.implicits._
import org.http4s.server.middleware._

Let’s start by making a simple service.

val service = HttpRoutes.of[IO] {
  case _ =>
    Ok()
} 
// service: HttpRoutes[IO] = Kleisli(
//   org.http4s.HttpRoutes$$$Lambda$8265/1868696275@4e45c51a
// ) 

val request = Request[IO](Method.GET, uri"/")
// request: Request[IO] = (
//   Method("GET"),
//   Uri(None, None, "/", , None),
//   HttpVersion(1, 1),
//   Headers(),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@29db9c56
// )

service.orNotFound(request).unsafeRunSync()
// res0: Response[IO] = Response(
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@14e2616d
// )

That didn’t do all that much. Lets build out our CSRF Middleware by creating a CSRFBuilder

val cookieName = "csrf-token"
val key  = CSRF.generateSigningKey[IO].unsafeRunSync()
val defaultOriginCheck: Request[IO] => Boolean =
  CSRF.defaultOriginCheck[IO](_, "localhost", Uri.Scheme.http, None)
val csrfBuilder = CSRF[IO,IO](key, defaultOriginCheck)

More info on what is possible in the CSRFBuilder Docs, but we will create a fairly simple CSRF Middleware in our example.

val csrf = csrfBuilder.withCookieName(cookieName).withCookieDomain(Some("localhost")).withCookiePath(Some("/")).build
// csrf: CSRF[IO, IO] = org.http4s.server.middleware.CSRF@33426db0

Now we need to wrap this around our service! We’re gonna start with a safe call

val dummyRequest: Request[IO] =
    Request[IO](method = Method.GET).putHeaders(Header("Origin", "http://localhost"))
// dummyRequest: Request[IO] = (
//   Method("GET"),
//   Uri(None, None, "/", , None),
//   HttpVersion(1, 1),
//   Headers(Origin: http://localhost),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@53cf03d7
// )
val resp = csrf.validate()(service.orNotFound)(dummyRequest).unsafeRunSync()
// resp: Response[IO] = Response(
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Set-Cookie: csrf-token=1F801D8262308EB3F7FD4D72BFA86F9D0A2CAF0F3D38BE910A7EDD44FA90CC64-1647642503203-FCC2F87806A2AD0EAF2D546FEB3BEA19677D1A44; Domain=localhost; Path=/; SameSite=Lax; HttpOnly),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@61a2def5
// )

Notice how the response has the CSRF cookies added. How easy was that? And, as described in Middleware, services and middleware can be composed such that only some of your endpoints are CSRF enabled. By default, safe methods will update the CSRF token, while unsafe methods will validate them.

Without getting too deep into it, safe methods are OPTIONS, GET, and HEAD. While unsafe methods are POST, PUT, PATCH, DELETE, and TRACE. To put it simply, state changing methods are unsafe. For more information, check out this cheat sheet on CSRF Prevention.

Unsafe requests (like POST) require us to send the CSRF token in the X-Csrf-Token header (this is the default name, but it can be changed), so we are going to get the value and send it up in our POST. I’ve also added the response cookie as a RequestCookie, normally the browser would send this up with our request, but I needed to do it manually for the purpose of this demo.

val cookie = resp.cookies.head
// cookie: ResponseCookie = ResponseCookie(
//   "csrf-token",
//   "1F801D8262308EB3F7FD4D72BFA86F9D0A2CAF0F3D38BE910A7EDD44FA90CC64-1647642503203-FCC2F87806A2AD0EAF2D546FEB3BEA19677D1A44",
//   None,
//   None,
//   Some("localhost"),
//   Some("/"),
//   Lax,
//   false,
//   true,
//   None
// )
val dummyPostRequest: Request[IO] =
    Request[IO](method = Method.POST).putHeaders(
      Header("Origin", "http://localhost"),
      Header("X-Csrf-Token", cookie.content)
    ).addCookie(RequestCookie(cookie.name,cookie.content))
// dummyPostRequest: Request[IO] = (
//   Method("POST"),
//   Uri(None, None, "/", , None),
//   HttpVersion(1, 1),
//   Headers(Origin: http://localhost, X-Csrf-Token: 1F801D8262308EB3F7FD4D72BFA86F9D0A2CAF0F3D38BE910A7EDD44FA90CC64-1647642503203-FCC2F87806A2AD0EAF2D546FEB3BEA19677D1A44, Cookie: csrf-token=1F801D8262308EB3F7FD4D72BFA86F9D0A2CAF0F3D38BE910A7EDD44FA90CC64-1647642503203-FCC2F87806A2AD0EAF2D546FEB3BEA19677D1A44),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@35cfb8d9
// )
val validateResp = csrf.validate()(service.orNotFound)(dummyPostRequest).unsafeRunSync()
// validateResp: Response[IO] = Response(
//   Status(200),
//   HttpVersion(1, 1),
//   Headers(Content-Length: 0, Set-Cookie: csrf-token=1F801D8262308EB3F7FD4D72BFA86F9D0A2CAF0F3D38BE910A7EDD44FA90CC64-1647642503223-2682528548E96FA2C837BA4E63B793602DF18A26; Domain=localhost; Path=/; SameSite=Lax; HttpOnly),
//   Stream(..),
//   io.chrisdavenport.vault.Vault@426d8de3
// )