diff --git a/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift b/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift index c92e41715..e69d034ba 100644 --- a/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift +++ b/Sources/NIOHTTP1/HTTPTypedPipelineSetup.swift @@ -32,7 +32,7 @@ public struct NIOUpgradableHTTPServerPipelineConfiguration @@ -43,10 +43,6 @@ public struct NIOUpgradableHTTPServerPipelineConfiguration ) { @@ -109,11 +105,12 @@ extension ChannelPipeline.SynchronousOperations { ) throws -> EventLoopFuture { self.eventLoop.assertInEventLoop() - let responseEncoder = HTTPResponseEncoder(configuration: configuration.httpResponseEncoderConfiguration) + let responseEncoder = HTTPResponseEncoder(configuration: configuration.encoderConfiguration) let requestDecoder = ByteToMessageHandler(HTTPRequestDecoder(leftOverBytesStrategy: .forwardBytes)) - var extraHTTPHandlers: [RemovableChannelHandler] = [requestDecoder] - extraHTTPHandlers.reserveCapacity(3) + var extraHTTPHandlers = [RemovableChannelHandler]() + extraHTTPHandlers.reserveCapacity(4) + extraHTTPHandlers.append(requestDecoder) try self.addHandler(responseEncoder) try self.addHandler(requestDecoder) @@ -146,3 +143,112 @@ extension ChannelPipeline.SynchronousOperations { return upgrader.upgradeResultFuture } } + +// MARK: - Client pipeline configuration + +/// Configuration for an upgradable HTTP pipeline. +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +@_spi(AsyncChannel) +public struct NIOUpgradableHTTPClientPipelineConfiguration { + /// The strategy to use when dealing with leftover bytes after removing the ``HTTPDecoder`` from the pipeline. + public var leftOverBytesStrategy = RemoveAfterUpgradeStrategy.dropBytes + + /// Whether to validate outbound response headers to confirm that they are + /// spec compliant. Defaults to `true`. + public var enableOutboundHeaderValidation = true + + /// The configuration for the ``HTTPRequestEncoder``. + public var encoderConfiguration = HTTPRequestEncoder.Configuration() + + /// The configuration for the ``NIOTypedHTTPClientUpgradeHandler``. + public var upgradeConfiguration: NIOTypedHTTPClientUpgradeConfiguration + + /// Initializes a new ``NIOUpgradableHTTPClientPipelineConfiguration`` with default values. + /// + /// The current defaults provide the following features: + /// 1. Outbound header fields validation to protect against response splitting attacks. + public init( + upgradeConfiguration: NIOTypedHTTPClientUpgradeConfiguration + ) { + self.upgradeConfiguration = upgradeConfiguration + } +} + +extension ChannelPipeline { + /// Configure a `ChannelPipeline` for use as an HTTP client. + /// + /// - Parameters: + /// - configuration: The HTTP pipeline's configuration. + /// - Returns: An `EventLoopFuture` that will fire when the pipeline is configured. The future contains an `EventLoopFuture` + /// that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`. + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) + @_spi(AsyncChannel) + public func configureUpgradableHTTPClientPipeline( + configuration: NIOUpgradableHTTPClientPipelineConfiguration + ) -> EventLoopFuture> { + self._configureUpgradableHTTPClientPipeline(configuration: configuration) + } + + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) + private func _configureUpgradableHTTPClientPipeline( + configuration: NIOUpgradableHTTPClientPipelineConfiguration + ) -> EventLoopFuture> { + let future: EventLoopFuture> + + if self.eventLoop.inEventLoop { + let result = Result, Error> { + try self.syncOperations.configureUpgradableHTTPClientPipeline( + configuration: configuration + ) + } + future = self.eventLoop.makeCompletedFuture(result) + } else { + future = self.eventLoop.submit { + try self.syncOperations.configureUpgradableHTTPClientPipeline( + configuration: configuration + ) + } + } + + return future + } +} + +extension ChannelPipeline.SynchronousOperations { + /// Configure a `ChannelPipeline` for use as an HTTP client. + /// + /// - Parameters: + /// - configuration: The HTTP pipeline's configuration. + /// - Returns: An `EventLoopFuture` that is fired once the pipeline has been upgraded or not and contains the `UpgradeResult`. + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) + @_spi(AsyncChannel) + public func configureUpgradableHTTPClientPipeline( + configuration: NIOUpgradableHTTPClientPipelineConfiguration + ) throws -> EventLoopFuture { + self.eventLoop.assertInEventLoop() + + let requestEncoder = HTTPRequestEncoder(configuration: configuration.encoderConfiguration) + let responseDecoder = ByteToMessageHandler(HTTPResponseDecoder(leftOverBytesStrategy: configuration.leftOverBytesStrategy)) + var httpHandlers = [RemovableChannelHandler]() + httpHandlers.reserveCapacity(3) + httpHandlers.append(requestEncoder) + httpHandlers.append(responseDecoder) + + try self.addHandler(requestEncoder) + try self.addHandler(responseDecoder) + + if configuration.enableOutboundHeaderValidation { + let headerValidationHandler = NIOHTTPRequestHeadersValidator() + try self.addHandler(headerValidationHandler) + httpHandlers.append(headerValidationHandler) + } + + let upgrader = NIOTypedHTTPClientUpgradeHandler( + httpHandlers: httpHandlers, + upgradeConfiguration: configuration.upgradeConfiguration + ) + try self.addHandler(upgrader) + + return upgrader.upgradeResultFuture + } +} diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift new file mode 100644 index 000000000..82c6f129f --- /dev/null +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgradeHandler.swift @@ -0,0 +1,286 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2013 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 + +/// An object that implements `NIOTypedHTTPClientProtocolUpgrader` knows how to handle HTTP upgrade to +/// a protocol on a client-side channel. +/// It has the option of denying this upgrade based upon the server response. +@_spi(AsyncChannel) +public protocol NIOTypedHTTPClientProtocolUpgrader { + associatedtype UpgradeResult: Sendable + + /// The protocol this upgrader knows how to support. + var supportedProtocol: String { get } + + /// All the header fields the protocol requires in the request to successfully upgrade. + /// These header fields will be added to the outbound request's "Connection" header field. + /// It is the responsibility of the custom headers call to actually add these required headers. + var requiredUpgradeHeaders: [String] { get } + + /// Additional headers to be added to the request, beyond the "Upgrade" and "Connection" headers. + func addCustom(upgradeRequestHeaders: inout HTTPHeaders) + + /// Gives the receiving upgrader the chance to deny the upgrade based on the upgrade HTTP response. + func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool + + /// Called when the upgrade response has been flushed. At this time it is safe to mutate the channel + /// pipeline to add whatever channel handlers are required. + /// Until the returned `EventLoopFuture` succeeds, all received data will be buffered. + func upgrade(channel: Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture +} + +/// The upgrade configuration for the ``NIOTypedHTTPClientUpgradeHandler``. +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +@_spi(AsyncChannel) +public struct NIOTypedHTTPClientUpgradeConfiguration { + /// The initial request head that is sent out once the channel becomes active. + public var upgradeRequestHead: HTTPRequestHead + + /// The array of potential upgraders. + public var upgraders: [any NIOTypedHTTPClientProtocolUpgrader] + + /// A closure that is run once it is determined that no protocol upgrade is happening. This can be used + /// to configure handlers that expect HTTP. + public var notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture + + public init( + upgradeRequestHead: HTTPRequestHead, + upgraders: [any NIOTypedHTTPClientProtocolUpgrader], + notUpgradingCompletionHandler: @Sendable @escaping (Channel) -> EventLoopFuture + ) { + precondition(upgraders.count > 0, "A minimum of one protocol upgrader must be specified.") + self.upgradeRequestHead = upgradeRequestHead + self.upgraders = upgraders + self.notUpgradingCompletionHandler = notUpgradingCompletionHandler + } +} + +/// A client-side channel handler that sends a HTTP upgrade handshake request to perform a HTTP-upgrade. +/// This handler will add all appropriate headers to perform an upgrade to +/// the a protocol. It may add headers for a set of protocols in preference order. +/// If the upgrade fails (i.e. response is not 101 Switching Protocols), this handler simply +/// removes itself from the pipeline. If the upgrade is successful, it upgrades the pipeline to the new protocol. +/// +/// The request sends an order of preference to request which protocol it would like to use for the upgrade. +/// It will only upgrade to the protocol that is returned first in the list and does not currently +/// have the capability to upgrade to multiple simultaneous layered protocols. +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +@_spi(AsyncChannel) +public final class NIOTypedHTTPClientUpgradeHandler: ChannelDuplexHandler, RemovableChannelHandler { + public typealias OutboundIn = HTTPClientRequestPart + public typealias OutboundOut = HTTPClientRequestPart + public typealias InboundIn = HTTPClientResponsePart + public typealias InboundOut = HTTPClientResponsePart + + /// The upgrade future which will be completed once protocol upgrading has been done. + public var upgradeResultFuture: EventLoopFuture { + self.upgradeResultPromise.futureResult + } + + private let upgradeRequestHead: HTTPRequestHead + private let httpHandlers: [RemovableChannelHandler] + private let notUpgradingCompletionHandler: @Sendable (Channel) -> EventLoopFuture + private var stateMachine: NIOTypedHTTPClientUpgraderStateMachine + private var _upgradeResultPromise: EventLoopPromise? + private var upgradeResultPromise: EventLoopPromise { + precondition( + self._upgradeResultPromise != nil, + "Tried to access the upgrade result before the handler was added to a pipeline" + ) + return self._upgradeResultPromise! + } + + /// Create a ``NIOTypedHTTPClientUpgradeHandler``. + /// + /// - Parameters: + /// - httpHandlers: All `RemovableChannelHandler` objects which will be removed from the pipeline + /// once the upgrade response is sent. This is used to ensure that the pipeline will be in a clean state + /// after the upgrade. It should include any handlers that are directly related to handling HTTP. + /// At the very least this should include the `HTTPEncoder` and `HTTPDecoder`, but should also include + /// any other handler that cannot tolerate receiving non-HTTP data. + /// - upgradeConfiguration: The upgrade configuration. + public init( + httpHandlers: [RemovableChannelHandler], + upgradeConfiguration: NIOTypedHTTPClientUpgradeConfiguration + ) { + self.httpHandlers = httpHandlers + var upgradeRequestHead = upgradeConfiguration.upgradeRequestHead + Self.addHeaders( + to: &upgradeRequestHead, + upgraders: upgradeConfiguration.upgraders + ) + self.upgradeRequestHead = upgradeRequestHead + self.stateMachine = .init(upgraders: upgradeConfiguration.upgraders) + self.notUpgradingCompletionHandler = upgradeConfiguration.notUpgradingCompletionHandler + } + + public func handlerAdded(context: ChannelHandlerContext) { + self._upgradeResultPromise = context.eventLoop.makePromise(of: UpgradeResult.self) + } + + public func handlerRemoved(context: ChannelHandlerContext) { + switch self.stateMachine.handlerRemoved() { + case .failUpgradePromise: + self.upgradeResultPromise.fail(ChannelError.inappropriateOperationForState) + case .none: + break + } + } + + public func channelActive(context: ChannelHandlerContext) { + switch self.stateMachine.channelActive() { + case .writeUpgradeRequest: + context.write(self.wrapOutboundOut(.head(self.upgradeRequestHead)), promise: nil) + context.write(self.wrapOutboundOut(.body(.byteBuffer(.init()))), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + + case .none: + break + } + } + + private static func addHeaders( + to requestHead: inout HTTPRequestHead, + upgraders: [any NIOTypedHTTPClientProtocolUpgrader] + ) { + let requiredHeaders = ["upgrade"] + upgraders.flatMap { $0.requiredUpgradeHeaders } + requestHead.headers.add(name: "Connection", value: requiredHeaders.joined(separator: ",")) + + let allProtocols = upgraders.map { $0.supportedProtocol.lowercased() } + requestHead.headers.add(name: "Upgrade", value: allProtocols.joined(separator: ",")) + + // Allow each upgrader the chance to add custom headers. + for upgrader in upgraders { + upgrader.addCustom(upgradeRequestHeaders: &requestHead.headers) + } + } + + public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + switch self.stateMachine.write() { + case .failWrite(let error): + promise?.fail(error) + + case .forwardWrite: + context.write(data, promise: promise) + } + } + + public func channelRead(context: ChannelHandlerContext, data: NIOAny) { + switch self.stateMachine.channelReadData(data) { + case .unwrapData: + let responsePart = self.unwrapInboundIn(data) + self.channelRead(context: context, responsePart: responsePart) + + case .fireChannelRead: + context.fireChannelRead(data) + + case .none: + break + } + } + + public func channelRead(context: ChannelHandlerContext, responsePart: HTTPClientResponsePart) { + switch self.stateMachine.channelReadResponsePart(responsePart) { + case .fireErrorCaughtAndRemoveHandler(let error): + self.upgradeResultPromise.fail(error) + context.fireErrorCaught(error) + context.pipeline.removeHandler(self, promise: nil) + + case .runNotUpgradingInitializer: + self.notUpgradingCompletionHandler(context.channel) + .hop(to: context.eventLoop) + .whenComplete { result in + self.upgradingHandlerCompleted(context: context, result) + } + + case .startUpgrading(let upgrader, let responseHead): + self.startUpgrading( + context: context, + upgrader: upgrader, + responseHead: responseHead + ) + + case .none: + break + } + } + + private func startUpgrading( + context: ChannelHandlerContext, + upgrader: any NIOTypedHTTPClientProtocolUpgrader, + responseHead: HTTPResponseHead + ) { + // Before we start the upgrade we have to remove the HTTPEncoder and HTTPDecoder handlers from the + // pipeline, to prevent them parsing any more data. We'll buffer the incoming data until that completes. + self.removeHTTPHandlers(context: context) + .flatMap { + upgrader.upgrade(channel: context.channel, upgradeResponse: responseHead) + }.hop(to: context.eventLoop) + .whenComplete { result in + self.upgradingHandlerCompleted(context: context, result) + } + } + + private func upgradingHandlerCompleted( + context: ChannelHandlerContext, + _ result: Result + ) { + switch self.stateMachine.upgradingHandlerCompleted(result) { + case .fireErrorCaughtAndRemoveHandler(let error): + self.upgradeResultPromise.fail(error) + context.fireErrorCaught(error) + context.pipeline.removeHandler(self, promise: nil) + + case .fireErrorCaughtAndStartUnbuffering(let error): + self.upgradeResultPromise.fail(error) + context.fireErrorCaught(error) + self.unbuffer(context: context) + + case .startUnbuffering(let value): + self.upgradeResultPromise.succeed(value) + self.unbuffer(context: context) + + case .removeHandler(let value): + self.upgradeResultPromise.succeed(value) + context.pipeline.removeHandler(self, promise: nil) + + case .none: + break + } + } + + private func unbuffer(context: ChannelHandlerContext) { + while true { + switch self.stateMachine.unbuffer() { + case .fireChannelRead(let data): + context.fireChannelRead(data) + + case .fireChannelReadCompleteAndRemoveHandler: + context.fireChannelReadComplete() + context.pipeline.removeHandler(self, promise: nil) + return + } + } + } + + /// Removes any extra HTTP-related handlers from the channel pipeline. + private func removeHTTPHandlers(context: ChannelHandlerContext) -> EventLoopFuture { + guard self.httpHandlers.count > 0 else { + return context.eventLoop.makeSucceededFuture(()) + } + + let removeFutures = self.httpHandlers.map { context.pipeline.removeHandler($0) } + return .andAllSucceed(removeFutures, on: context.eventLoop) + } +} diff --git a/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift new file mode 100644 index 000000000..fa04481ea --- /dev/null +++ b/Sources/NIOHTTP1/NIOTypedHTTPClientUpgraderStateMachine.swift @@ -0,0 +1,334 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2023 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 DequeModule +import NIOCore + +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +struct NIOTypedHTTPClientUpgraderStateMachine { + @usableFromInline + enum State { + /// The state before we received a TLSUserEvent. We are just forwarding any read at this point. + case initial(upgraders: [any NIOTypedHTTPClientProtocolUpgrader]) + + /// The request has been sent. We are waiting for the upgrade response. + case awaitingUpgradeResponseHead(upgraders: [any NIOTypedHTTPClientProtocolUpgrader]) + + @usableFromInline + struct AwaitingUpgradeResponseEnd { + var upgrader: any NIOTypedHTTPClientProtocolUpgrader + var responseHead: HTTPResponseHead + } + /// We received the response head and are just waiting for the response end. + case awaitingUpgradeResponseEnd(AwaitingUpgradeResponseEnd) + + @usableFromInline + struct Upgrading { + var buffer: Deque + } + /// We are either running the upgrading handler. + case upgrading(Upgrading) + + @usableFromInline + struct Unbuffering { + var buffer: Deque + } + case unbuffering(Unbuffering) + + case finished + + case modifying + } + + private var state: State + + init(upgraders: [any NIOTypedHTTPClientProtocolUpgrader]) { + self.state = .initial(upgraders: upgraders) + } + + @usableFromInline + enum HandlerRemovedAction { + case failUpgradePromise + } + + @inlinable + mutating func handlerRemoved() -> HandlerRemovedAction? { + switch self.state { + case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading, .unbuffering: + self.state = .finished + return .failUpgradePromise + + case .finished: + return .none + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + } + } + + @usableFromInline + enum ChannelActiveAction { + case writeUpgradeRequest + } + + @inlinable + mutating func channelActive() -> ChannelActiveAction? { + switch self.state { + case .initial(let upgraders): + self.state = .awaitingUpgradeResponseHead(upgraders: upgraders) + return .writeUpgradeRequest + + case .finished: + return nil + + case .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .unbuffering, .upgrading: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + } + } + + @usableFromInline + enum WriteAction { + case failWrite(Error) + case forwardWrite + } + + @usableFromInline + func write() -> WriteAction { + switch self.state { + case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading: + return .failWrite(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade) + + case .unbuffering, .finished: + return .forwardWrite + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + } + } + + @usableFromInline + enum ChannelReadDataAction { + case unwrapData + case fireChannelRead + } + + @inlinable + mutating func channelReadData(_ data: NIOAny) -> ChannelReadDataAction? { + switch self.state { + case .initial: + return .unwrapData + + case .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd: + return .unwrapData + + case .upgrading(var upgrading): + // We got a read while running upgrading. + // We have to buffer the read to unbuffer it afterwards + self.state = .modifying + upgrading.buffer.append(data) + self.state = .upgrading(upgrading) + return nil + + case .unbuffering(var unbuffering): + self.state = .modifying + unbuffering.buffer.append(data) + self.state = .unbuffering(unbuffering) + return nil + + case .finished: + return .fireChannelRead + + case .modifying: + fatalError("Internal inconsistency in HTTPServerUpgradeStateMachine") + } + } + + + @usableFromInline + enum ChannelReadResponsePartAction { + case fireErrorCaughtAndRemoveHandler(Error) + case runNotUpgradingInitializer + case startUpgrading( + upgrader: any NIOTypedHTTPClientProtocolUpgrader, + responseHeaders: HTTPResponseHead + ) + } + + @inlinable + mutating func channelReadResponsePart(_ responsePart: HTTPClientResponsePart) -> ChannelReadResponsePartAction? { + switch self.state { + case .initial: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + + case .awaitingUpgradeResponseHead(let upgraders): + // We should decide if we can upgrade based on the first response header: if we aren't upgrading, + // by the time the body comes in we should be out of the pipeline. That means that if we don't think we're + // upgrading, the only thing we should see is a response head. Anything else in an error. + guard case .head(let response) = responsePart else { + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.invalidHTTPOrdering) + } + + // Assess whether the server has accepted our upgrade request. + guard case .switchingProtocols = response.status else { + var buffer = Deque() + buffer.append(.init(responsePart)) + self.state = .upgrading(.init(buffer: buffer)) + return .runNotUpgradingInitializer + } + + // Ok, we have a HTTP response. Check if it's an upgrade confirmation. + // If it's not, we want to pass it on and remove ourselves from the channel pipeline. + let acceptedProtocols = response.headers[canonicalForm: "upgrade"] + + // At the moment we only upgrade to the first protocol returned from the server. + guard let protocolName = acceptedProtocols.first?.lowercased() else { + // There are no upgrade protocols returned. + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.responseProtocolNotFound) + } + + let matchingUpgrader = upgraders + .first(where: { $0.supportedProtocol.lowercased() == protocolName }) + + guard let upgrader = matchingUpgrader else { + // There is no upgrader for this protocol. + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.responseProtocolNotFound) + } + + guard upgrader.shouldAllowUpgrade(upgradeResponse: response) else { + // The upgrader says no. + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.upgraderDeniedUpgrade) + } + + // We received the response head and decided that we can upgrade. + // We now need to wait for the response end and then we can perform the upgrade + self.state = .awaitingUpgradeResponseEnd(.init( + upgrader: upgrader, + responseHead: response + )) + return .none + + case .awaitingUpgradeResponseEnd(let awaitingUpgradeResponseEnd): + switch responsePart { + case .head: + // We got two HTTP response heads. + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(NIOHTTPClientUpgradeError.invalidHTTPOrdering) + + case .body: + // We tolerate body parts to be send but just ignore them + return .none + + case .end: + // We got the response end and can now run the upgrader. + self.state = .upgrading(.init(buffer: .init())) + return .startUpgrading( + upgrader: awaitingUpgradeResponseEnd.upgrader, + responseHeaders: awaitingUpgradeResponseEnd.responseHead + ) + } + + case .upgrading, .unbuffering, .finished: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + } + } + + @usableFromInline + enum UpgradingHandlerCompletedAction { + case fireErrorCaughtAndStartUnbuffering(Error) + case removeHandler(UpgradeResult) + case fireErrorCaughtAndRemoveHandler(Error) + case startUnbuffering(UpgradeResult) + } + + @inlinable + mutating func upgradingHandlerCompleted(_ result: Result) -> UpgradingHandlerCompletedAction? { + switch self.state { + case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .unbuffering: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + + case .upgrading(let upgrading): + switch result { + case .success(let value): + if !upgrading.buffer.isEmpty { + self.state = .unbuffering(.init(buffer: upgrading.buffer)) + return .startUnbuffering(value) + } else { + self.state = .finished + return .removeHandler(value) + } + + case .failure(let error): + if !upgrading.buffer.isEmpty { + // So we failed to upgrade. There is nothing really that we can do here. + // We are unbuffering the reads but there shouldn't be any handler in the pipeline + // that expects a specific type of reads anyhow. + self.state = .unbuffering(.init(buffer: upgrading.buffer)) + return .fireErrorCaughtAndStartUnbuffering(error) + } else { + self.state = .finished + return .fireErrorCaughtAndRemoveHandler(error) + } + } + + case .finished: + // We have to tolerate this + return nil + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + } + } + + @usableFromInline + enum UnbufferAction { + case fireChannelRead(NIOAny) + case fireChannelReadCompleteAndRemoveHandler + } + + @inlinable + mutating func unbuffer() -> UnbufferAction { + switch self.state { + case .initial, .awaitingUpgradeResponseHead, .awaitingUpgradeResponseEnd, .upgrading, .finished: + preconditionFailure("Invalid state \(self.state)") + + case .unbuffering(var unbuffering): + self.state = .modifying + + if let element = unbuffering.buffer.popFirst() { + self.state = .unbuffering(unbuffering) + + return .fireChannelRead(element) + } else { + self.state = .finished + + return .fireChannelReadCompleteAndRemoveHandler + } + + case .modifying: + fatalError("Internal inconsistency in HTTPClientUpgradeStateMachine") + + } + } +} diff --git a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift index a665cd63a..9e43f2d7d 100644 --- a/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/NIOTypedHTTPServerUpgradeHandler.swift @@ -15,10 +15,9 @@ /// An object that implements `NIOTypedHTTPServerProtocolUpgrader` knows how to handle HTTP upgrade to /// a protocol on a server-side channel. -@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) @_spi(AsyncChannel) public protocol NIOTypedHTTPServerProtocolUpgrader { - associatedtype UpgradeResult + associatedtype UpgradeResult: Sendable /// The protocol this upgrader knows how to support. var supportedProtocol: String { get } diff --git a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift index 5e7df19c4..b92c5f121 100644 --- a/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift +++ b/Sources/NIOWebSocket/NIOWebSocketClientUpgrader.swift @@ -13,7 +13,7 @@ //===----------------------------------------------------------------------===// import NIOCore -import NIOHTTP1 +@_spi(AsyncChannel) import NIOHTTP1 import _NIOBase64 @available(*, deprecated, renamed: "NIOWebSocketClientUpgrader") @@ -25,7 +25,6 @@ public typealias NIOWebClientSocketUpgrader = NIOWebSocketClientUpgrader /// This upgrader also assumes that the `HTTPClientUpgradeHandler` will appropriately mutate the /// pipeline to remove the HTTP `ChannelHandler`s. public final class NIOWebSocketClientUpgrader: NIOHTTPClientProtocolUpgrader { - /// RFC 6455 specs this as the required entry in the Upgrade header. public let supportedProtocol: String = "websocket" /// None of the websocket headers are actually defined as 'required'. @@ -34,7 +33,7 @@ public final class NIOWebSocketClientUpgrader: NIOHTTPClientProtocolUpgrader { private let requestKey: String private let maxFrameSize: Int private let automaticErrorHandling: Bool - private let upgradePipelineHandler: (Channel, HTTPResponseHead) -> EventLoopFuture + private let upgradePipelineHandler: @Sendable (Channel, HTTPResponseHead) -> EventLoopFuture /// - Parameters: /// - requestKey: sent to the server in the `Sec-WebSocket-Key` HTTP header. Default is random request key. @@ -45,7 +44,7 @@ public final class NIOWebSocketClientUpgrader: NIOHTTPClientProtocolUpgrader { requestKey: String = randomRequestKey(), maxFrameSize: Int = 1 << 14, automaticErrorHandling: Bool = true, - upgradePipelineHandler: @escaping (Channel, HTTPResponseHead) -> EventLoopFuture + upgradePipelineHandler: @escaping @Sendable (Channel, HTTPResponseHead) -> EventLoopFuture ) { precondition(requestKey != "", "The request key must contain a valid Sec-WebSocket-Key") precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size") @@ -57,49 +56,81 @@ public final class NIOWebSocketClientUpgrader: NIOHTTPClientProtocolUpgrader { /// Add additional headers that are needed for a WebSocket upgrade request. public func addCustom(upgradeRequestHeaders: inout HTTPHeaders) { - upgradeRequestHeaders.add(name: "Sec-WebSocket-Key", value: self.requestKey) - upgradeRequestHeaders.add(name: "Sec-WebSocket-Version", value: "13") + _addCustom(upgradeRequestHeaders: &upgradeRequestHeaders, requestKey: self.requestKey) } - /// Allow or deny the upgrade based on the upgrade HTTP response - /// headers containing the correct accept key. public func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool { - - let acceptValueHeader = upgradeResponse.headers["Sec-WebSocket-Accept"] - - guard acceptValueHeader.count == 1 else { - return false - } - - // Validate the response key in 'Sec-WebSocket-Accept'. - var hasher = SHA1() - hasher.update(string: self.requestKey) - hasher.update(string: magicWebSocketGUID) - let expectedAcceptValue = String(base64Encoding: hasher.finish()) - - return expectedAcceptValue == acceptValueHeader[0] + _shouldAllowUpgrade(upgradeResponse: upgradeResponse, requestKey: self.requestKey) } - /// Called when the upgrade response has been flushed and it is safe to mutate the channel - /// pipeline. Adds channel handlers for websocket frame encoding, decoding and errors. public func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { - - var upgradeFuture = context.pipeline.addHandler(WebSocketFrameEncoder()).flatMap { - context.pipeline.addHandler(ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: self.maxFrameSize))) - } - - if self.automaticErrorHandling { - upgradeFuture = upgradeFuture.flatMap { - context.pipeline.addHandler(WebSocketProtocolErrorHandler()) - } - } - - return upgradeFuture.flatMap { - self.upgradePipelineHandler(context.channel, upgradeResponse) - } + _upgrade( + channel: context.channel, + upgradeResponse: upgradeResponse, + maxFrameSize: self.maxFrameSize, + enableAutomaticErrorHandling: self.automaticErrorHandling, + upgradePipelineHandler: self.upgradePipelineHandler + ) } } +/// A `NIOTypedHTTPClientProtocolUpgrader` that knows how to do the WebSocket upgrade dance. +/// +/// This upgrader assumes that the `HTTPClientUpgradeHandler` will create and send the upgrade request. +/// This upgrader also assumes that the `HTTPClientUpgradeHandler` will appropriately mutate the +/// pipeline to remove the HTTP `ChannelHandler`s. +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +@_spi(AsyncChannel) +public final class NIOTypedWebSocketClientUpgrader: NIOTypedHTTPClientProtocolUpgrader { + /// RFC 6455 specs this as the required entry in the Upgrade header. + public let supportedProtocol: String = "websocket" + /// None of the websocket headers are actually defined as 'required'. + public let requiredUpgradeHeaders: [String] = [] + + private let requestKey: String + private let maxFrameSize: Int + private let enableAutomaticErrorHandling: Bool + private let upgradePipelineHandler: @Sendable (Channel, HTTPResponseHead) -> EventLoopFuture + + /// - Parameters: + /// - requestKey: Sent to the server in the `Sec-WebSocket-Key` HTTP header. Default is random request key. + /// - maxFrameSize: Largest incoming `WebSocketFrame` size in bytes. Default is 16,384 bytes. + /// - enableAutomaticErrorHandling: If true, adds `WebSocketProtocolErrorHandler` to the channel pipeline to catch and respond to WebSocket protocol errors. Default is true. + /// - upgradePipelineHandler: Called once the upgrade was successful. + public init( + requestKey: String = NIOWebSocketClientUpgrader.randomRequestKey(), + maxFrameSize: Int = 1 << 14, + enableAutomaticErrorHandling: Bool = true, + upgradePipelineHandler: @escaping @Sendable (Channel, HTTPResponseHead) -> EventLoopFuture + ) { + precondition(requestKey != "", "The request key must contain a valid Sec-WebSocket-Key") + precondition(maxFrameSize <= UInt32.max, "invalid overlarge max frame size") + self.requestKey = requestKey + self.upgradePipelineHandler = upgradePipelineHandler + self.maxFrameSize = maxFrameSize + self.enableAutomaticErrorHandling = enableAutomaticErrorHandling + } + + public func addCustom(upgradeRequestHeaders: inout NIOHTTP1.HTTPHeaders) { + _addCustom(upgradeRequestHeaders: &upgradeRequestHeaders, requestKey: self.requestKey) + } + + public func shouldAllowUpgrade(upgradeResponse: HTTPResponseHead) -> Bool { + _shouldAllowUpgrade(upgradeResponse: upgradeResponse, requestKey: self.requestKey) + } + + public func upgrade(channel: Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + _upgrade( + channel: channel, + upgradeResponse: upgradeResponse, + maxFrameSize: self.maxFrameSize, + enableAutomaticErrorHandling: self.enableAutomaticErrorHandling, + upgradePipelineHandler: self.upgradePipelineHandler + ) + } +} + + @available(*, unavailable) extension NIOWebSocketClientUpgrader: Sendable {} @@ -128,3 +159,48 @@ extension NIOWebSocketClientUpgrader { return NIOWebSocketClientUpgrader.randomRequestKey(using: &generator) } } + +/// Add additional headers that are needed for a WebSocket upgrade request. +private func _addCustom(upgradeRequestHeaders: inout HTTPHeaders, requestKey: String) { + upgradeRequestHeaders.add(name: "Sec-WebSocket-Key", value: requestKey) + upgradeRequestHeaders.add(name: "Sec-WebSocket-Version", value: "13") +} + +/// Allow or deny the upgrade based on the upgrade HTTP response +/// headers containing the correct accept key. +private func _shouldAllowUpgrade(upgradeResponse: HTTPResponseHead, requestKey: String) -> Bool { + let acceptValueHeader = upgradeResponse.headers["Sec-WebSocket-Accept"] + + guard acceptValueHeader.count == 1 else { + return false + } + + // Validate the response key in 'Sec-WebSocket-Accept'. + var hasher = SHA1() + hasher.update(string: requestKey) + hasher.update(string: magicWebSocketGUID) + let expectedAcceptValue = String(base64Encoding: hasher.finish()) + + return expectedAcceptValue == acceptValueHeader[0] +} + +/// Called when the upgrade response has been flushed and it is safe to mutate the channel +/// pipeline. Adds channel handlers for websocket frame encoding, decoding and errors. +private func _upgrade( + channel: Channel, + upgradeResponse: HTTPResponseHead, + maxFrameSize: Int, + enableAutomaticErrorHandling: Bool, + upgradePipelineHandler: @escaping @Sendable (Channel, HTTPResponseHead) -> EventLoopFuture +) -> EventLoopFuture { + return channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(WebSocketFrameEncoder()) + try channel.pipeline.syncOperations.addHandler(ByteToMessageHandler(WebSocketFrameDecoder(maxFrameSize: maxFrameSize))) + if enableAutomaticErrorHandling { + try channel.pipeline.syncOperations.addHandler(WebSocketProtocolErrorHandler()) + } + } + .flatMap { + upgradePipelineHandler(channel, upgradeResponse) + } +} diff --git a/Sources/NIOWebSocketClient/Client.swift b/Sources/NIOWebSocketClient/Client.swift new file mode 100644 index 000000000..fef5b1e15 --- /dev/null +++ b/Sources/NIOWebSocketClient/Client.swift @@ -0,0 +1,144 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2021 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 +// +//===----------------------------------------------------------------------===// +#if swift(>=5.9) +@_spi(AsyncChannel) import NIOCore +@_spi(AsyncChannel) import NIOPosix +@_spi(AsyncChannel) import NIOHTTP1 +@_spi(AsyncChannel) import NIOWebSocket + +@available(macOS 14, *) +@main +struct Client { + /// The host to connect to. + private let host: String + /// The port to connect to. + private let port: Int + /// The client's event loop group. + private let eventLoopGroup: MultiThreadedEventLoopGroup + + enum UpgradeResult { + case websocket(NIOAsyncChannel) + case notUpgraded + } + + static func main() async throws { + let client = Client( + host: "localhost", + port: 8888, + eventLoopGroup: .singleton + ) + try await client.run() + } + + /// This method starts the client and tries to setup a WebSocket connection. + func run() async throws { + let upgradeResult: EventLoopFuture = try await ClientBootstrap(group: self.eventLoopGroup) + .connect( + host: self.host, + port: self.port + ) { channel in + channel.eventLoop.makeCompletedFuture { + let upgrader = NIOTypedWebSocketClientUpgrader( + upgradePipelineHandler: { (channel, _) in + channel.eventLoop.makeCompletedFuture { + let asyncChannel = try NIOAsyncChannel(synchronouslyWrapping: channel) + return UpgradeResult.websocket(asyncChannel) + } + } + ) + + var headers = HTTPHeaders() + headers.add(name: "Content-Type", value: "text/plain; charset=utf-8") + headers.add(name: "Content-Length", value: "0") + + let requestHead = HTTPRequestHead( + version: .http1_1, + method: .GET, + uri: "/", + headers: headers + ) + + let clientUpgradeConfiguration = NIOTypedHTTPClientUpgradeConfiguration( + upgradeRequestHead: requestHead, + upgraders: [upgrader], + notUpgradingCompletionHandler: { channel in + channel.eventLoop.makeCompletedFuture { + return UpgradeResult.notUpgraded + } + } + ) + + let negotiationResultFuture = try channel.pipeline.syncOperations.configureUpgradableHTTPClientPipeline( + configuration: .init(upgradeConfiguration: clientUpgradeConfiguration) + ) + + return negotiationResultFuture + } + } + + // We are awaiting and handling the upgrade result now. + try await self.handleUpgradeResult(upgradeResult) + } + + /// This method handles the upgrade result. + private func handleUpgradeResult(_ upgradeResult: EventLoopFuture) async throws { + switch try await upgradeResult.get() { + case .websocket(let websocketChannel): + print("Handling websocket connection") + try await self.handleWebsocketChannel(websocketChannel) + print("Done handling websocket connection") + case .notUpgraded: + // The upgrade to websocket did not succeed. We are just exiting in this case. + print("Upgrade declined") + } + } + + private func handleWebsocketChannel(_ channel: NIOAsyncChannel) async throws { + // We are sending a ping frame and then + // start to handle all inbound frames. + + let pingFrame = WebSocketFrame(fin: true, opcode: .ping, data: ByteBuffer(string: "Hello!")) + try await channel.outboundWriter.write(pingFrame) + + for try await frame in channel.inboundStream { + switch frame.opcode { + case .pong: + print("Received pong: \(String(buffer: frame.data))") + + case .text: + print("Received: \(String(buffer: frame.data))") + + case .connectionClose: + // Handle a received close frame. We're just going to close by returning from this method. + print("Received Close instruction from server") + return + case .binary, .continuation, .ping: + // We ignore these frames. + break + default: + // Unknown frames are errors. + return + } + } + } +} + +#else +@main +struct Server { + static func main() { + fatalError("Requires at least Swift 5.9") + } +} +#endif diff --git a/Sources/NIOWebSocketClient/main.swift b/Sources/NIOWebSocketClient/main.swift deleted file mode 100644 index 5e86a9e04..000000000 --- a/Sources/NIOWebSocketClient/main.swift +++ /dev/null @@ -1,233 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the SwiftNIO open source project -// -// Copyright (c) 2017-2021 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 -import NIOPosix -import NIOHTTP1 -import NIOWebSocket - -print("Establishing connection.") - -enum ConnectTo { - case ip(host: String, port: Int) - case unixDomainSocket(path: String) -} - -// The HTTP handler to be used to initiate the request. -// This initial request will be adapted by the WebSocket upgrader to contain the upgrade header parameters. -// Channel read will only be called if the upgrade fails. - -private final class HTTPInitialRequestHandler: ChannelInboundHandler, RemovableChannelHandler { - public typealias InboundIn = HTTPClientResponsePart - public typealias OutboundOut = HTTPClientRequestPart - - public let target: ConnectTo - - public init(target: ConnectTo) { - self.target = target - } - - public func channelActive(context: ChannelHandlerContext) { - print("Client connected to \(context.remoteAddress!)") - - // We are connected. It's time to send the message to the server to initialize the upgrade dance. - var headers = HTTPHeaders() - if case let .ip(host: host, port: port) = target { - headers.add(name: "Host", value: "\(host):\(port)") - } - headers.add(name: "Content-Type", value: "text/plain; charset=utf-8") - headers.add(name: "Content-Length", value: "\(0)") - - let requestHead = HTTPRequestHead(version: .http1_1, - method: .GET, - uri: "/", - headers: headers) - - context.write(self.wrapOutboundOut(.head(requestHead)), promise: nil) - - let body = HTTPClientRequestPart.body(.byteBuffer(ByteBuffer())) - context.write(self.wrapOutboundOut(body), promise: nil) - - context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) - } - - public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - - let clientResponse = self.unwrapInboundIn(data) - - print("Upgrade failed") - - switch clientResponse { - case .head(let responseHead): - print("Received status: \(responseHead.status)") - case .body(let byteBuffer): - let string = String(buffer: byteBuffer) - print("Received: '\(string)' back from the server.") - case .end: - print("Closing channel.") - context.close(promise: nil) - } - } - - public func handlerRemoved(context: ChannelHandlerContext) { - print("HTTP handler removed.") - } - - public func errorCaught(context: ChannelHandlerContext, error: Error) { - print("error: ", error) - - // As we are not really interested getting notified on success or failure - // we just pass nil as promise to reduce allocations. - context.close(promise: nil) - } -} - -// The web socket handler to be used once the upgrade has occurred. -// One added, it sends a ping-pong round trip with "Hello World" data. -// It also listens for any text frames from the server and prints them. - -private final class WebSocketPingPongHandler: ChannelInboundHandler { - typealias InboundIn = WebSocketFrame - typealias OutboundOut = WebSocketFrame - - let testFrameData: String = "Hello World" - - // This is being hit, channel active won't be called as it is already added. - public func handlerAdded(context: ChannelHandlerContext) { - print("WebSocket handler added.") - self.pingTestFrameData(context: context) - } - - public func handlerRemoved(context: ChannelHandlerContext) { - print("WebSocket handler removed.") - } - - public func channelRead(context: ChannelHandlerContext, data: NIOAny) { - let frame = self.unwrapInboundIn(data) - - switch frame.opcode { - case .pong: - self.pong(context: context, frame: frame) - case .text: - var data = frame.unmaskedData - let text = data.readString(length: data.readableBytes) ?? "" - print("Websocket: Received \(text)") - case .connectionClose: - self.receivedClose(context: context, frame: frame) - case .binary, .continuation, .ping: - // We ignore these frames. - break - default: - // Unknown frames are errors. - self.closeOnError(context: context) - } - } - - public func channelReadComplete(context: ChannelHandlerContext) { - context.flush() - } - - private func receivedClose(context: ChannelHandlerContext, frame: WebSocketFrame) { - // Handle a received close frame. We're just going to close. - print("Received Close instruction from server") - context.close(promise: nil) - } - - private func pingTestFrameData(context: ChannelHandlerContext) { - let buffer = context.channel.allocator.buffer(string: self.testFrameData) - let frame = WebSocketFrame(fin: true, opcode: .ping, data: buffer) - context.writeAndFlush(self.wrapOutboundOut(frame), promise: nil) - } - - private func pong(context: ChannelHandlerContext, frame: WebSocketFrame) { - var frameData = frame.data - if let frameDataString = frameData.readString(length: self.testFrameData.count) { - print("Websocket: Received: \(frameDataString)") - } - } - - private func closeOnError(context: ChannelHandlerContext) { - // We have hit an error, we want to close. We do that by sending a close frame and then - // shutting down the write side of the connection. The server will respond with a close of its own. - var data = context.channel.allocator.buffer(capacity: 2) - data.write(webSocketErrorCode: .protocolError) - let frame = WebSocketFrame(fin: true, opcode: .connectionClose, data: data) - context.write(self.wrapOutboundOut(frame)).whenComplete { (_: Result) in - context.close(mode: .output, promise: nil) - } - } -} - -// First argument is the program path -let arguments = CommandLine.arguments -let arg1 = arguments.dropFirst().first -let arg2 = arguments.dropFirst(2).first - -let defaultHost = "::1" -let defaultPort: Int = 8888 - -let connectTarget: ConnectTo -switch (arg1, arg1.flatMap(Int.init), arg2.flatMap(Int.init)) { -case (.some(let h), _ , .some(let p)): - /* we got two arguments, let's interpret that as host and port */ - connectTarget = .ip(host: h, port: p) -case (.some(let portString), .none, _): - /* couldn't parse as number, expecting unix domain socket path */ - connectTarget = .unixDomainSocket(path: portString) -case (_, .some(let p), _): - /* only one argument --> port */ - connectTarget = .ip(host: defaultHost, port: p) -default: - connectTarget = .ip(host: defaultHost, port: defaultPort) -} - -let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) -let bootstrap = ClientBootstrap(group: group) - // Enable SO_REUSEADDR. - .channelOption(ChannelOptions.socketOption(.so_reuseaddr), value: 1) - .channelInitializer { channel in - - let httpHandler = HTTPInitialRequestHandler(target: connectTarget) - - let websocketUpgrader = NIOWebSocketClientUpgrader(requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", - upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in - channel.pipeline.addHandler(WebSocketPingPongHandler()) - }) - - let config: NIOHTTPClientUpgradeConfiguration = ( - upgraders: [ websocketUpgrader ], - completionHandler: { _ in - channel.pipeline.removeHandler(httpHandler, promise: nil) - }) - - return channel.pipeline.addHTTPClientHandlers(withClientUpgrade: config).flatMap { - channel.pipeline.addHandler(httpHandler) - } -} -defer { - try! group.syncShutdownGracefully() -} - -let channel = try { () -> Channel in - switch connectTarget { - case .ip(let host, let port): - return try bootstrap.connect(host: host, port: port).wait() - case .unixDomainSocket(let path): - return try bootstrap.connect(unixDomainSocketPath: path).wait() - } -}() - -// Will be closed after we echo-ed back to the server. -try channel.closeFuture.wait() - -print("Client closed") diff --git a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift index 56c7bd3cf..8344f4741 100644 --- a/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPClientUpgradeTests.swift @@ -16,7 +16,7 @@ import XCTest import Dispatch @testable import NIOCore import NIOEmbedded -@testable import NIOHTTP1 +@_spi(AsyncChannel) @testable import NIOHTTP1 extension EmbeddedChannel { @@ -32,31 +32,10 @@ extension EmbeddedChannel { } } -private func setUpClientChannel(clientHTTPHandler: RemovableChannelHandler, - clientUpgraders: [NIOHTTPClientProtocolUpgrader], - _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void) throws -> EmbeddedChannel { - - let channel = EmbeddedChannel() - - let config: NIOHTTPClientUpgradeConfiguration = ( - upgraders: clientUpgraders, - completionHandler: { context in - channel.pipeline.removeHandler(clientHTTPHandler, promise: nil) - upgradeCompletionHandler(context) - }) +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +protocol TypedAndUntypedHTTPClientProtocolUpgrader: NIOHTTPClientProtocolUpgrader, NIOTypedHTTPClientProtocolUpgrader where UpgradeResult == Bool {} - try channel.pipeline.addHTTPClientHandlers(leftOverBytesStrategy: .forwardBytes, withClientUpgrade: config).flatMap({ - channel.pipeline.addHandler(clientHTTPHandler) - }).wait() - - try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) - .wait() - - return channel -} - -private final class SuccessfulClientUpgrader: NIOHTTPClientProtocolUpgrader { - +private final class SuccessfulClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgrader { fileprivate let supportedProtocol: String fileprivate let requiredUpgradeHeaders: [String] fileprivate let upgradeHeaders: [(String,String)] @@ -87,10 +66,15 @@ private final class SuccessfulClientUpgrader: NIOHTTPClientProtocolUpgrader { self.upgradeContextResponseCallCount += 1 return context.channel.eventLoop.makeSucceededFuture(()) } + + func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + self.upgradeContextResponseCallCount += 1 + return channel.eventLoop.makeSucceededFuture(true) + } } -private final class ExplodingClientUpgrader: NIOHTTPClientProtocolUpgrader { - +private final class ExplodingClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgrader { + fileprivate let supportedProtocol: String fileprivate let requiredUpgradeHeaders: [String] fileprivate let upgradeHeaders: [(String,String)] @@ -118,10 +102,15 @@ private final class ExplodingClientUpgrader: NIOHTTPClientProtocolUpgrader { XCTFail("Upgrade should not be called.") return context.channel.eventLoop.makeSucceededFuture(()) } + + func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + XCTFail("Upgrade should not be called.") + return channel.eventLoop.makeSucceededFuture(false) + } } -private final class DenyingClientUpgrader: NIOHTTPClientProtocolUpgrader { - +private final class DenyingClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgrader { + fileprivate let supportedProtocol: String fileprivate let requiredUpgradeHeaders: [String] fileprivate let upgradeHeaders: [(String,String)] @@ -152,9 +141,14 @@ private final class DenyingClientUpgrader: NIOHTTPClientProtocolUpgrader { XCTFail("Upgrade should not be called.") return context.channel.eventLoop.makeSucceededFuture(()) } + + func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + XCTFail("Upgrade should not be called.") + return channel.eventLoop.makeSucceededFuture(false) + } } -private final class UpgradeDelayClientUpgrader: NIOHTTPClientProtocolUpgrader { +private final class UpgradeDelayClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgrader { fileprivate let supportedProtocol: String fileprivate let requiredUpgradeHeaders: [String] @@ -188,7 +182,14 @@ private final class UpgradeDelayClientUpgrader: NIOHTTPClientProtocolUpgrader { context.pipeline.addHandler(self.upgradedHandler) } } - + + func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + self.upgradePromise = channel.eventLoop.makePromise() + return self.upgradePromise!.futureResult.flatMap { + channel.pipeline.addHandler(self.upgradedHandler) + }.map { _ in true} + } + fileprivate func unblockUpgrade() { self.upgradePromise!.succeed(()) } @@ -278,9 +279,41 @@ private final class RecordingHTTPHandler: ChannelInboundHandler, RemovableChanne } } +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +private func assertPipelineContainsUpgradeHandler(channel: Channel) { + let handler = try? channel.pipeline.syncOperations.handler(type: NIOHTTPClientUpgradeHandler.self) + let typedHandler = try? channel.pipeline.syncOperations.handler(type: NIOTypedHTTPClientUpgradeHandler.self) + + XCTAssertTrue(handler != nil || typedHandler != nil) +} + @available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) class HTTPClientUpgradeTestCase: XCTestCase { - + func setUpClientChannel( + clientHTTPHandler: RemovableChannelHandler, + clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], + _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void + ) throws -> EmbeddedChannel { + + let channel = EmbeddedChannel() + + let config: NIOHTTPClientUpgradeConfiguration = ( + upgraders: clientUpgraders, + completionHandler: { context in + channel.pipeline.removeHandler(clientHTTPHandler, promise: nil) + upgradeCompletionHandler(context) + }) + + try channel.pipeline.addHTTPClientHandlers(leftOverBytesStrategy: .forwardBytes, withClientUpgrade: config).flatMap({ + channel.pipeline.addHandler(clientHTTPHandler) + }).wait() + + try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + + return channel + } + // MARK: Test basic happy path requests and responses. func testSimpleUpgradeSucceeds() throws { @@ -320,9 +353,8 @@ class HTTPClientUpgradeTestCase: XCTestCase { .assertContains(handlerType: HTTPRequestEncoder.self)) XCTAssertNoThrow(try clientChannel.pipeline .assertContains(handlerType: ByteToMessageHandler.self)) - XCTAssertNoThrow(try clientChannel.pipeline - .assertContains(handlerType: NIOHTTPClientUpgradeHandler.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" @@ -401,8 +433,8 @@ class HTTPClientUpgradeTestCase: XCTestCase { let clientUpgrader = SuccessfulClientUpgrader(forProtocol: upgradeProtocol, upgradeHeaders: clientHeaders) - let clientUpgraders: [NIOHTTPClientProtocolUpgrader] = [unusedClientUpgrader, clientUpgrader] - + let clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader] = [unusedClientUpgrader, clientUpgrader] + // The process should kick-off independently by sending the upgrade request to the server. let clientChannel = try setUpClientChannel(clientHTTPHandler: ExplodingHTTPHandler(), clientUpgraders: clientUpgraders) { (context) in @@ -457,7 +489,7 @@ class HTTPClientUpgradeTestCase: XCTestCase { } } - final class AddHandlerClientUpgrader: NIOHTTPClientProtocolUpgrader { + final class AddHandlerClientUpgrader: TypedAndUntypedHTTPClientProtocolUpgrader { fileprivate let requiredUpgradeHeaders: [String] = [] fileprivate let supportedProtocol: String fileprivate let handler: T @@ -476,6 +508,10 @@ class HTTPClientUpgradeTestCase: XCTestCase { func upgrade(context: ChannelHandlerContext, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { return context.pipeline.addHandler(handler) } + + func upgrade(channel: any Channel, upgradeResponse: HTTPResponseHead) -> EventLoopFuture { + return channel.pipeline.addHandler(handler).map { _ in true } + } } var upgradeHandlerCallbackFired = false @@ -923,3 +959,239 @@ class HTTPClientUpgradeTestCase: XCTestCase { } } } + +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +final class TypedHTTPClientUpgradeTestCase: HTTPClientUpgradeTestCase { + override func setUpClientChannel( + clientHTTPHandler: RemovableChannelHandler, + clientUpgraders: [any TypedAndUntypedHTTPClientProtocolUpgrader], + _ upgradeCompletionHandler: @escaping (ChannelHandlerContext) -> Void + ) throws -> EmbeddedChannel { + + let channel = EmbeddedChannel() + + var headers = HTTPHeaders() + headers.add(name: "Content-Type", value: "text/plain; charset=utf-8") + headers.add(name: "Content-Length", value: "\(0)") + + let requestHead = HTTPRequestHead( + version: .http1_1, + method: .GET, + uri: "/", + headers: headers + ) + + let upgraders: [any NIOTypedHTTPClientProtocolUpgrader] = Array(clientUpgraders.map { $0 as! any NIOTypedHTTPClientProtocolUpgrader }) + + let config = NIOTypedHTTPClientUpgradeConfiguration( + upgradeRequestHead: requestHead, + upgraders: upgraders + ) { channel in + channel.eventLoop.makeCompletedFuture { + try channel.pipeline.syncOperations.addHandler(clientHTTPHandler) + }.map { _ in + false + } + } + var configuration = NIOUpgradableHTTPClientPipelineConfiguration(upgradeConfiguration: config) + configuration.leftOverBytesStrategy = .forwardBytes + let upgradeResult = try channel.pipeline.syncOperations.configureUpgradableHTTPClientPipeline(configuration: configuration) + let context = try channel.pipeline.syncOperations.context(handlerType: NIOTypedHTTPClientUpgradeHandler.self) + + try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + upgradeResult.whenSuccess { result in + if result { + upgradeCompletionHandler(context) + } + } + + return channel + } + + // - MARK: The following tests are all overridden from the base class since they slightly differ in behaviour + + override func testUpgradeOnlyHandlesKnownProtocols() throws { + var upgradeHandlerCallbackFired = false + + let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto") + let clientHandler = RecordingHTTPHandler() + + // The process should kick-off independently by sending the upgrade request to the server. + let clientChannel = try setUpClientChannel(clientHTTPHandler: clientHandler, + clientUpgraders: [clientUpgrader]) { _ in + + // This is called before the upgrader gets called. + upgradeHandlerCallbackFired = true + } + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: unknownProtocol\r\n\r\n" + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, .responseProtocolNotFound) + } + + clientChannel.embeddedEventLoop.run() + + // Should fail with error (response is malformed) and remove upgrader from pipeline. + + // Check that the http elements are not removed from the pipeline. + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: HTTPRequestEncoder.self)) + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: ByteToMessageHandler.self)) + + // Check that the HTTP handler received its response. + XCTAssertLessThanOrEqual(0, clientHandler.channelReadChannelHandlerContextDataCallCount) + // Check an error is reported + XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount) + + XCTAssertFalse(upgradeHandlerCallbackFired) + + XCTAssertNoThrow(try clientChannel.pipeline + .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self)) + } + + override func testUpgradeResponseCanBeRejectedByClientUpgrader() throws { + let upgradeProtocol = "myProto" + + var upgradeHandlerCallbackFired = false + + let clientUpgrader = DenyingClientUpgrader(forProtocol: upgradeProtocol) + let clientHandler = RecordingHTTPHandler() + + // The process should kick-off independently by sending the upgrade request to the server. + let clientChannel = try setUpClientChannel(clientHTTPHandler: clientHandler, + clientUpgraders: [clientUpgrader]) { _ in + + // This is called before the upgrader gets called. + upgradeHandlerCallbackFired = true + } + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: \(upgradeProtocol)\r\n\r\n" + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, .upgraderDeniedUpgrade) + } + + clientChannel.embeddedEventLoop.run() + + // Should fail with error (response is denied) and remove upgrader from pipeline. + + // Check that the http elements are not removed from the pipeline. + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: HTTPRequestEncoder.self)) + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: ByteToMessageHandler.self)) + + XCTAssertEqual(1, clientUpgrader.addCustomUpgradeRequestHeadersCallCount) + + // Check that the HTTP handler received its response. + XCTAssertLessThanOrEqual(0, clientHandler.channelReadChannelHandlerContextDataCallCount) + + // Check an error is reported + XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount) + + XCTAssertFalse(upgradeHandlerCallbackFired) + + XCTAssertNoThrow(try clientChannel.pipeline + .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self)) + } + + override func testFiresOutboundErrorDuringAddingHandlers() throws { + let upgradeProtocol = "myProto" + var errorOnAdditionalChannelWrite: Error? + var upgradeHandlerCallbackFired = false + + let clientUpgrader = UpgradeDelayClientUpgrader(forProtocol: upgradeProtocol) + let clientHandler = RecordingHTTPHandler() + + let clientChannel = try setUpClientChannel(clientHTTPHandler: clientHandler, + clientUpgraders: [clientUpgrader]) { (context) in + + // This is called before the upgrader gets called. + upgradeHandlerCallbackFired = true + } + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + + // 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))) + + let promise = clientChannel.eventLoop.makePromise(of: Void.self) + + promise.futureResult.whenFailure() { error in + errorOnAdditionalChannelWrite = error + } + + // Send another outbound request during the upgrade. + let requestHead = HTTPRequestHead(version: .http1_1, method: .GET, uri: "/") + let secondRequest: HTTPClientRequestPart = .head(requestHead) + clientChannel.writeAndFlush(secondRequest, promise: promise) + + clientChannel.embeddedEventLoop.run() + + let promiseError = errorOnAdditionalChannelWrite as! NIOHTTPClientUpgradeError + XCTAssertEqual(NIOHTTPClientUpgradeError.writingToHandlerDuringUpgrade, promiseError) + + // Soundness check that the upgrade was delayed. + XCTAssertEqual(0, clientUpgrader.upgradedHandler.handlerAddedContextCallCount) + + // Upgrade now. + clientUpgrader.unblockUpgrade() + clientChannel.embeddedEventLoop.run() + + // Check that the upgrade was still successful, despite the interruption. + XCTAssert(upgradeHandlerCallbackFired) + XCTAssertEqual(1, clientUpgrader.upgradedHandler.handlerAddedContextCallCount) + } + + override func testUpgradeResponseMissingAllProtocols() throws { + var upgradeHandlerCallbackFired = false + + let clientUpgrader = ExplodingClientUpgrader(forProtocol: "myProto") + let clientHandler = RecordingHTTPHandler() + + // The process should kick-off independently by sending the upgrade request to the server. + let clientChannel = try setUpClientChannel(clientHTTPHandler: clientHandler, + clientUpgraders: [clientUpgrader]) { _ in + + // This is called before the upgrader gets called. + upgradeHandlerCallbackFired = true + } + defer { + XCTAssertNoThrow(try clientChannel.finish()) + } + + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\n\r\n" + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, .responseProtocolNotFound) + } + + clientChannel.embeddedEventLoop.run() + + // Should fail with error (response is malformed) and remove upgrader from pipeline. + + // Check that the http elements are not removed from the pipeline. + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: HTTPRequestEncoder.self)) + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: ByteToMessageHandler.self)) + + // Check that the HTTP handler received its response. + XCTAssertLessThanOrEqual(0, clientHandler.channelReadChannelHandlerContextDataCallCount) + // Check an error is reported + XCTAssertEqual(0, clientHandler.errorCaughtChannelHandlerContextCallCount) + + XCTAssertFalse(upgradeHandlerCallbackFired) + + XCTAssertNoThrow(try clientChannel.pipeline + .assertDoesNotContain(handlerType: NIOHTTPClientUpgradeHandler.self)) + } +} diff --git a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift index fd974e253..94df819eb 100644 --- a/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift +++ b/Tests/NIOWebSocketTests/WebSocketClientEndToEndTests.swift @@ -15,8 +15,8 @@ import XCTest import NIOCore import NIOEmbedded -import NIOHTTP1 -@testable import NIOWebSocket +@_spi(AsyncChannel) import NIOHTTP1 +@_spi(AsyncChannel) @testable import NIOWebSocket extension EmbeddedChannel { @@ -146,12 +146,12 @@ private class WebSocketRecorderHandler: ChannelInboundHandler, ChannelOutboundHa } } +private func basicRequest(path: String = "/") -> String { + return "GET \(path) HTTP/1.1\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0" +} + +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) class WebSocketClientEndToEndTests: XCTestCase { - - private func basicRequest(path: String = "/") -> String { - return "GET \(path) HTTP/1.1\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 0" - } - func testSimpleUpgradeSucceeds() throws { var upgradeHandlerCallbackFired = false @@ -173,7 +173,7 @@ class WebSocketClientEndToEndTests: XCTestCase { // Read the server request. if let requestString = try clientChannel.readByteBufferOutputAsString() { - XCTAssertEqual(requestString, self.basicRequest() + "\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: \(requestKey)\r\nSec-WebSocket-Version: 13\r\n\r\n") + XCTAssertEqual(requestString, basicRequest() + "\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: \(requestKey)\r\nSec-WebSocket-Version: 13\r\n\r\n") } else { XCTFail() } @@ -284,7 +284,7 @@ class WebSocketClientEndToEndTests: XCTestCase { XCTAssertNoThrow(try clientChannel.close().wait()) } - private func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { + fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { let handler = WebSocketRecorderHandler() @@ -404,3 +404,214 @@ class WebSocketClientEndToEndTests: XCTestCase { XCTAssertNoThrow(try clientChannel.close().wait()) } } + +@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *) +final class TypedWebSocketClientEndToEndTests: WebSocketClientEndToEndTests { + func setUpClientChannel( + clientUpgraders: [any NIOTypedHTTPClientProtocolUpgrader], + notUpgradingCompletionHandler: @Sendable @escaping (Channel) -> EventLoopFuture + ) throws -> (EmbeddedChannel, EventLoopFuture) { + + let channel = EmbeddedChannel() + + var headers = HTTPHeaders() + headers.add(name: "Content-Type", value: "text/plain; charset=utf-8") + headers.add(name: "Content-Length", value: "\(0)") + + let requestHead = HTTPRequestHead( + version: .http1_1, + method: .GET, + uri: "/", + headers: headers + ) + + let config = NIOTypedHTTPClientUpgradeConfiguration( + upgradeRequestHead: requestHead, + upgraders: clientUpgraders, + notUpgradingCompletionHandler: notUpgradingCompletionHandler + ) + + let upgradeResult = try channel.pipeline.syncOperations.configureUpgradableHTTPClientPipeline(configuration: .init(upgradeConfiguration: config)) + + try channel.connect(to: SocketAddress(ipAddress: "127.0.0.1", port: 0)) + .wait() + + return (channel, upgradeResult) + } + + override func testSimpleUpgradeSucceeds() throws { + let requestKey = "OfS0wDaT5NoxF2gqm7Zj2YtetzM=" + let responseKey = "yKEqitDFPE81FyIhKTm+ojBqigk=" + + let basicUpgrader = NIOTypedWebSocketClientUpgrader( + requestKey: requestKey, + upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in + channel.pipeline.addHandler(WebSocketRecorderHandler()) + }) + + // The process should kick-off independently by sending the upgrade request to the server. + let (clientChannel, upgradeResult) = try setUpClientChannel( + clientUpgraders: [basicUpgrader], + notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() } + ) + + // Read the server request. + if let requestString = try clientChannel.readByteBufferOutputAsString() { + XCTAssertEqual(requestString, basicRequest() + "\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Key: \(requestKey)\r\nSec-WebSocket-Version: 13\r\n\r\n") + } else { + XCTFail() + } + + // Push the successful server response. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept:\(responseKey)\r\n\r\n" + + XCTAssertNoThrow(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) + + clientChannel.embeddedEventLoop.run() + + // Once upgraded, validate the http 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 that the pipeline now has the correct websocket handlers added. + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: WebSocketFrameEncoder.self)) + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: ByteToMessageHandler.self)) + XCTAssertNoThrow(try clientChannel.pipeline + .assertContains(handlerType: WebSocketRecorderHandler.self)) + + try upgradeResult.wait() + + // Close the pipeline. + XCTAssertNoThrow(try clientChannel.close().wait()) + } + + override func testRejectUpgradeIfMissingAcceptKey() throws { + let requestKey = "OfS0wDaT5NoxF2gqm7Zj2YtetzM=" + + let basicUpgrader = NIOTypedWebSocketClientUpgrader( + requestKey: requestKey, + upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in + channel.pipeline.addHandler(WebSocketRecorderHandler()) + }) + + // The process should kick-off independently by sending the upgrade request to the server. + let (clientChannel, upgradeResult) = try setUpClientChannel( + clientUpgraders: [basicUpgrader], + notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() } + ) + + // Push the successful server response but with a missing accept key. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\n\r\n" + + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.upgraderDeniedUpgrade) + } + + // Close the pipeline. + XCTAssertNoThrow(try clientChannel.close().wait()) + + XCTAssertThrowsError(try upgradeResult.wait()) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.upgraderDeniedUpgrade) + } + } + + override func testRejectUpgradeIfIncorrectAcceptKey() throws { + let requestKey = "OfS0wDaT5NoxF2gqm7Zj2YtetzM=" + let responseKey = "notACorrectKeyL1am=F1y=nn=" + + let basicUpgrader = NIOTypedWebSocketClientUpgrader( + requestKey: requestKey, + upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in + channel.pipeline.addHandler(WebSocketRecorderHandler()) + }) + + // The process should kick-off independently by sending the upgrade request to the server. + let (clientChannel, upgradeResult) = try setUpClientChannel( + clientUpgraders: [basicUpgrader], + notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() } + ) + + // Push the successful server response but with an incorrect response key. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept:\(responseKey)\r\n\r\n" + + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.upgraderDeniedUpgrade) + } + + // Close the pipeline. + XCTAssertNoThrow(try clientChannel.close().wait()) + + XCTAssertThrowsError(try upgradeResult.wait()) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.upgraderDeniedUpgrade) + } + } + + override func testRejectUpgradeIfNotWebsocket() throws { + let requestKey = "OfS0wDaT5NoxF2gqm7Zj2YtetzM=" + let responseKey = "yKEqitDFPE81FyIhKTm+ojBqigk=" + + let basicUpgrader = NIOTypedWebSocketClientUpgrader( + requestKey: requestKey, + upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in + channel.pipeline.addHandler(WebSocketRecorderHandler()) + }) + + // The process should kick-off independently by sending the upgrade request to the server. + let (clientChannel, upgradeResult) = try setUpClientChannel( + clientUpgraders: [basicUpgrader], + notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() } + ) + + // Push the successful server response with an incorrect protocol. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: myProtocol\r\nSec-WebSocket-Accept:\(responseKey)\r\n\r\n" + + XCTAssertThrowsError(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.responseProtocolNotFound) + } + + // Close the pipeline. + XCTAssertNoThrow(try clientChannel.close().wait()) + + XCTAssertThrowsError(try upgradeResult.wait()) { error in + XCTAssertEqual(error as? NIOHTTPClientUpgradeError, NIOHTTPClientUpgradeError.responseProtocolNotFound) + } + } + + override fileprivate func runSuccessfulUpgrade() throws -> (EmbeddedChannel, WebSocketRecorderHandler) { + let handler = WebSocketRecorderHandler() + + let basicUpgrader = NIOTypedWebSocketClientUpgrader( + requestKey: "OfS0wDaT5NoxF2gqm7Zj2YtetzM=", + upgradePipelineHandler: { (channel: Channel, _: HTTPResponseHead) in + channel.pipeline.addHandler(handler) + }) + + // The process should kick-off independently by sending the upgrade request to the server. + let (clientChannel, upgradeResult) = try setUpClientChannel( + clientUpgraders: [basicUpgrader], + notUpgradingCompletionHandler: { $0.eventLoop.makeSucceededVoidFuture() } + ) + + // Push the successful server response. + let response = "HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept:yKEqitDFPE81FyIhKTm+ojBqigk=\r\n\r\n" + + XCTAssertNoThrow(try clientChannel.writeInbound(clientChannel.allocator.buffer(string: response))) + + clientChannel.embeddedEventLoop.run() + + // We now have a successful upgrade, clear the output channels read to test the frames. + XCTAssertNoThrow(try clientChannel.readOutbound(as: ByteBuffer.self)) + + clientChannel.embeddedEventLoop.run() + + try upgradeResult.wait() + + return (clientChannel, handler) + } +}