Skip to content

Commit

Permalink
fix(api-formats): Gracefully handle invalid Accept header quality
Browse files Browse the repository at this point in the history
Wrap `toDouble` operation in a try to handle cases where invalid string cannot be converted to a double.
  • Loading branch information
acote-coveo committed Jul 12, 2024
1 parent ff69aeb commit c73dd26
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
8 changes: 4 additions & 4 deletions core/src/main/scala/org/scalatra/ApiFormats.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package org.scalatra
import java.util.Locale.ENGLISH
import java.util.concurrent.ConcurrentHashMap
import org.scalatra.ServletCompat.http.{ HttpServletRequest, HttpServletResponse }
import org.scalatra.util.RicherString.*

import org.scalatra.util.RicherString._

import scala.jdk.CollectionConverters._
import scala.jdk.CollectionConverters.*
import scala.collection.concurrent
import scala.util.Try

object ApiFormats {

Expand Down Expand Up @@ -113,7 +113,7 @@ trait ApiFormats extends ScalatraBase {

private def parseAcceptHeader(implicit request: HttpServletRequest): List[String] = {
def isValidQPair(a: Array[String]) = {
a.length == 2 && a(0) == "q" && validRange.contains(a(1).toDouble)
a.length == 2 && a(0) == "q" && Try(a(1).toDouble).toOption.exists(validRange.contains)
}

request.headers.get("Accept") map { s =>
Expand Down
7 changes: 7 additions & 0 deletions core/src/test/scala/org/scalatra/ApiFormatsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ class ApiFormatsSpec extends MutableScalatraSpec {
body must_== "txt"
}
}

"when the priory value is not a double the parser should ignore the broken priority" in {
get("/hello", headers = Map("Accept" -> "application/json; q=0.8 oops, text/plain, */*")) {
response.getContentType() must startWith("text/plain")
body must_== "txt"
}
}
}
}
}

0 comments on commit c73dd26

Please sign in to comment.