Skip to content

Commit

Permalink
Merge pull request #2942 from ScalaFanatic/fix-request-add-cookies
Browse files Browse the repository at this point in the history
Fix Request.addCookie so it complies with the HTTP specification
  • Loading branch information
rossabaker committed Nov 5, 2019
2 parents 8daf6f9 + 9619a51 commit f3bd779
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
9 changes: 8 additions & 1 deletion core/src/main/scala/org/http4s/Message.scala
Expand Up @@ -340,7 +340,14 @@ sealed abstract case class Request[F[_]](

/** Add a Cookie header for the provided [[Cookie]] */
def addCookie(cookie: RequestCookie): Self =
putHeaders(Cookie(NonEmptyList.of(cookie)))
headers
.get(Cookie)
.fold(putHeaders(Cookie(NonEmptyList.of(cookie)))) { preExistingCookie =>
removeHeader(Cookie).putHeaders(
Header(
Cookie.name.value,
s"${preExistingCookie.value}; ${cookie.name}=${cookie.content}"))
}

/** Add a Cookie header with the provided values */
def addCookie(name: String, content: String): Self =
Expand Down
20 changes: 19 additions & 1 deletion tests/src/test/scala/org/http4s/MessageSpec.scala
Expand Up @@ -67,13 +67,31 @@ class MessageSpec extends Http4sSpec {
.map(_.value) must beSome("token=value")
}

"contain a single Cookie header when multiple explicit cookies are added" in {
Request(Method.GET)
.addCookie(RequestCookie("token1", "value1"))
.addCookie(RequestCookie("token2", "value2"))
.headers
.get("Cookie".ci)
.map(_.value) must beSome("token1=value1; token2=value2")
}

"contain a Cookie header when a name/value pair is added" in {
Request(Method.GET)
.addCookie("token", "value")
.headers
.get("Cookie".ci)
.map(_.value) must beSome("token=value")
}

"contain a single Cookie header when name/value pairs are added" in {
Request(Method.GET)
.addCookie("token1", "value1")
.addCookie("token2", "value2")
.headers
.get("Cookie".ci)
.map(_.value) must beSome("token1=value1; token2=value2")
}
}

"Request.with..." should {
Expand Down Expand Up @@ -118,7 +136,7 @@ class MessageSpec extends Http4sSpec {
"redact Cookie Headers" in {
val request =
Request[IO](Method.GET).addCookie("token", "value").addCookie("token2", "value2")
request.toString must_== ("Request(method=GET, uri=/, headers=Headers(Cookie: <REDACTED>, Cookie: <REDACTED>))")
request.toString must_== ("Request(method=GET, uri=/, headers=Headers(Cookie: <REDACTED>))")
}
}
}
Expand Down

0 comments on commit f3bd779

Please sign in to comment.