diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 5744b66f7..da3fa33a6 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -128,6 +128,16 @@ private func correctlyFrameTransportHeaders(hasBody: HTTPMethod.HasBody, headers } } +/// Validates the response/request headers to ensure that we correctly send the body with chunked transfer +/// encoding, when needed. +private func messageIsChunked(headers: HTTPHeaders, version: HTTPVersion) -> Bool { + if version.major == 1 && version.minor >= 1 { + return headers.first(name: "transfer-encoding") == "chunked" ? true : false + } else { + return false + } +} + /// A `ChannelOutboundHandler` that can serialize HTTP requests. /// /// This channel handler is used to translate messages from a series of @@ -136,9 +146,37 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH public typealias OutboundIn = HTTPClientRequestPart public typealias OutboundOut = IOData + /// Configuration for the ``HTTPRequestEncoder``. + /// + /// This object controls the behaviour of the ``HTTPRequestEncoder``. It enables users to + /// change the default behaviour of the type to better handle a wide range of use-cases. + public struct Configuration: Sendable, Hashable { + /// Whether the ``HTTPRequestEncoder`` should automatically add `Content-Length` or + /// `Transfer-Encoding` headers when appropriate. + /// + /// Defaults to `true`. + /// + /// Set to `false` if you are confident you are appropriately setting these framing + /// headers yourself, to skip NIO's transformation. + public var automaticallySetFramingHeaders: Bool + + public init() { + self.automaticallySetFramingHeaders = true + } + } + private var isChunked = false - public init () { } + private var configuration: Configuration + + public convenience init() { + self.init(configuration: Configuration()) + } + + public init(configuration: Configuration) { + self.configuration = configuration + } + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.unwrapOutboundIn(data) { @@ -146,8 +184,12 @@ public final class HTTPRequestEncoder: ChannelOutboundHandler, RemovableChannelH assert(!(request.headers.contains(name: "content-length") && request.headers[canonicalForm: "transfer-encoding"].contains("chunked"[...])), "illegal HTTP sent: \(request) contains both a content-length and transfer-encoding:chunked") - self.isChunked = correctlyFrameTransportHeaders(hasBody: request.method.hasRequestBody, - headers: &request.headers, version: request.version) == .chunked + if self.configuration.automaticallySetFramingHeaders { + self.isChunked = correctlyFrameTransportHeaders(hasBody: request.method.hasRequestBody, + headers: &request.headers, version: request.version) == .chunked + } else { + self.isChunked = messageIsChunked(headers: request.headers, version: request.version) + } writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(request: request) @@ -177,9 +219,36 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel public typealias OutboundIn = HTTPServerResponsePart public typealias OutboundOut = IOData + /// Configuration for the ``HTTPResponseEncoder``. + /// + /// This object controls the behaviour of the ``HTTPResponseEncoder``. It enables users to + /// change the default behaviour of the type to better handle a wide range of use-cases. + public struct Configuration: Sendable, Hashable { + /// Whether the ``HTTPResponseEncoder`` should automatically add `Content-Length` or + /// `Transfer-Encoding` headers when appropriate. + /// + /// Defaults to `true`. + /// + /// Set to `false` if you are confident you are appropriately setting these framing + /// headers yourself, to skip NIO's transformation. + public var automaticallySetFramingHeaders: Bool + + public init() { + self.automaticallySetFramingHeaders = true + } + } + private var isChunked = false - public init () { } + private var configuration: Configuration + + public convenience init() { + self.init(configuration: Configuration()) + } + + public init(configuration: Configuration) { + self.configuration = configuration + } public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch self.unwrapOutboundIn(data) { @@ -187,8 +256,13 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel assert(!(response.headers.contains(name: "content-length") && response.headers[canonicalForm: "transfer-encoding"].contains("chunked"[...])), "illegal HTTP sent: \(response) contains both a content-length and transfer-encoding:chunked") - self.isChunked = correctlyFrameTransportHeaders(hasBody: response.status.mayHaveResponseBody ? .yes : .no, - headers: &response.headers, version: response.version) == .chunked + + if self.configuration.automaticallySetFramingHeaders { + self.isChunked = correctlyFrameTransportHeaders(hasBody: response.status.mayHaveResponseBody ? .yes : .no, + headers: &response.headers, version: response.version) == .chunked + } else { + self.isChunked = messageIsChunked(headers: response.headers, version: response.version) + } writeHead(wrapOutboundOut: self.wrapOutboundOut, writeStartLine: { buffer in buffer.write(response: response) diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index d65fe9bd5..251143f95 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -162,7 +162,50 @@ extension ChannelPipeline { return future } - + + /// Configure a `ChannelPipeline` for use as a HTTP client. + /// + /// - parameters: + /// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`. + /// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder` + /// from the pipeline. + /// - enableOutboundHeaderValidation: Whether the pipeline should confirm that outbound headers are well-formed. + /// Defaults to `true`. + /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. + /// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for + /// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientUpgradeHandler`` and + /// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler`` + /// for more details. + /// - returns: An `EventLoopFuture` that will fire when the pipeline is configured. + public func addHTTPClientHandlers(position: Position = .last, + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + enableOutboundHeaderValidation: Bool = true, + encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), + withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil) -> EventLoopFuture { + let future: EventLoopFuture + + if self.eventLoop.inEventLoop { + let result = Result { + try self.syncOperations.addHTTPClientHandlers(position: position, + leftOverBytesStrategy: leftOverBytesStrategy, + enableOutboundHeaderValidation: enableOutboundHeaderValidation, + encoderConfiguration: encoderConfiguration, + withClientUpgrade: upgrade) + } + future = self.eventLoop.makeCompletedFuture(result) + } else { + future = self.eventLoop.submit { + return try self.syncOperations.addHTTPClientHandlers(position: position, + leftOverBytesStrategy: leftOverBytesStrategy, + enableOutboundHeaderValidation: enableOutboundHeaderValidation, + encoderConfiguration: encoderConfiguration, + withClientUpgrade: upgrade) + } + } + + return future + } + #if swift(>=5.7) /// Configure a `ChannelPipeline` for use as a HTTP server. /// @@ -282,12 +325,63 @@ extension ChannelPipeline { withOutboundHeaderValidation: headerValidation ) } - - private func _configureHTTPServerPipeline(position: ChannelPipeline.Position = .last, - withPipeliningAssistance pipelining: Bool = true, - withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, - withErrorHandling errorHandling: Bool = true, - withOutboundHeaderValidation headerValidation: Bool = true) -> EventLoopFuture { + + /// Configure a `ChannelPipeline` for use as a HTTP server. + /// + /// This function knows how to set up all first-party HTTP channel handlers appropriately + /// for server use. It supports the following features: + /// + /// 1. Providing assistance handling clients that pipeline HTTP requests, using the + /// ``HTTPServerPipelineHandler``. + /// 2. Supporting HTTP upgrade, using the ``HTTPServerUpgradeHandler``. + /// 3. Providing assistance handling protocol errors. + /// 4. Validating outbound header fields to protect against response splitting attacks. + /// + /// This method will likely be extended in future with more support for other first-party + /// features. + /// + /// - parameters: + /// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`. + /// - pipelining: Whether to provide assistance handling HTTP clients that pipeline + /// their requests. Defaults to `true`. If `false`, users will need to handle + /// clients that pipeline themselves. + /// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If + /// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade + /// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more + /// details. + /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. + /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. + /// - headerValidation: Whether to validate outbound request headers to confirm that they meet + /// spec compliance. Defaults to `true`. + /// - encoderConfiguration: The configuration for the ``HTTPResponseEncoder``. + /// - returns: An `EventLoopFuture` that will fire when the pipeline is configured. + public func configureHTTPServerPipeline( + position: ChannelPipeline.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init() + ) -> EventLoopFuture { + self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) + } + + private func _configureHTTPServerPipeline( + position: ChannelPipeline.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init() + ) -> EventLoopFuture { let future: EventLoopFuture if self.eventLoop.inEventLoop { @@ -296,7 +390,8 @@ extension ChannelPipeline { withPipeliningAssistance: pipelining, withServerUpgrade: upgrade, withErrorHandling: errorHandling, - withOutboundHeaderValidation: headerValidation) + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration) } future = self.eventLoop.makeCompletedFuture(result) } else { @@ -305,7 +400,8 @@ extension ChannelPipeline { withPipeliningAssistance: pipelining, withServerUpgrade: upgrade, withErrorHandling: errorHandling, - withOutboundHeaderValidation: headerValidation) + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration) } } @@ -383,9 +479,35 @@ extension ChannelPipeline.SynchronousOperations { withClientUpgrade: upgrade) } + /// Configure a `ChannelPipeline` for use as a HTTP client. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - parameters: + /// - position: The position in the `ChannelPipeline` where to add the HTTP client handlers. Defaults to `.last`. + /// - leftOverBytesStrategy: The strategy to use when dealing with leftover bytes after removing the `HTTPDecoder` + /// from the pipeline. + /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. + /// - upgrade: Add a ``NIOHTTPClientUpgradeHandler`` to the pipeline, configured for + /// HTTP upgrade. Should be a tuple of an array of ``NIOHTTPClientProtocolUpgrader`` and + /// the upgrade completion handler. See the documentation on ``NIOHTTPClientUpgradeHandler`` + /// for more details. + /// - throws: If the pipeline could not be configured. + public func addHTTPClientHandlers(position: ChannelPipeline.Position = .last, + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + enableOutboundHeaderValidation: Bool = true, + encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), + withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil) throws { + try self._addHTTPClientHandlers(position: position, + leftOverBytesStrategy: leftOverBytesStrategy, + enableOutboundHeaderValidation: enableOutboundHeaderValidation, + encoderConfiguration: encoderConfiguration, + withClientUpgrade: upgrade) + } + private func _addHTTPClientHandlers(position: ChannelPipeline.Position = .last, leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, enableOutboundHeaderValidation: Bool = true, + encoderConfiguration: HTTPRequestEncoder.Configuration = .init(), withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration? = nil) throws { // Why two separate functions? With the fast-path (no upgrader, yes header validator) we can promote the Array of handlers // to the stack and skip an allocation. @@ -393,17 +515,20 @@ extension ChannelPipeline.SynchronousOperations { try self._addHTTPClientHandlersFallback(position: position, leftOverBytesStrategy: leftOverBytesStrategy, enableOutboundHeaderValidation: enableOutboundHeaderValidation, + encoderConfiguration: encoderConfiguration, withClientUpgrade: upgrade) } else { try self._addHTTPClientHandlers(position: position, - leftOverBytesStrategy: leftOverBytesStrategy) + leftOverBytesStrategy: leftOverBytesStrategy, + encoderConfiguration: encoderConfiguration) } } private func _addHTTPClientHandlers(position: ChannelPipeline.Position, - leftOverBytesStrategy: RemoveAfterUpgradeStrategy) throws { + leftOverBytesStrategy: RemoveAfterUpgradeStrategy, + encoderConfiguration: HTTPRequestEncoder.Configuration) throws { self.eventLoop.assertInEventLoop() - let requestEncoder = HTTPRequestEncoder() + let requestEncoder = HTTPRequestEncoder(configuration: encoderConfiguration) let responseDecoder = HTTPResponseDecoder(leftOverBytesStrategy: leftOverBytesStrategy) let requestHeaderValidator = NIOHTTPRequestHeadersValidator() let handlers: [ChannelHandler] = [requestEncoder, ByteToMessageHandler(responseDecoder), requestHeaderValidator] @@ -413,9 +538,10 @@ extension ChannelPipeline.SynchronousOperations { private func _addHTTPClientHandlersFallback(position: ChannelPipeline.Position, leftOverBytesStrategy: RemoveAfterUpgradeStrategy, enableOutboundHeaderValidation: Bool, + encoderConfiguration: HTTPRequestEncoder.Configuration, withClientUpgrade upgrade: NIOHTTPClientUpgradeConfiguration?) throws { self.eventLoop.assertInEventLoop() - let requestEncoder = HTTPRequestEncoder() + let requestEncoder = HTTPRequestEncoder(configuration: encoderConfiguration) let responseDecoder = HTTPResponseDecoder(leftOverBytesStrategy: leftOverBytesStrategy) var handlers: [RemovableChannelHandler] = [requestEncoder, ByteToMessageHandler(responseDecoder)] @@ -554,15 +680,63 @@ extension ChannelPipeline.SynchronousOperations { withOutboundHeaderValidation: headerValidation ) } - + + /// Configure a `ChannelPipeline` for use as a HTTP server. + /// + /// This function knows how to set up all first-party HTTP channel handlers appropriately + /// for server use. It supports the following features: + /// + /// 1. Providing assistance handling clients that pipeline HTTP requests, using the + /// `HTTPServerPipelineHandler`. + /// 2. Supporting HTTP upgrade, using the `HTTPServerUpgradeHandler`. + /// 3. Providing assistance handling protocol errors. + /// 4. Validating outbound header fields to protect against response splitting attacks. + /// + /// This method will likely be extended in future with more support for other first-party + /// features. + /// + /// - important: This **must** be called on the Channel's event loop. + /// - parameters: + /// - position: Where in the pipeline to add the HTTP server handlers, defaults to `.last`. + /// - pipelining: Whether to provide assistance handling HTTP clients that pipeline + /// their requests. Defaults to `true`. If `false`, users will need to handle + /// clients that pipeline themselves. + /// - upgrade: Whether to add a `HTTPServerUpgradeHandler` to the pipeline, configured for + /// HTTP upgrade. Defaults to `nil`, which will not add the handler to the pipeline. If + /// provided should be a tuple of an array of `HTTPServerProtocolUpgrader` and the upgrade + /// completion handler. See the documentation on `HTTPServerUpgradeHandler` for more + /// details. + /// - errorHandling: Whether to provide assistance handling protocol errors (e.g. + /// failure to parse the HTTP request) by sending 400 errors. Defaults to `true`. + /// - headerValidation: Whether to validate outbound request headers to confirm that they meet + /// spec compliance. Defaults to `true`. + /// - encoderConfiguration: The configuration for the ``HTTPRequestEncoder``. + /// - throws: If the pipeline could not be configured. + public func configureHTTPServerPipeline(position: ChannelPipeline.Position = .last, + withPipeliningAssistance pipelining: Bool = true, + withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, + withErrorHandling errorHandling: Bool = true, + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration) throws { + try self._configureHTTPServerPipeline( + position: position, + withPipeliningAssistance: pipelining, + withServerUpgrade: upgrade, + withErrorHandling: errorHandling, + withOutboundHeaderValidation: headerValidation, + withEncoderConfiguration: encoderConfiguration + ) + } + private func _configureHTTPServerPipeline(position: ChannelPipeline.Position = .last, withPipeliningAssistance pipelining: Bool = true, withServerUpgrade upgrade: NIOHTTPServerUpgradeConfiguration? = nil, withErrorHandling errorHandling: Bool = true, - withOutboundHeaderValidation headerValidation: Bool = true) throws { + withOutboundHeaderValidation headerValidation: Bool = true, + withEncoderConfiguration encoderConfiguration: HTTPResponseEncoder.Configuration = .init()) throws { self.eventLoop.assertInEventLoop() - let responseEncoder = HTTPResponseEncoder() + let responseEncoder = HTTPResponseEncoder(configuration: encoderConfiguration) let requestDecoder = HTTPRequestDecoder(leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes) var handlers: [RemovableChannelHandler] = [responseEncoder, ByteToMessageHandler(requestDecoder)] diff --git a/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift index f2ae117df..7ceebab4c 100644 --- a/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPRequestEncoderTest.swift @@ -23,14 +23,26 @@ private extension ByteBuffer { } } +extension HTTPRequestEncoder.Configuration { + fileprivate static let noFramingTransformation: HTTPRequestEncoder.Configuration = { + var config = HTTPRequestEncoder.Configuration() + config.automaticallySetFramingHeaders = false + return config + }() +} + class HTTPRequestEncoderTests: XCTestCase { - private func sendRequest(withMethod method: HTTPMethod, andHeaders headers: HTTPHeaders) throws -> ByteBuffer { + private func sendRequest( + withMethod method: HTTPMethod, + andHeaders headers: HTTPHeaders, + configuration: HTTPRequestEncoder.Configuration = .init() + ) throws -> ByteBuffer { let channel = EmbeddedChannel() defer { XCTAssertEqual(true, try? channel.finish().isClean) } - try channel.pipeline.addHandler(HTTPRequestEncoder()).wait() + try channel.pipeline.addHandler(HTTPRequestEncoder(configuration: configuration)).wait() var request = HTTPRequestHead(version: .http1_1, method: method, uri: "/uri") request.headers = headers try channel.writeOutbound(HTTPClientRequestPart.head(request)) @@ -51,6 +63,11 @@ class HTTPRequestEncoderTests: XCTestCase { writtenData.assertContainsOnly("GET /uri HTTP/1.1\r\n\r\n") } + func testNoAutoHeadersForPOSTWhenDisabled() throws { + let writtenData = try sendRequest(withMethod: .POST, andHeaders: HTTPHeaders(), configuration: .noFramingTransformation) + writtenData.assertContainsOnly("POST /uri HTTP/1.1\r\n\r\n") + } + func testGETContentHeadersLeftAlone() throws { var headers = HTTPHeaders([("content-length", "17")]) var writtenData = try sendRequest(withMethod: .GET, andHeaders: headers) @@ -79,12 +96,24 @@ class HTTPRequestEncoderTests: XCTestCase { writtenData.assertContainsOnly("TRACE /uri HTTP/1.1\r\n\r\n") } + func testAllowContentLengthHeadersWhenForced_forTRACE() throws { + let headers = HTTPHeaders([("content-length", "0")]) + let writtenData = try sendRequest(withMethod: .TRACE, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("TRACE /uri HTTP/1.1\r\ncontent-length: 0\r\n\r\n") + } + func testNoTransferEncodingHeadersForTRACE() throws { let headers = HTTPHeaders([("transfer-encoding", "chunked")]) let writtenData = try sendRequest(withMethod: .TRACE, andHeaders: headers) writtenData.assertContainsOnly("TRACE /uri HTTP/1.1\r\n\r\n") } + func testAllowTransferEncodingHeadersWhenForced_forTRACE() throws { + let headers = HTTPHeaders([("transfer-encoding", "chunked")]) + let writtenData = try sendRequest(withMethod: .TRACE, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("TRACE /uri HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n") + } + func testNoChunkedEncodingForHTTP10() throws { let channel = EmbeddedChannel() defer { @@ -265,6 +294,110 @@ class HTTPRequestEncoderTests: XCTestCase { XCTAssertNoThrow(XCTAssertTrue(try channel.finish().isClean)) } + func testFullPipelineCanDisableFramingHeaders_withFutures() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertEqual(true, try? channel.finish().isClean) + } + + try channel.pipeline.addHTTPClientHandlers(encoderConfiguration: .noFramingTransformation).wait() + let request = HTTPRequestHead(version: .http1_1, method: .POST, uri: "/uri") + try channel.writeOutbound(HTTPClientRequestPart.head(request)) + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + buffer.assertContainsOnly("POST /uri HTTP/1.1\r\n\r\n") + } + + func testFullPipelineCanDisableFramingHeaders_syncOperations() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertEqual(true, try? channel.finish().isClean) + } + + try channel.pipeline.syncOperations.addHTTPClientHandlers(encoderConfiguration: .noFramingTransformation) + let request = HTTPRequestHead(version: .http1_1, method: .POST, uri: "/uri") + try channel.writeOutbound(HTTPClientRequestPart.head(request)) + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + buffer.assertContainsOnly("POST /uri HTTP/1.1\r\n\r\n") + } + + func testFullPipelineCanDisableFramingHeaders_sendWithoutChunked() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertEqual(true, try? channel.finish().isClean) + } + + try channel.pipeline.addHTTPClientHandlers(encoderConfiguration: .noFramingTransformation).wait() + let request = HTTPRequestHead(version: .http1_1, method: .POST, uri: "/uri") + try channel.writeOutbound(HTTPClientRequestPart.head(request)) + guard let headBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + headBuffer.assertContainsOnly("POST /uri HTTP/1.1\r\n\r\n") + + let body = ByteBuffer(string: "hello world!") + try channel.writeOutbound(HTTPClientRequestPart.body(.byteBuffer(body))) + guard let bodyBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(bodyBuffer, body) + + try channel.writeOutbound(HTTPClientRequestPart.end(nil)) + guard let trailerBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(trailerBuffer.readableBytes, 0) + } + + func testFullPipelineCanDisableFramingHeaders_sendWithChunked() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertEqual(true, try? channel.finish().isClean) + } + + try channel.pipeline.addHTTPClientHandlers(encoderConfiguration: .noFramingTransformation).wait() + let request = HTTPRequestHead(version: .http1_1, method: .POST, uri: "/uri", headers: ["transfer-encoding": "chunked"]) + try channel.writeOutbound(HTTPClientRequestPart.head(request)) + guard let headBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + headBuffer.assertContainsOnly("POST /uri HTTP/1.1\r\ntransfer-encoding: chunked\r\n\r\n") + + let body = ByteBuffer(string: "hello world!") + try channel.writeOutbound(HTTPClientRequestPart.body(.byteBuffer(body))) + guard let prefixBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + guard let bodyBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + guard let suffixBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(prefixBuffer, ByteBuffer(string: "c\r\n")) + XCTAssertEqual(bodyBuffer, body) + XCTAssertEqual(suffixBuffer, ByteBuffer(string: "\r\n")) + + try channel.writeOutbound(HTTPClientRequestPart.end(nil)) + guard let trailerBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(trailerBuffer, ByteBuffer(string: "0\r\n\r\n")) + } + private func assertOutboundContainsOnly(_ channel: EmbeddedChannel, _ expected: String) { XCTAssertNoThrow(XCTAssertNotNil(try channel.readOutbound(as: ByteBuffer.self).map { buffer in buffer.assertContainsOnly(expected) diff --git a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift index 5f0169779..0a4a38a50 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift @@ -23,14 +23,26 @@ private extension ByteBuffer { } } +extension HTTPResponseEncoder.Configuration { + fileprivate static let noFramingTransformation: HTTPResponseEncoder.Configuration = { + var config = HTTPResponseEncoder.Configuration() + config.automaticallySetFramingHeaders = false + return config + }() +} + class HTTPResponseEncoderTests: XCTestCase { - private func sendResponse(withStatus status: HTTPResponseStatus, andHeaders headers: HTTPHeaders) -> ByteBuffer { + private func sendResponse( + withStatus status: HTTPResponseStatus, + andHeaders headers: HTTPHeaders, + configuration: HTTPResponseEncoder.Configuration = .init() + ) -> ByteBuffer { let channel = EmbeddedChannel() defer { XCTAssertEqual(true, try? channel.finish().isClean) } - XCTAssertNoThrow(try channel.pipeline.addHandler(HTTPResponseEncoder()).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(HTTPResponseEncoder(configuration: configuration)).wait()) var switchingResponse = HTTPResponseHead(version: .http1_1, status: status) switchingResponse.headers = headers XCTAssertNoThrow(try channel.writeOutbound(HTTPServerResponsePart.head(switchingResponse))) @@ -64,42 +76,83 @@ class HTTPResponseEncoderTests: XCTestCase { writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") } + func testNoAutoHeadersWhenDisabled() throws { + let writtenData = sendResponse(withStatus: .ok, andHeaders: HTTPHeaders(), configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 200 OK\r\n\r\n") + } + func testNoContentLengthHeadersFor101() throws { let headers = HTTPHeaders([("content-length", "0")]) let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\n\r\n") } + func testAllowContentLengthHeadersWhenForced_for101() throws { + let headers = HTTPHeaders([("content-length", "0")]) + let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\ncontent-length: 0\r\n\r\n") + } + func testNoContentLengthHeadersForCustom1XX() throws { let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("content-length", "0")]) let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload; as=style\r\n\r\n") } + func testAllowContentLengthHeadersWhenForced_forCustom1XX() throws { + let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("content-length", "0")]) + let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload; as=style\r\ncontent-length: 0\r\n\r\n") + } + func testNoContentLengthHeadersFor204() throws { let headers = HTTPHeaders([("content-length", "0")]) let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") } + func testAllowContentLengthHeadersWhenForced_For204() throws { + let headers = HTTPHeaders([("content-length", "0")]) + let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\ncontent-length: 0\r\n\r\n") + } + func testNoTransferEncodingHeadersFor101() throws { let headers = HTTPHeaders([("transfer-encoding", "chunked")]) let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\n\r\n") } + func testAllowTransferEncodingHeadersWhenForced_for101() throws { + let headers = HTTPHeaders([("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .switchingProtocols, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 101 Switching Protocols\r\ntransfer-encoding: chunked\r\n\r\n") + } + func testNoTransferEncodingHeadersForCustom1XX() throws { let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("transfer-encoding", "chunked")]) let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload; as=style\r\n\r\n") } + func testAllowTransferEncodingHeadersWhenForced_forCustom1XX() throws { + let headers = HTTPHeaders([("Link", "; rel=preload; as=style"), ("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .custom(code: 103, reasonPhrase: "Early Hints"), andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 103 Early Hints\r\nLink: ; rel=preload; as=style\r\ntransfer-encoding: chunked\r\n\r\n") + } + func testNoTransferEncodingHeadersFor204() throws { let headers = HTTPHeaders([("transfer-encoding", "chunked")]) let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\n\r\n") } + func testAllowTransferEncodingHeadersWhenForced_for204() throws { + let headers = HTTPHeaders([("transfer-encoding", "chunked")]) + let writtenData = sendResponse(withStatus: .noContent, andHeaders: headers, configuration: .noFramingTransformation) + writtenData.assertContainsOnly("HTTP/1.1 204 No Content\r\ntransfer-encoding: chunked\r\n\r\n") + } + func testNoChunkedEncodingForHTTP10() throws { let channel = EmbeddedChannel() defer { @@ -118,4 +171,128 @@ class HTTPResponseEncoderTests: XCTestCase { let writtenResponse = b.getString(at: b.readerIndex, length: b.readableBytes)! XCTAssertEqual(writtenResponse, "HTTP/1.0 200 OK\r\n\r\n") } + + func testFullPipelineCanDisableFramingHeaders_withFuture() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + XCTAssertNoThrow(try channel.pipeline.configureHTTPServerPipeline(withEncoderConfiguration: .noFramingTransformation).wait()) + let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") + XCTAssertNoThrow(try channel.writeInbound(request)) + + let response = HTTPResponseHead(version: .http1_1, status: .ok) + XCTAssertNoThrow(try channel.writeOutbound(HTTPServerResponsePart.head(response))) + + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Could not read buffer") + return + } + + buffer.assertContainsOnly("HTTP/1.1 200 OK\r\n\r\n") + } + + func testFullPipelineCanDisableFramingHeaders_syncOperations() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(withEncoderConfiguration: .noFramingTransformation)) + let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") + XCTAssertNoThrow(try channel.writeInbound(request)) + + let response = HTTPResponseHead(version: .http1_1, status: .ok) + XCTAssertNoThrow(try channel.writeOutbound(HTTPServerResponsePart.head(response))) + + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Could not read buffer") + return + } + + buffer.assertContainsOnly("HTTP/1.1 200 OK\r\n\r\n") + } + + func testFullPipelineCanDisableFramingHeaders_sendWithoutChunked() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(withEncoderConfiguration: .noFramingTransformation)) + let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") + XCTAssertNoThrow(try channel.writeInbound(request)) + + let response = HTTPResponseHead(version: .http1_1, status: .ok) + XCTAssertNoThrow(try channel.writeOutbound(HTTPServerResponsePart.head(response))) + + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Could not read buffer") + return + } + + buffer.assertContainsOnly("HTTP/1.1 200 OK\r\n\r\n") + + let body = ByteBuffer(string: "hello world!") + try channel.writeOutbound(HTTPServerResponsePart.body(.byteBuffer(body))) + guard let bodyBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(bodyBuffer, body) + + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + guard let trailerBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(trailerBuffer.readableBytes, 0) + } + + func testFullPipelineCanDisableFramingHeaders_sendWithChunked() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try channel.finish()) + } + + XCTAssertNoThrow(try channel.pipeline.syncOperations.configureHTTPServerPipeline(withEncoderConfiguration: .noFramingTransformation)) + let request = ByteBuffer(string: "GET / HTTP/1.1\r\n\r\n") + XCTAssertNoThrow(try channel.writeInbound(request)) + + let response = HTTPResponseHead(version: .http1_1, status: .ok, headers: ["transfer-encoding": "chunked"]) + XCTAssertNoThrow(try channel.writeOutbound(HTTPServerResponsePart.head(response))) + + guard let buffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Could not read buffer") + return + } + + buffer.assertContainsOnly("HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n") + + let body = ByteBuffer(string: "hello world!") + try channel.writeOutbound(HTTPServerResponsePart.body(.byteBuffer(body))) + guard let prefixBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + guard let bodyBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + guard let suffixBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(prefixBuffer, ByteBuffer(string: "c\r\n")) + XCTAssertEqual(bodyBuffer, body) + XCTAssertEqual(suffixBuffer, ByteBuffer(string: "\r\n")) + + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + guard let trailerBuffer = try channel.readOutbound(as: ByteBuffer.self) else { + XCTFail("Unable to read buffer") + return + } + XCTAssertEqual(trailerBuffer, ByteBuffer(string: "0\r\n\r\n")) + } }