Skip to content

Commit

Permalink
Merge pull request #4654 from ScalaWilliam/file-under-file-exception
Browse files Browse the repository at this point in the history
FileService: Querying /file.png/anything where /file.png is a file throws
  • Loading branch information
rossabaker committed Mar 29, 2021
2 parents 58002ee + 8e46331 commit 40f5e44
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import cats.data.{Kleisli, NonEmptyList, OptionT}
import cats.effect.{Blocker, ContextShift, Sync}
import cats.syntax.all._
import java.io.File
import java.nio.file.NoSuchFileException
import java.nio.file.{LinkOption, Path, Paths}
import java.nio.file.{Files, LinkOption, NoSuchFileException, Path, Paths}
import org.http4s.headers.Range.SubRange
import org.http4s.headers._
import org.http4s.server.middleware.TranslateUri
Expand Down Expand Up @@ -86,13 +85,16 @@ object FileService {
case _ => OptionT.none
}
resolvedPath
.semiflatMap(path => F.delay(path.toRealPath(LinkOption.NOFOLLOW_LINKS)))
.flatMapF(path =>
F.delay(
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS))
Some(path.toRealPath(LinkOption.NOFOLLOW_LINKS))
else None))
.collect { case path if path.startsWith(rootPath) => path.toFile }
.flatMap(f => config.pathCollector(f, config, request))
.semiflatMap(config.cacheStrategy.cache(request.pathInfo, _))
.recoverWith {
case _: NoSuchFileException => OptionT.none
case BadTraversal => OptionT.some(Response(Status.BadRequest))
.recoverWith { case BadTraversal =>
OptionT.some(Response(Status.BadRequest))
}
})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,11 @@ class FileServiceSuite extends Http4sSuite with StaticContentShared {
routes.orNotFound(req).map(_.status).assertEquals(Status.Ok)
}

test("Return a 404 for a resource under an existing file") {
val req = Request[IO](uri = uri"/testresource.txt/test")
routes.orNotFound(req).map(_.status).assertEquals(Status.NotFound)
}

test("Decodes path segments") {
val req = Request[IO](uri = uri"/space+truckin%27.txt")
routes.orNotFound(req).map(_.status).assertEquals(Status.Ok)
Expand Down

0 comments on commit 40f5e44

Please sign in to comment.