Skip to content

Commit

Permalink
KTOR-1797 Add check for unescaped quote inside quoted header parameter (
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov authored Jan 22, 2021
1 parent 89c627a commit f776d7c
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
30 changes: 29 additions & 1 deletion ktor-http/common/src/io/ktor/http/HeaderValueWithParameters.kt
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,35 @@ private fun String.checkNeedEscape(): Boolean {
return false
}

private fun String.isQuoted(): Boolean = length > 1 && first() == '\"' && last() == '\"'
private fun String.isQuoted(): Boolean {
if (length < 2) {
return false
}
if (first() != '"' || last() != '"') {
return false
}
var startIndex = 1
do {
val index = indexOf('"', startIndex)
if (index == lastIndex) {
break
}

var slashesCount = 0
var slashIndex = index - 1
while (this[slashIndex] == '\\') {
slashesCount++
slashIndex--
}
if (slashesCount % 2 == 0) {
return false
}

startIndex = index + 1
} while (startIndex < length)

return true
}

/**
* Escape string using double quotes
Expand Down
33 changes: 33 additions & 0 deletions ktor-http/common/test/io/ktor/tests/http/HeadersTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,39 @@ class HeadersTest {
}
}

@Test
fun testRenderQuotesIfHasUnescapedQuotes() {
// first
assertEquals(
"""file; k="\"\"vv\""""",
ContentDisposition.File.withParameter("k", """""vv"""").toString()
)
// middle
assertEquals(
"""file; k="\"v\"v\""""",
ContentDisposition.File.withParameter("k", """"v"v"""").toString()
)
// last
assertEquals(
"""file; k="\"vv\"\""""",
ContentDisposition.File.withParameter("k", """"vv""""").toString()
)
// escaped slash
assertEquals(
"""file; k="\"v\\\\\"v\""""",
ContentDisposition.File.withParameter("k", """"v\\"v"""").toString()
)
}

@Test
fun testDoesNotRenderQuotesIfHasEscapedQuotes() {
// middle
assertEquals(
"""file; k="v\"v"""",
ContentDisposition.File.withParameter("k", """"v\"v"""").toString()
)
}

@Test
fun headersOfShouldBeCaseInsensitive() {
val value = "world"
Expand Down

0 comments on commit f776d7c

Please sign in to comment.