Skip to content

Commit

Permalink
KTOR-4722 renderSetCookieHeader should not encode extensions (#3172)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov committed Oct 4, 2022
1 parent d6b9a87 commit 69792c3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
8 changes: 4 additions & 4 deletions ktor-http/common/src/io/ktor/http/Cookie.kt
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,8 @@ public fun renderSetCookieHeader(

cookiePartFlag("Secure", secure),
cookiePartFlag("HttpOnly", httpOnly)
) + extensions.map { cookiePartExt(it.key.assertCookieName(), it.value, encoding) } +
if (includeEncoding) cookiePartExt("\$x-enc", encoding.name, CookieEncoding.RAW) else ""
) + extensions.map { cookiePartExt(it.key.assertCookieName(), it.value) } +
if (includeEncoding) cookiePartExt("\$x-enc", encoding.name) else ""
).filter { it.isNotEmpty() }
.joinToString("; ")

Expand Down Expand Up @@ -221,7 +221,7 @@ private inline fun cookiePartFlag(name: String, value: Boolean) =
if (value) name else ""

@Suppress("NOTHING_TO_INLINE")
private inline fun cookiePartExt(name: String, value: String?, encoding: CookieEncoding) =
if (value == null) cookiePartFlag(name, true) else cookiePart(name, value, encoding)
private inline fun cookiePartExt(name: String, value: String?) =
if (value == null) cookiePartFlag(name, true) else cookiePart(name, value, CookieEncoding.RAW)

private fun String.toIntClamping(): Int = toLong().coerceIn(0L, Int.MAX_VALUE.toLong()).toInt()
36 changes: 36 additions & 0 deletions ktor-http/common/test/io/ktor/tests/http/RenderSetCookieTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 2014-2022 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.tests.http

import io.ktor.http.*
import kotlin.test.*

class RenderSetCookieTest {

@Test
fun renderCookieDoesntEncodeExtensions() {
val cookie = Cookie(
"name",
"value",
encoding = CookieEncoding.BASE64_ENCODING,
extensions = mapOf("foo" to "bar")
)
val rendered = renderSetCookieHeader(cookie)
assertEquals("name=dmFsdWU=; foo=bar; \$x-enc=BASE64_ENCODING", rendered)
}

@Test
fun renderCookieThrowsOnNotEncodedExtensions() {
val cookie = Cookie(
"name",
"value",
encoding = CookieEncoding.BASE64_ENCODING,
extensions = mapOf("foo" to "b,ar")
)
assertFailsWith<IllegalArgumentException> {
renderSetCookieHeader(cookie)
}
}
}

0 comments on commit 69792c3

Please sign in to comment.