From 61053a00bbbdb4f98e493672336d9080e4e92db7 Mon Sep 17 00:00:00 2001 From: Adam Fowler Date: Wed, 14 Jan 2026 11:40:00 +0000 Subject: [PATCH] NIOTypedHTTPClientUpgradeHandler will write Upgrade request on handlerAdded if active (#3473) `NIOTypedHTTPClientUpgradeHandler.handlerAdded` will write upgrade request if the channel is already active ### Motivation: This has been added to make it easier to implement a websocket client that supports proxies. If the upgrade handler is added after the proxy connect has been processed previously nothing would happen. ### Modifications: - Added new function `NIOTypedHTTPClientUpgradeHandler.writeUpgradeRequest()` function. Call this from `channelActive` and also from `handlerAdded` if the channel is already active. - Added test `testUpgradeHappensAfterHandlerAdded` ### Result: NIOTypedHTTPClientUpgradeHandler now also works if it is added to a channel after the channel is active --------- Co-authored-by: Cory Benfield --- .../NIOTypedHTTPClientUpgradeHandler.swift | 25 ++- ...OTypedHTTPClientUpgraderStateMachine.swift | 5 +- .../HTTPClientUpgradeTests.swift | 202 +++++++++++++++++- 3 files changed, 219 insertions(+), 13 deletions(-) diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift index a7d43b403..992f7464c 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift @@ -127,6 +127,14 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func handlerAdded(context: ChannelHandlerContext) { self._upgradeResultPromise = context.eventLoop.makePromise(of: UpgradeResult.self) + if context.channel.isActive { + switch self.stateMachine.channelActive() { + case .writeUpgradeRequest: + self.writeUpgradeRequest(context: context) + case .none: + break + } + } } public func handlerRemoved(context: ChannelHandlerContext) { @@ -141,13 +149,7 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch public func channelActive(context: ChannelHandlerContext) { switch self.stateMachine.channelActive() { case .writeUpgradeRequest: - context.write( - NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.head(self.upgradeRequestHead)), - promise: nil - ) - context.write(NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) - context.writeAndFlush(NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.end(nil)), promise: nil) - + self.writeUpgradeRequest(context: context) case .none: break } @@ -198,6 +200,15 @@ public final class NIOTypedHTTPClientUpgradeHandler: Ch context.fireErrorCaught(error) } + private func writeUpgradeRequest(context: ChannelHandlerContext) { + context.write( + NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.head(self.upgradeRequestHead)), + promise: nil + ) + context.write(NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) + context.writeAndFlush(NIOTypedHTTPClientUpgradeHandler.wrapOutboundOut(.end(nil)), promise: nil) + } + private func channelRead(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) { switch self.stateMachine.channelReadResponsePart(responsePart) { case .fireErrorCaughtAndRemoveHandler(let error): diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift index 08d9e8fcb..b6e626f42 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift @@ -91,7 +91,10 @@ struct NIOTypedHTTPClientUpgraderStateMachine { case .finished: return nil - case .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .unbuffering, .upgrading: + case .awaitingUpgradeResponseHead: + return nil + + case .awaitingUpgradeResponseEnd, .unbuffering, .upgrading: fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") case .modifying: diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index 8c409ec95..3ddd1cff1 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -1139,9 +1139,26 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], _ upgradeCompletionHandler: @escaping (ChannelHandlerContext, Result) -> Void ) throws -> EmbeddedChannel { - let channel = EmbeddedChannel() + try setUpClientChannel( + channel: channel, + previousHTTPHandler: previousHTTPHandler, + clientHTTPHandler: clientHTTPHandler, + clientUpgraders: clientUpgraders, + upgradeCompletionHandler + ) + try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + return channel + } + func setUpClientChannel( + channel: Channel, + previousHTTPHandler: (RemovableChannelHandler & Sendable)? = nil, + clientHTTPHandler: RemovableChannelHandler & Sendable, + clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], + _ upgradeCompletionHandler: @escaping (ChannelHandlerContext, Result) -> Void + ) throws { if let previousHTTPHandler { try channel.pipeline.syncOperations.addHandler(previousHTTPHandler) } @@ -1180,13 +1197,9 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { ) let loopBoundContext = context.loopBound - try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) - .wait() upgradeResult.assumeIsolated().whenComplete { result in upgradeCompletionHandler(loopBoundContext.value, result) } - - return channel } override func setUpClientChannel( @@ -1454,4 +1467,183 @@ final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self) ) } + + // MARK: Tests specific to typed handler + + func testUpgradeHappensAfterHandlerAdded() throws { + let upgradeProtocol = "myProto" + let addedUpgradeHeader = "myUpgradeHeader" + let addedUpgradeValue = "upgradeHeader" + + let upgradeHandlerCallbackFired = NIOLockedValueBox(false) + + // This header is not required by the server but we will validate its receipt. + let clientHeaders = [(addedUpgradeHeader, addedUpgradeValue)] + + let clientUpgrader = SuccessfulClientUpgrader( + forProtocol: upgradeProtocol, + upgradeHeaders: clientHeaders + ) + + let clientChannel = EmbeddedChannel() + try clientChannel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + try setUpClientChannel( + channel: clientChannel, + clientHTTPHandler: ExplodingHTTPHandler(), + clientUpgraders: [clientUpgrader] + ) { _, result in + switch result { + case .success(true): + upgradeHandlerCallbackFired.withLockedValue { $0 = true } + default: + break + } + } + + // Read the server request. + if let requestString = try clientChannel.readByteBufferOutputAsString() { + XCTAssertEqual( + requestString, + "GET / HTTP/1.1\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0\r\nConnection: upgrade\r\nUpgrade: \(upgradeProtocol.lowercased())\r\n\(addedUpgradeHeader): \(addedUpgradeValue)\r\n\r\n" + ) + } else { + XCTFail() + } + + // Validate the pipeline still has http handlers. + clientChannel.pipeline.assertContains(handlerType: HTTPRequestEncoder.self) + clientChannel.pipeline.assertContains(handlerType: ByteToMessageHandler.self) + assertPipelineContainsUpgradeHandler(channel: clientChannel) + + // Push the successful server response. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: \(upgradeProtocol)\r\n\r\n" + + XCTAssertNoThrow(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) + + clientChannel.embeddedEventLoop.run() + + // Once upgraded, validate the pipeline has been removed. + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: HTTPRequestEncoder.self) + ) + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: ByteToMessageHandler.self) + ) + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self) + ) + + // Check the client upgrader was used correctly. + XCTAssertEqual(1, clientUpgrader.addCustomUpgradeRequestHeadersCallCount) + XCTAssertEqual(1, clientUpgrader.shouldAllowUpgradeCallCount) + XCTAssertEqual(1, clientUpgrader.upgradeContextResponseCallCount) + + XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 }) + } + + func testUpgradeHappensWhenAddedDuringChannelActive() throws { + final class OnActiveChannelHandler: ChannelInboundHandler { + fileprivate typealias InboundIn = ByteBuffer + fileprivate typealias OutboundOut = ByteBuffer + + let onActive: (Channel) throws -> Void + + init(_ onActive: @escaping (Channel) throws -> Void) { + self.onActive = onActive + } + func channelActive(context: ChannelHandlerContext) { + do { + try onActive(context.channel) + } catch { + context.fireErrorCaught(error) + } + context.fireChannelActive() + } + } + let upgradeProtocol = "myProto" + let addedUpgradeHeader = "myUpgradeHeader" + let addedUpgradeValue = "upgradeHeader" + + let upgradeHandlerCallbackFired = NIOLockedValueBox(false) + + // This header is not required by the server but we will validate its receipt. + let clientHeaders = [(addedUpgradeHeader, addedUpgradeValue)] + + let clientUpgrader = SuccessfulClientUpgrader( + forProtocol: upgradeProtocol, + upgradeHeaders: clientHeaders + ) + + let clientChannel = EmbeddedChannel() + let setupUpgraderOnActiveChannelHandler = OnActiveChannelHandler { [self] channel in + try setUpClientChannel( + channel: channel, + clientHTTPHandler: ExplodingHTTPHandler(), + clientUpgraders: [clientUpgrader] + ) { _, result in + switch result { + case .success(true): + upgradeHandlerCallbackFired.withLockedValue { $0 = true } + default: + break + } + } + } + try clientChannel.pipeline.syncOperations.addHandler(setupUpgraderOnActiveChannelHandler) + try clientChannel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + + // Read the server request. + if let requestString = try clientChannel.readByteBufferOutputAsString() { + XCTAssertEqual( + requestString, + "GET / HTTP/1.1\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0\r\nConnection: upgrade\r\nUpgrade: \(upgradeProtocol.lowercased())\r\n\(addedUpgradeHeader): \(addedUpgradeValue)\r\n\r\n" + ) + } else { + XCTFail() + } + + // Validate the pipeline still has http handlers. + clientChannel.pipeline.assertContains(handlerType: HTTPRequestEncoder.self) + clientChannel.pipeline.assertContains(handlerType: ByteToMessageHandler.self) + assertPipelineContainsUpgradeHandler(channel: clientChannel) + + // Push the successful server response. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: \(upgradeProtocol)\r\n\r\n" + + XCTAssertNoThrow(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) + + clientChannel.embeddedEventLoop.run() + + // Once upgraded, validate the pipeline has been removed. + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: HTTPRequestEncoder.self) + ) + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: ByteToMessageHandler.self) + ) + XCTAssertNoThrow( + try clientChannel.pipeline + .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self) + ) + + // Check the client upgrader was used correctly. + XCTAssertEqual(1, clientUpgrader.addCustomUpgradeRequestHeadersCallCount) + XCTAssertEqual(1, clientUpgrader.shouldAllowUpgradeCallCount) + XCTAssertEqual(1, clientUpgrader.upgradeContextResponseCallCount) + + XCTAssert(upgradeHandlerCallbackFired.withLockedValue { $0 }) + } }