Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make HTTP decompression limit configurable #2203

Merged
merged 2 commits into from
Feb 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 6 additions & 1 deletion Sources/Vapor/Server/HTTPServer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ public final class HTTPServer {
/// When `true`, HTTP server will support gzip and deflate compression.
public var supportCompression: Bool

/// Limit of data to decompress when HTTP compression is supported.
public var decompressionLimit: NIOHTTPDecompression.DecompressionLimit

/// When `true`, HTTP server will support pipelined requests.
public var supportPipelining: Bool

Expand All @@ -63,6 +66,7 @@ public final class HTTPServer {
tcpNoDelay: Bool = true,
webSocketMaxFrameSize: Int = 1 << 14,
supportCompression: Bool = false,
decompressionLimit: NIOHTTPDecompression.DecompressionLimit = .ratio(10),
supportPipelining: Bool = false,
supportVersions: Set<HTTPVersionMajor>? = nil,
tlsConfiguration: TLSConfiguration? = nil,
Expand All @@ -77,6 +81,7 @@ public final class HTTPServer {
self.tcpNoDelay = tcpNoDelay
self.webSocketMaxFrameSize = webSocketMaxFrameSize
self.supportCompression = supportCompression
self.decompressionLimit = decompressionLimit
self.supportPipelining = supportPipelining
if let supportVersions = supportVersions {
self.supportVersions = supportVersions
Expand Down Expand Up @@ -338,7 +343,7 @@ private extension ChannelPipeline {

// add response compressor if configured
if configuration.supportCompression {
let requestDecompressionHandler = NIOHTTPRequestDecompressor(limit: .ratio(10))
let requestDecompressionHandler = NIOHTTPRequestDecompressor(limit: configuration.decompressionLimit)
let responseCompressionHandler = HTTPResponseCompressor()

handlers.append(responseCompressionHandler)
Expand Down
38 changes: 38 additions & 0 deletions Tests/VaporTests/ApplicationTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Vapor
import XCTVapor
import COperatingSystem
import AsyncHTTPClient

final class ApplicationTests: XCTestCase {
func testApplicationStop() throws {
Expand Down Expand Up @@ -1117,6 +1118,9 @@ final class ApplicationTests: XCTestCase {
XCTAssertEqual(res.status.code, 201)
req.application.running?.stop()
return "bar"
}.flatMapErrorThrowing {
req.application.running?.stop()
throw $0
}
}

Expand Down Expand Up @@ -1365,6 +1369,33 @@ final class ApplicationTests: XCTestCase {
XCTAssertEqual(bytes.hexEncodedString(), "012a80f0")
XCTAssertEqual(bytes.hexEncodedString(uppercase: true), "012A80F0")
}

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

let smallOrigString = "Hello, world!"
let smallBody = ByteBuffer(base64String: "H4sIAAAAAAAAE/NIzcnJ11Eozy/KSVEEAObG5usNAAA=")! // "Hello, world!"
let bigBody = ByteBuffer(base64String: "H4sIAAAAAAAAE/NIzcnJ11HILU3OgBBJmenpqUUK5flFOSkKJRmJeQpJqWn5RamKAICcGhUqAAAA")! // "Hello, much much bigger world than before!"

app.server.configuration.supportCompression = true
app.server.configuration.decompressionLimit = .size(smallBody.readableBytes) // Max out at the smaller payload (.size is of compressed data)
app.post("gzip") { $0.body.string ?? "" }

let tester = try XCTUnwrap(app.testable(method: .running(port: 8080)))

// Small payload should just barely get through.
_ = try XCTUnwrap(tester.test(.POST, "/gzip", headers: ["Content-Encoding": "gzip"], body: smallBody) { XCTAssertEqual($0.body.string, smallOrigString) })

// Big payload should be hard-rejected. We can't test for the raw NIOHTTPDecompression.DecompressionError.limit error here because
// protocol decoding errors are only ever logged and can't be directly caught.
XCTAssertThrowsError(try tester.test(.POST, "/gzip", headers: ["Content-Encoding": "gzip"], body: bigBody) {
XCTFail("Unexpected response \($0)")
}) { error in
guard let clientError = try? XCTUnwrap(error as? HTTPClientError) else { return } // XCTUnwrap() isn't enough because this closure can't throw, sigh
XCTAssertEqual(clientError, HTTPClientError.remoteConnectionClosed)
}
}
}

extension Application.Responder {
Expand Down Expand Up @@ -1416,4 +1447,11 @@ private extension ByteBuffer {
var string: String? {
return self.getString(at: self.readerIndex, length: self.readableBytes)
}

init?(base64String: String) {
guard let decoded = Data(base64Encoded: base64String) else { return nil }
var buffer = ByteBufferAllocator().buffer(capacity: decoded.count)
buffer.writeBytes(decoded)
self = buffer
}
}