Skip to content

Commit

Permalink
fix relative percent decoding in file middleware (#2500)
Browse files Browse the repository at this point in the history
  • Loading branch information
tanner0101 authored Sep 30, 2020
1 parent 236c616 commit cf1651f
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
8 changes: 5 additions & 3 deletions Sources/Vapor/Middleware/FileMiddleware.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ public final class FileMiddleware: Middleware {

/// See `Middleware`.
public func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
// make a copy of the path
var path = request.url.path
// make a copy of the percent-decoded path
guard var path = request.url.path.removingPercentEncoding else {
return request.eventLoop.makeFailedFuture(Abort(.badRequest))
}

// path must be relative.
while path.hasPrefix("/") {
Expand All @@ -27,7 +29,7 @@ public final class FileMiddleware: Middleware {
}

// create absolute file path
let filePath = self.publicDirectory + (path.removingPercentEncoding ?? path)
let filePath = self.publicDirectory + path

// check if file exists and is not a directory
var isDir: ObjCBool = false
Expand Down
15 changes: 15 additions & 0 deletions Tests/VaporTests/FileTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,19 @@ final class FileTests: XCTestCase {
XCTAssertEqual(res.body.string, "<h1>Hello</h1>\n")
}
}

func testPercentDecodedRelativePath() throws {
let app = Application(.testing)
defer { app.shutdown() }

let path = #file.split(separator: "/").dropLast().joined(separator: "/")
app.middleware.use(FileMiddleware(publicDirectory: "/" + path))

try app.test(.GET, "%2e%2e/VaporTests/Utilities/foo.txt") { res in
XCTAssertEqual(res.status, .forbidden)
}.test(.GET, "Utilities/foo.txt") { res in
XCTAssertEqual(res.status, .ok)
XCTAssertEqual(res.body.string, "bar\n")
}
}
}
1 change: 1 addition & 0 deletions Tests/VaporTests/Utilities/foo.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
bar

0 comments on commit cf1651f

Please sign in to comment.