diff --git a/Sources/NIOHTTP1/HTTPDecoder.swift b/Sources/NIOHTTP1/HTTPDecoder.swift index e4d8bb59e..888bf9df8 100644 --- a/Sources/NIOHTTP1/HTTPDecoder.swift +++ b/Sources/NIOHTTP1/HTTPDecoder.swift @@ -591,6 +591,12 @@ public final class HTTPDecoder: ByteToMessageDecoder, HTTPDecoderDelega private var stopParsing = false // set on upgrade or HTTP version error private var lastResponseHeaderWasInformational = false + /// The paired response encoder, if any, that this (server request) decoder feeds decoded + /// request methods to so it can omit the body from responses to `HEAD`/`CONNECT` requests. + /// Set via the internal initializer used by `configureHTTPServerPipeline`; `nil` otherwise + /// (client decoding, or direct use), in which case decoding is unaffected. + private var responseEncoder: HTTPResponseEncoder? = nil + /// Creates a new instance of `HTTPDecoder`. /// /// - Parameters: @@ -644,6 +650,23 @@ public final class HTTPDecoder: ByteToMessageDecoder, HTTPDecoderDelega self.informationalResponseStrategy = informationalResponseStrategy } + /// Creates a request decoder that feeds each decoded request's method to `responseEncoder`, so + /// it can omit the body from responses to `HEAD`/`CONNECT` requests. Used by + /// `configureHTTPServerPipeline`. + internal convenience init( + leftOverBytesStrategy: RemoveAfterUpgradeStrategy = .dropBytes, + informationalResponseStrategy: NIOInformationalResponseStrategy = .drop, + limitConfiguration: NIOHTTPDecoderLimitConfiguration = .init(), + responseEncoder: HTTPResponseEncoder + ) { + self.init( + leftOverBytesStrategy: leftOverBytesStrategy, + informationalResponseStrategy: informationalResponseStrategy, + limitConfiguration: limitConfiguration + ) + self.responseEncoder = responseEncoder + } + func didReceiveBody(_ bytes: UnsafeRawBufferPointer) { let offset = self.buffer!.withUnsafeReadableBytes { allBytes -> Int in let offset = bytes.baseAddress! - allBytes.baseAddress! @@ -730,6 +753,9 @@ public final class HTTPDecoder: ByteToMessageDecoder, HTTPDecoderDelega keepAliveState: keepAliveState ) ) + // Record the method so the paired response encoder can omit the body from responses to + // HEAD/CONNECT requests. No-op unless an encoder was wired up (server pipeline). + self.responseEncoder?.recordRequestMethod(reqHead.method) message = NIOAny(HTTPServerRequestPart.head(reqHead)) case .response where (100..<200).contains(statusCode) && statusCode != 101: diff --git a/Sources/NIOHTTP1/HTTPEncoder.swift b/Sources/NIOHTTP1/HTTPEncoder.swift index 87205fca5..f53a013d5 100644 --- a/Sources/NIOHTTP1/HTTPEncoder.swift +++ b/Sources/NIOHTTP1/HTTPEncoder.swift @@ -278,6 +278,23 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel private var isChunked = false + /// Set while writing a response to a `HEAD` or `CONNECT` request. While set, response body + /// bytes and the end-of-body marker (including the chunked terminator) are suppressed, while + /// the framing headers on the response head are preserved so the response still advertises + /// what an equivalent `GET` would have returned. + private var suppressResponseBody = false + + /// Methods of requests still awaiting a response, fed by the paired ``HTTPRequestDecoder`` via + /// ``recordRequestMethod(_:)`` as it decodes each request head. The encoder consults this so + /// that responses to `HEAD`/`CONNECT` requests are encoded without a message body, which those + /// responses must not carry (RFC 9110 §9.3.2, RFC 9112 §6.3). + /// + /// Wired up by `configureHTTPServerPipeline`. When the encoder is used directly (its public + /// initializers), nothing feeds this, so it stays empty and the encoder behaves exactly as + /// before — framing purely from the response status. It is inline (no allocation) for the + /// common case of at most one request in flight. + private var requestMethods = HTTPServerRequestMethodQueue() + private var configuration: Configuration public convenience init() { @@ -288,20 +305,64 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel self.configuration = configuration } + /// Records the method of a decoded request so the response to it can be framed without a body + /// if it was a `HEAD` or `CONNECT`. Called by the paired request decoder; see the note on + /// ``requestMethods``. + internal func recordRequestMethod(_ method: HTTPMethod) { + self.requestMethods.append(method) + } + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { switch HTTPResponseEncoder.unwrapOutboundIn(data) { case .head(var response): + // Correlate this response with the request it answers. Responses to HEAD and CONNECT + // must not carry a body. A non-final 1xx (except 101) response is followed by a further + // head, so we don't consume the pending request method for it (mirrors + // HTTPResponseDecoder). + let statusCode = response.status.code + let isNonFinalInformational = (100..<200).contains(statusCode) && statusCode != 101 + var respondingToConnect = false + if !isNonFinalInformational, let method = self.requestMethods.popFirst() { + self.suppressResponseBody = method == .HEAD || method == .CONNECT + respondingToConnect = method == .CONNECT + } + + let bodyShouldBeChunked: Bool if self.configuration.automaticallySetFramingHeaders { - self.isChunked = + // A CONNECT response has no body, so frame it as such — this also strips any + // Transfer-Encoding/Content-Length, which a 2xx CONNECT response (a switch to + // tunnel mode) must not include (RFC 9110 §9.3.6, RFC 9112 §6.1). A HEAD response + // can still advertise what an equivalent GET would return (from + // https://www.rfc-editor.org/rfc/rfc9112.html#name-transfer-encoding): + // > Transfer-Encoding MAY be sent in a response to a HEAD request or in a 304 + // > (Not Modified) response to a GET request, neither of which includes a message + // > body, to indicate that the origin server would have applied a transfer coding + // > to the message body if the request had been an unconditional GET. + let hasBody: HTTPMethod.HasBody + if respondingToConnect || !response.status.mayHaveResponseBody { + hasBody = .no + } else { + hasBody = .yes + } + + bodyShouldBeChunked = correctlyFrameTransportHeaders( - hasBody: response.status.mayHaveResponseBody ? .yes : .no, + hasBody: hasBody, headers: &response.headers, version: response.version ) == .chunked + } else { - self.isChunked = messageIsChunked(headers: response.headers, version: response.version) + bodyShouldBeChunked = messageIsChunked( + headers: response.headers, + version: response.version + ) } + // If we're responding to either a HEAD or a CONNECT request, there will actually be + // no body, so set `isChunked` to false. + self.isChunked = self.suppressResponseBody ? false : bodyShouldBeChunked + writeHead( wrapOutboundOut: HTTPResponseEncoder.wrapOutboundOut, writeStartLine: { buffer in @@ -312,14 +373,29 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel promise: promise ) case .body(let bodyPart): - writeChunk( - wrapOutboundOut: HTTPResponseEncoder.wrapOutboundOut, - context: context, - isChunked: self.isChunked, - chunk: bodyPart, - promise: promise - ) + if self.suppressResponseBody { + // A response to a HEAD/CONNECT request cannot carry a body (RFC 9112 §6.3). Rather + // than silently dropping the bytes, reject the write so the caller learns of the + // misuse. Nothing is written downstream, so the head and end still form a + // well-formed bodyless response. + promise?.fail(NIOHTTPResponseEncoderError.responseBodyNotAllowed) + } else { + writeChunk( + wrapOutboundOut: HTTPResponseEncoder.wrapOutboundOut, + context: context, + isChunked: self.isChunked, + chunk: bodyPart, + promise: promise + ) + } case .end(let trailers): + if self.suppressResponseBody { + // A HEAD/CONNECT response must not be chunked. + // When we receive the response head, we actually set this to false if we are + // suppressing the body, so assert this still holds at this point. + assert(!self.isChunked, "There can be no body for HEAD and CONNECT responses.") + } + self.suppressResponseBody = false writeTrailers( wrapOutboundOut: HTTPResponseEncoder.wrapOutboundOut, context: context, @@ -334,6 +410,32 @@ public final class HTTPResponseEncoder: ChannelOutboundHandler, RemovableChannel @available(*, unavailable) extension HTTPResponseEncoder: Sendable {} +/// Errors thrown by ``HTTPResponseEncoder``. +public struct NIOHTTPResponseEncoderError: Error { + private enum BaseError: Hashable { + case responseBodyNotAllowed + } + + private let baseError: BaseError +} + +extension NIOHTTPResponseEncoderError { + /// A response body was written for a response to a `HEAD` or `CONNECT` request, which cannot + /// carry a message body (RFC 9110 §9.3.2, RFC 9112 §6.3). The offending body write is failed + /// with this error and no bytes are emitted for it. + public static let responseBodyNotAllowed: NIOHTTPResponseEncoderError = .init( + baseError: .responseBodyNotAllowed + ) +} + +extension NIOHTTPResponseEncoderError: Hashable {} + +extension NIOHTTPResponseEncoderError: CustomDebugStringConvertible { + public var debugDescription: String { + String(describing: self.baseError) + } +} + extension ByteBuffer { private mutating func write(status: HTTPResponseStatus) { self.writeString(String(status.code)) diff --git a/Sources/NIOHTTP1/HTTPPipelineSetup.swift b/Sources/NIOHTTP1/HTTPPipelineSetup.swift index 09d06e2ad..dc1d613eb 100644 --- a/Sources/NIOHTTP1/HTTPPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPPipelineSetup.swift @@ -1064,9 +1064,12 @@ extension ChannelPipeline.SynchronousOperations { self.eventLoop.assertInEventLoop() let responseEncoder = HTTPResponseEncoder(configuration: encoderConfiguration) + // The encoder is outbound-only; the request decoder feeds it each decoded request's method + // so responses to HEAD/CONNECT are encoded without a body. let requestDecoder = HTTPRequestDecoder( leftOverBytesStrategy: upgrade == nil ? .dropBytes : .forwardBytes, - limitConfiguration: decoderLimitConfiguration + limitConfiguration: decoderLimitConfiguration, + responseEncoder: responseEncoder ) var handlers: [RemovableChannelHandler] = [responseEncoder, ByteToMessageHandler(requestDecoder)] diff --git a/Sources/NIOHTTP1/HTTPServerRequestMethodQueue.swift b/Sources/NIOHTTP1/HTTPServerRequestMethodQueue.swift new file mode 100644 index 000000000..7464f3a64 --- /dev/null +++ b/Sources/NIOHTTP1/HTTPServerRequestMethodQueue.swift @@ -0,0 +1,49 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2026 Apple Inc. and the SwiftNIO project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftNIO project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import NIOCore + +/// A FIFO of the methods of requests that have been decoded but whose responses have not yet been +/// written, used by ``HTTPResponseEncoder`` to omit the body from responses to `HEAD`/`CONNECT` +/// requests (which must not carry one — RFC 9110 §9.3.2, RFC 9112 §6.3). +/// +/// HTTP/1 serializes responses, so in the common case only a single request is awaiting a response +/// and its method is held inline with no heap allocation. The `overflow` buffer is only allocated +/// if a peer pipelines requests that the decoder reads ahead within a single read (so more than one +/// is pending at once); it stays `nil` — and thus allocation-free — otherwise. +struct HTTPServerRequestMethodQueue { + /// The method of the oldest request still awaiting a response, or `nil` if none is pending. + private var first: HTTPMethod? + /// Methods of any further pending requests, oldest first. Allocated only under pipelining. + private var overflow: CircularBuffer? + + mutating func append(_ method: HTTPMethod) { + if self.first == nil { + self.first = method + } else { + if self.overflow == nil { + self.overflow = CircularBuffer(initialCapacity: 4) + } + self.overflow!.append(method) + } + } + + mutating func popFirst() -> HTTPMethod? { + guard let method = self.first else { + return nil + } + self.first = self.overflow?.popFirst() + return method + } +} diff --git a/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift b/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift index 62fa87259..5e7159615 100644 --- a/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift @@ -106,10 +106,13 @@ extension ChannelPipeline.SynchronousOperations { self.eventLoop.assertInEventLoop() let responseEncoder = HTTPResponseEncoder(configuration: configuration.encoderConfiguration) + // The encoder is outbound-only; the request decoder feeds it each decoded request's method + // so responses to HEAD/CONNECT are encoded without a body. let requestDecoder = ByteToMessageHandler( HTTPRequestDecoder( leftOverBytesStrategy: .forwardBytes, - limitConfiguration: configuration.decoderConfiguration + limitConfiguration: configuration.decoderConfiguration, + responseEncoder: responseEncoder ) ) diff --git a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift index 7a2496726..796f9a758 100644 --- a/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPResponseEncoderTest.swift @@ -408,4 +408,210 @@ class HTTPResponseEncoderTests: XCTestCase { let writtenData = sendResponse(withStatus: .ok, andHeaders: headers) writtenData.assertContainsOnly("HTTP/1.1 200 OK\r\ncontent-length: 3\r\n\r\n") } + + // MARK: - HEAD/CONNECT response body suppression + + /// Adds only the response encoder, lets it observe a request with `requestMethod`, then writes + /// the given (bodyless) response and returns all response bytes as a single string. + private func encodeResponse( + toRequestMethod requestMethod: HTTPMethod, + status: HTTPResponseStatus, + headers: HTTPHeaders = HTTPHeaders(), + configuration: HTTPResponseEncoder.Configuration = .init() + ) throws -> String { + let channel = EmbeddedChannel() + defer { XCTAssertEqual(true, try? channel.finish().isClean) } + + // Feed the encoder the request method, exactly as the paired request decoder would when the + // request was decoded. + let encoder = HTTPResponseEncoder(configuration: configuration) + try channel.pipeline.syncOperations.addHandler(encoder) + encoder.recordRequestMethod(requestMethod) + + var responseHead = HTTPResponseHead(version: .http1_1, status: status) + responseHead.headers = headers + try channel.writeOutbound(HTTPServerResponsePart.head(responseHead)) + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + + var all = channel.allocator.buffer(capacity: 128) + while var buffer = try channel.readOutbound(as: ByteBuffer.self) { + all.writeBuffer(&buffer) + } + return String(buffer: all) + } + + /// Asserts that writing a body part for a response to `requestMethod` (a HEAD/CONNECT request, + /// which cannot have a body) fails with ``NIOHTTPResponseEncoderError/responseBodyNotAllowed``. + private func assertBodyWriteRejected( + forRequestMethod requestMethod: HTTPMethod, + configuration: HTTPResponseEncoder.Configuration = .init(), + file: StaticString = #filePath, + line: UInt = #line + ) throws { + let channel = EmbeddedChannel() + defer { _ = try? channel.finish() } + + let encoder = HTTPResponseEncoder(configuration: configuration) + try channel.pipeline.syncOperations.addHandler(encoder) + encoder.recordRequestMethod(requestMethod) + + try channel.writeOutbound(HTTPServerResponsePart.head(HTTPResponseHead(version: .http1_1, status: .ok))) + XCTAssertThrowsError( + try channel.writeOutbound(HTTPServerResponsePart.body(.byteBuffer(ByteBuffer(string: "hello")))), + file: file, + line: line + ) { error in + XCTAssertEqual(error as? NIOHTTPResponseEncoderError, .responseBodyNotAllowed, file: file, line: line) + } + } + + func testHeadResponseOmitsChunkedTerminator() throws { + // A 200 with no Content-Length is chunked for a GET; for a HEAD the framing header is + // preserved but the terminator ("0\r\n\r\n") — an illegal body — must not be written. + XCTAssertEqual( + try self.encodeResponse(toRequestMethod: .HEAD, status: .ok), + "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n" + ) + } + + func testHeadResponsePreservesExplicitContentLength() throws { + // An explicit Content-Length (what a GET would return) is preserved and no body is sent. + XCTAssertEqual( + try self.encodeResponse(toRequestMethod: .HEAD, status: .ok, headers: ["content-length": "1000"]), + "HTTP/1.1 200 OK\r\ncontent-length: 1000\r\n\r\n" + ) + } + + func testWritingBodyToHeadResponseIsRejected() throws { + // A HEAD response must not carry a body: writing one is rejected rather than silently dropped. + try self.assertBodyWriteRejected(forRequestMethod: .HEAD) + } + + func testWritingBodyToHeadResponseIsRejectedInManualFramingMode() throws { + // Body suppression is method-based, so it applies even when the caller owns the framing headers. + try self.assertBodyWriteRejected(forRequestMethod: .HEAD, configuration: .noFramingTransformation) + } + + func testConnectResponseOmitsFramingHeaders() throws { + // A CONNECT response carries no body, and a 2xx CONNECT response must not include + // Transfer-Encoding or Content-Length (it switches to a tunnel), so no framing header is + // emitted. + XCTAssertEqual( + try self.encodeResponse(toRequestMethod: .CONNECT, status: .ok), + "HTTP/1.1 200 OK\r\n\r\n" + ) + } + + func testWritingBodyToConnectResponseIsRejected() throws { + // A CONNECT response must not carry a body either. + try self.assertBodyWriteRejected(forRequestMethod: .CONNECT) + } + + func testConnectResponseStripsExplicitContentLength() throws { + // A 2xx CONNECT response must not carry Content-Length either; it's stripped. + XCTAssertEqual( + try self.encodeResponse(toRequestMethod: .CONNECT, status: .ok, headers: ["content-length": "1000"]), + "HTTP/1.1 200 OK\r\n\r\n" + ) + } + + func testManualFramingModeStillOmitsHeadResponseTerminator() throws { + // With automaticallySetFramingHeaders = false the caller owns the framing headers (here a + // chunked Transfer-Encoding is left untouched), but the end-of-body marker is still + // suppressed for a HEAD response. + XCTAssertEqual( + try self.encodeResponse( + toRequestMethod: .HEAD, + status: .ok, + headers: ["transfer-encoding": "chunked"], + configuration: .noFramingTransformation + ), + "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n" + ) + } + + func testGetResponseStillEmitsChunkedTerminator() throws { + // Control: the identical response to a GET must still be chunked, terminator included. + XCTAssertEqual( + try self.encodeResponse(toRequestMethod: .GET, status: .ok), + "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n0\r\n\r\n" + ) + } + + func testEncoderWithoutObservedRequestFallsBackToStatusFraming() throws { + // If the encoder never observes a request (e.g. placed before the decoder, or used + // standalone) it behaves exactly as before: status-only framing, terminator included. + let channel = EmbeddedChannel() + defer { XCTAssertEqual(true, try? channel.finish().isClean) } + try channel.pipeline.syncOperations.addHandler(HTTPResponseEncoder()) + try channel.writeOutbound(HTTPServerResponsePart.head(HTTPResponseHead(version: .http1_1, status: .ok))) + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + var all = channel.allocator.buffer(capacity: 128) + while var buffer = try channel.readOutbound(as: ByteBuffer.self) { + all.writeBuffer(&buffer) + } + XCTAssertEqual(String(buffer: all), "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n0\r\n\r\n") + } + + func testHeadThenGetOnConfiguredServerPipelineKeepsConnectionUsable() throws { + // End-to-end via configureHTTPServerPipeline: the HEAD response carries no body, and a + // subsequent GET on the same keep-alive connection is framed normally. This proves the + // request-method queue advances correctly and the response stream isn't corrupted. + let channel = EmbeddedChannel() + defer { XCTAssertNoThrow(try channel.finish()) } + try channel.pipeline.syncOperations.configureHTTPServerPipeline() + + func readAllOutbound() throws -> String { + var all = channel.allocator.buffer(capacity: 128) + while var buffer = try channel.readOutbound(as: ByteBuffer.self) { + all.writeBuffer(&buffer) + } + return String(buffer: all) + } + func drainInboundRequest() throws { + while try channel.readInbound(as: HTTPServerRequestPart.self) != nil {} + } + + try channel.writeInbound(ByteBuffer(string: "HEAD /foo HTTP/1.1\r\nhost: example.com\r\n\r\n")) + try drainInboundRequest() + try channel.writeOutbound(HTTPServerResponsePart.head(HTTPResponseHead(version: .http1_1, status: .ok))) + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + XCTAssertEqual(try readAllOutbound(), "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n") + + try channel.writeInbound(ByteBuffer(string: "GET /foo HTTP/1.1\r\nhost: example.com\r\n\r\n")) + try drainInboundRequest() + try channel.writeOutbound(HTTPServerResponsePart.head(HTTPResponseHead(version: .http1_1, status: .ok))) + try channel.writeOutbound(HTTPServerResponsePart.end(nil)) + XCTAssertEqual(try readAllOutbound(), "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\n0\r\n\r\n") + } + + func testRequestMethodQueuePreservesFIFOOrderThroughOverflow() { + // The single in-flight case is inline; more than one pending (as when a peer pipelines and + // the decoder reads ahead) spills to the overflow buffer. Either way, order must be FIFO. + var queue = HTTPServerRequestMethodQueue() + XCTAssertNil(queue.popFirst()) + + // Common case: append then pop, repeatedly, never using overflow. + queue.append(.GET) + XCTAssertEqual(queue.popFirst(), .GET) + XCTAssertNil(queue.popFirst()) + + // Several pending at once (pipelining) must come back oldest-first. + queue.append(.HEAD) + queue.append(.GET) + queue.append(.CONNECT) + XCTAssertEqual(queue.popFirst(), .HEAD) + XCTAssertEqual(queue.popFirst(), .GET) + XCTAssertEqual(queue.popFirst(), .CONNECT) + XCTAssertNil(queue.popFirst()) + + // Interleaving append/pop after overflow was used still preserves order. + queue.append(.HEAD) + queue.append(.GET) + XCTAssertEqual(queue.popFirst(), .HEAD) + queue.append(.CONNECT) + XCTAssertEqual(queue.popFirst(), .GET) + XCTAssertEqual(queue.popFirst(), .CONNECT) + XCTAssertNil(queue.popFirst()) + } }