Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Signed Cookie #751

Merged
merged 24 commits into from
Jan 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions example/src/main/scala/example/SignCookies.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package example

import zhttp.http.{Cookie, Method, Response, _}
import zhttp.service.Server
import zio.duration.durationInt
import zio.{App, ExitCode, URIO}

/**
* Example to make app using signed-cookies
*/
object SignCookies extends App {

// Setting cookies with an expiry of 5 days
private val cookie = Cookie("key", "hello").withMaxAge(5 days)

private val app = Http.collect[Request] { case Method.GET -> !! / "cookie" =>
Response.ok.addCookie(cookie.sign("secret"))
}

// Run it like any simple app
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] =
Server.start(8090, app).exitCode
}
90 changes: 72 additions & 18 deletions zio-http/src/main/scala/zhttp/http/Cookie.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@ package zhttp.http

import zio.duration._

import java.security.MessageDigest
import java.time.Instant
import java.util.Base64.getEncoder
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
import scala.util.Try

final case class Cookie(
Expand All @@ -15,6 +19,7 @@ final case class Cookie(
isHttpOnly: Boolean = false,
maxAge: Option[Long] = None,
sameSite: Option[Cookie.SameSite] = None,
secret: Option[String] = None,
) { self =>

/**
Expand Down Expand Up @@ -68,6 +73,16 @@ final case class Cookie(
*/
def withSameSite(v: Cookie.SameSite): Cookie = copy(sameSite = Some(v))

/**
* Signs the cookie at the time of encoding using the provided secret.
*/
def sign(secret: String): Cookie = copy(secret = Some(secret))

/**
* Removes secret in the cookie
*/
def unSign: Cookie = copy(secret = None)

/**
* Resets secure flag in the cookie
*/
Expand Down Expand Up @@ -107,8 +122,13 @@ final case class Cookie(
* Converts cookie into a string
*/
def encode: String = {
val c = secret match {
case Some(sec) => content + "." + signContent(sec)
case None => content
}

val cookie = List(
Some(s"$name=$content"),
Some(s"$name=$c"),
expires.map(e => s"Expires=$e"),
maxAge.map(a => s"Max-Age=${a.toString}"),
domain.map(d => s"Domain=$d"),
Expand All @@ -120,6 +140,24 @@ final case class Cookie(
cookie.flatten.mkString("; ")
}

/**
* Signs cookie content with a secret and returns signature
*/
private def signContent(secret: String): String = {
tusharmath marked this conversation as resolved.
Show resolved Hide resolved
val sha256 = Mac.getInstance("HmacSHA256")
val secretKey = new SecretKeySpec(secret.getBytes(), "RSA")
sha256.init(secretKey)
val signed = sha256.doFinal(self.content.getBytes())
val mda = MessageDigest.getInstance("SHA-512")
getEncoder.encodeToString(mda.digest(signed))
}

/**
* Verifies signed-cookie's signature with a secret
*/
private def verify(content: String, signature: String, secret: String): Boolean =
self.withContent(content).signContent(secret) == signature

}

object Cookie {
Expand Down Expand Up @@ -147,10 +185,10 @@ object Cookie {
/**
* Decodes from Set-Cookie header value inside of Response into a cookie
*/
def decodeResponseCookie(headerValue: String): Option[Cookie] =
Try(unsafeDecodeResponseCookie(headerValue)).toOption
def decodeResponseCookie(headerValue: String, secret: Option[String] = None): Option[Cookie] =
Try(unsafeDecodeResponseCookie(headerValue, secret)).toOption

private[zhttp] def unsafeDecodeResponseCookie(headerValue: String): Cookie = {
private[zhttp] def unsafeDecodeResponseCookie(headerValue: String, secret: Option[String] = None): Cookie = {
var name: String = null
var content: String = null
var expires: Instant = null
Expand Down Expand Up @@ -214,21 +252,37 @@ object Cookie {
curr = next + 1
}
}
val decodedCookie =
if ((name != null && !name.isEmpty) || (content != null && !content.isEmpty))
Cookie(
name = name,
content = content,
expires = Option(expires),
maxAge = maxAge,
domain = Option(domain),
path = Option(path),
isSecure = secure,
isHttpOnly = httpOnly,
sameSite = Option(sameSite),
)
else
null

secret match {
case Some(s) => {
if (decodedCookie != null) {
val index = decodedCookie.content.lastIndexOf('.')
val signature = decodedCookie.content.slice(index + 1, decodedCookie.content.length)
val content = decodedCookie.content.slice(0, index)

if (decodedCookie.verify(content, signature, s))
decodedCookie.withContent(content).sign(s)
else null
} else decodedCookie
}
case None => decodedCookie
}

if ((name != null && !name.isEmpty) || (content != null && !content.isEmpty))
Cookie(
name = name,
content = content,
expires = Option(expires),
maxAge = maxAge,
domain = Option(domain),
path = Option(path),
isSecure = secure,
isHttpOnly = httpOnly,
sameSite = Option(sameSite),
)
else
null
}

/**
Expand Down
18 changes: 18 additions & 0 deletions zio-http/src/main/scala/zhttp/http/Middleware.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zhttp.http

import io.netty.handler.codec.http.HttpHeaderNames
import io.netty.util.AsciiString.contentEqualsIgnoreCase
import zhttp.http.CORS.DefaultCORSConfig
import zhttp.http.Headers.BasicSchemeName
import zhttp.http.Middleware.{Flag, RequestP}
Expand Down Expand Up @@ -45,6 +46,8 @@ sealed trait Middleware[-R, +E] { self =>
): Middleware[R1, E1] =
Middleware.fromMiddlewareFunctionZIO((m, u, h) => f(m, u, h))

final def modifyHeaders(f: PartialFunction[Header, Header]): Middleware[R, E] = Middleware.modifyHeaders(f)

final def orElse[R1 <: R, E1](other: Middleware[R1, E1]): Middleware[R1, E1] =
Middleware.OrElse(self, other)

Expand Down Expand Up @@ -89,6 +92,12 @@ object Middleware {
def addHeaders(headers: Headers): Middleware[Any, Nothing] =
patch((_, _) => Patch.addHeader(headers))

/**
* Modifies the provided list of headers to the updated list of headers
*/
def modifyHeaders(f: PartialFunction[Header, Header]): Middleware[Any, Nothing] =
patch((_, _) => Patch.updateHeaders(_.modify(f)))

/**
* Creates an authentication middleware that only allows authenticated requests to be passed on to the app.
*/
Expand Down Expand Up @@ -237,6 +246,15 @@ object Middleware {
} yield Patch.empty
}

/**
* Creates a middleware for signing cookies
*/
def signCookies(secret: String): Middleware[Any, Nothing] =
modifyHeaders {
case h if contentEqualsIgnoreCase(h._1, HeaderNames.setCookie) =>
(HeaderNames.setCookie, Cookie.decodeResponseCookie(h._2.toString).get.sign(secret).encode)
}

/**
* Creates a new constants middleware that always executes the app provided, independent of where the middleware is
* applied
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,9 @@ trait HeaderGetters[+A] { self =>
final def getSetCookie: Option[CharSequence] =
getHeaderValue(HeaderNames.setCookie)

final def getSetCookiesDecoded: List[Cookie] =
final def getSetCookiesDecoded(secret: Option[String] = None): List[Cookie] =
getHeaderValues(HeaderNames.setCookie)
tusharmath marked this conversation as resolved.
Show resolved Hide resolved
.map(Cookie.decodeResponseCookie)
.map(Cookie.decodeResponseCookie(_, secret))
.collect { case Some(cookie) => cookie }

final def getTe: Option[CharSequence] =
Expand Down
6 changes: 3 additions & 3 deletions zio-http/src/test/scala/zhttp/http/CookieSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ import zio.test._
object CookieSpec extends DefaultRunnableSpec {
def spec = suite("Cookies") {
suite("response cookies") {
testM("encode/decode cookies with ZIO Test Gen") {
testM("encode/decode signed/unsigned cookies with secret") {
checkAll(HttpGen.cookies) { cookie =>
val cookieString = cookie.encode
assert(Cookie.decodeResponseCookie(cookieString))(isSome(equalTo(cookie))) &&
assert(Cookie.decodeResponseCookie(cookieString).map(_.encode))(isSome(equalTo(cookieString)))
assert(Cookie.decodeResponseCookie(cookieString, cookie.secret))(isSome(equalTo(cookie))) &&
assert(Cookie.decodeResponseCookie(cookieString, cookie.secret).map(_.encode))(isSome(equalTo(cookieString)))
}
}
} +
Expand Down
3 changes: 2 additions & 1 deletion zio-http/src/test/scala/zhttp/internal/HttpGen.scala
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ object HttpGen {
httpOnly <- Gen.boolean
maxAge <- Gen.option(Gen.anyLong)
sameSite <- Gen.option(Gen.fromIterable(List(Cookie.SameSite.Strict, Cookie.SameSite.Lax)))
} yield Cookie(name, content, expires, domain, path, secure, httpOnly, maxAge, sameSite)
secret <- Gen.option(Gen.anyString)
} yield Cookie(name, content, expires, domain, path, secure, httpOnly, maxAge, sameSite, secret)

def header: Gen[Random with Sized, Header] = for {
key <- Gen.alphaNumericStringBounded(1, 4)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,13 @@ object MiddlewareSpec extends DefaultRunnableSpec with HttpAppTestExtensions {
res <- r.get
} yield assert(res)(equalTo(false))
}
} +
suite("signCookies") {
testM("should sign cookies") {
val cookie = Cookie("key", "value").withHttpOnly
val app = Http.ok.withSetCookie(cookie) @@ signCookies("secret") getHeader "set-cookie"
assertM(app(Request()))(isSome(equalTo(cookie.sign("secret").encode)))
}
}
}

Expand Down