From 73eb597aa3bddebeff4c8722351bbd52e66103a7 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Fri, 28 Oct 2022 15:32:43 +0100 Subject: [PATCH] Don't unconditionally remove the HTTPServerUpgradeHandler (#2303) Motivation: The `HTTPServerUpgradeHandler` removes itself from the pipeline after an upgrade and unbuffers any unconsumed reads. If an upgrade starts but does not complete successfully then the pipeline may be left in an unknown state. If, for example, the failure occurs before the user provided upgrade handler is run then unbuffered writes may be unwrapped by the wrong channel handler as the wrong type leading to a crash. Modifications: - Only remove the upgrade handler and forward buffered writes if all parts of the upgrade complete successfully. - If part of the upgrade fails then fire an error into the channel pipeline without removing the server upgrade handler. - Remove a few unnecessary `map`s. - Make `httpEncoder` non-optional since and remove associated dead code since it can never be `nil`. Result: Upgrade handling is safer. --- .../NIOHTTP1/HTTPServerUpgradeHandler.swift | 38 ++--- .../HTTPServerUpgradeTests+XCTest.swift | 5 +- .../HTTPServerUpgradeTests.swift | 156 +++++++++++++++++- 3 files changed, 176 insertions(+), 23 deletions(-) diff --git a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift index ede0421a1..1e58e199f 100644 --- a/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift +++ b/Sources/NIOHTTP1/HTTPServerUpgradeHandler.swift @@ -66,7 +66,7 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha private let upgraders: [String: HTTPServerProtocolUpgrader] private let upgradeCompletionHandler: (ChannelHandlerContext) -> Void - private let httpEncoder: HTTPResponseEncoder? + private let httpEncoder: HTTPResponseEncoder private let extraHTTPHandlers: [RemovableChannelHandler] /// Whether we've already seen the first request. @@ -176,7 +176,7 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha self.handleUpgrade(context: context, request: request, requestedProtocols: requestedProtocols) .hop(to: context.eventLoop) // the user might return a future from another EventLoop. .whenSuccess { callback in - assert(context.eventLoop.inEventLoop) + context.eventLoop.assertInEventLoop() if let callback = callback { self.gotUpgrader(upgrader: callback) } else { @@ -235,17 +235,22 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha self.removeExtraHandlers(context: context).flatMap { self.sendUpgradeResponse(context: context, upgradeRequest: request, responseHeaders: finalResponseHeaders) }.flatMap { - self.removeHandler(context: context, handler: self.httpEncoder) - }.map { + context.pipeline.removeHandler(self.httpEncoder) + }.flatMap { () -> EventLoopFuture in self.upgradeCompletionHandler(context) - }.flatMap { - upgrader.upgrade(context: context, upgradeRequest: request) - }.map { - context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) - self.upgradeState = .upgradeComplete - }.whenComplete { (_: Result) in - // When we remove ourselves we'll be delivering any buffered data. - context.pipeline.removeHandler(context: context, promise: nil) + return upgrader.upgrade(context: context, upgradeRequest: request) + }.whenComplete { result in + switch result { + case .success: + context.fireUserInboundEventTriggered(HTTPServerUpgradeEvents.upgradeComplete(toProtocol: proto, upgradeRequest: request)) + self.upgradeState = .upgradeComplete + // When we remove ourselves we'll be delivering any buffered data. + context.pipeline.removeHandler(context: context, promise: nil) + + case .failure(let error): + // Remain in the '.upgrading' state. + context.fireErrorCaught(error) + } } } }.flatMapError { error in @@ -305,15 +310,6 @@ public final class HTTPServerUpgradeHandler: ChannelInboundHandler, RemovableCha return HTTPHeaders([("connection", "upgrade"), ("upgrade", `protocol`)]) } - /// Removes the given channel handler from the channel pipeline. - private func removeHandler(context: ChannelHandlerContext, handler: RemovableChannelHandler?) -> EventLoopFuture { - if let handler = handler { - return context.pipeline.removeHandler(handler) - } else { - return context.eventLoop.makeSucceededFuture(()) - } - } - /// Removes any extra HTTP-related handlers from the channel pipeline. private func removeExtraHandlers(context: ChannelHandlerContext) -> EventLoopFuture { guard self.extraHTTPHandlers.count > 0 else { diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests+XCTest.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests+XCTest.swift index 979842b97..6d8abfb75 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests+XCTest.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests+XCTest.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -49,6 +49,9 @@ extension HTTPServerUpgradeTestCase { ("testDeliversBytesWhenRemovedDuringPartialUpgrade", testDeliversBytesWhenRemovedDuringPartialUpgrade), ("testDeliversBytesWhenReentrantlyCalledInChannelReadCompleteOnRemoval", testDeliversBytesWhenReentrantlyCalledInChannelReadCompleteOnRemoval), ("testWeTolerateUpgradeFuturesFromWrongEventLoops", testWeTolerateUpgradeFuturesFromWrongEventLoops), + ("testFailingToRemoveExtraHandlersThrowsError", testFailingToRemoveExtraHandlersThrowsError), + ("testFailedUpgradeResponseWriteThrowsError", testFailedUpgradeResponseWriteThrowsError), + ("testFailedUpgraderThrowsError", testFailedUpgraderThrowsError), ] } } diff --git a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift index 6648f18b4..31a4f3d00 100644 --- a/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift +++ b/Tests/NIOHTTP1Tests/HTTPServerUpgradeTests.swift @@ -2,7 +2,7 @@ // // This source file is part of the SwiftNIO open source project // -// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors +// Copyright (c) 2017-2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information @@ -262,6 +262,33 @@ private class SuccessfulUpgrader: HTTPServerProtocolUpgrader { } } +private class DelayedUnsuccessfulUpgrader: HTTPServerProtocolUpgrader { + let supportedProtocol: String + let requiredUpgradeHeaders: [String] + + private var upgradePromise: EventLoopPromise? + + init(forProtocol `protocol`: String) { + self.supportedProtocol = `protocol` + self.requiredUpgradeHeaders = [] + } + + func buildUpgradeResponse(channel: Channel, + upgradeRequest: HTTPRequestHead, + initialResponseHeaders: HTTPHeaders) -> EventLoopFuture { + return channel.eventLoop.makeSucceededFuture([:]) + } + + func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture { + self.upgradePromise = context.eventLoop.makePromise() + return self.upgradePromise!.futureResult + } + + func unblockUpgrade(withError error: Error) { + self.upgradePromise!.fail(error) + } +} + private class UpgradeDelayer: HTTPServerProtocolUpgrader { let supportedProtocol: String let requiredUpgradeHeaders: [String] = [] @@ -1387,4 +1414,131 @@ class HTTPServerUpgradeTestCase: XCTestCase { // We also want to confirm that the upgrade handler is no longer in the pipeline. try connectedServer.pipeline.assertDoesNotContainUpgrader() } + + func testFailingToRemoveExtraHandlersThrowsError() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try? channel.finish()) + } + + let encoder = HTTPResponseEncoder() + let handlers: [RemovableChannelHandler] = [HTTPServerPipelineHandler(), HTTPServerProtocolErrorHandler()] + let upgradeHandler = HTTPServerUpgradeHandler(upgraders: [SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: [], onUpgradeComplete: { _ in })], + httpEncoder: encoder, + extraHTTPHandlers: handlers, + upgradeCompletionHandler: { _ in }) + + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(encoder)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandlers(handlers)) + XCTAssertNoThrow(try channel.pipeline.syncOperations.addHandler(upgradeHandler)) + + let userEventSaver = UserEventSaver() + let dataRecorder = DataRecorder() + XCTAssertNoThrow(try channel.pipeline.addHandler(userEventSaver).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(dataRecorder).wait()) + + // Remove one of the extra handlers. + XCTAssertNoThrow(try channel.pipeline.removeHandler(handlers.last!).wait()) + + let head = HTTPServerRequestPart.head(.init(version: .http1_1, method: .GET, uri: "/foo", headers: ["upgrade": "myproto"])) + XCTAssertNoThrow(try channel.writeInbound(head)) + XCTAssertThrowsError(try channel.writeInbound(HTTPServerRequestPart.end(nil))) { error in + XCTAssertEqual(error as? ChannelPipelineError, .notFound) + } + + // Upgrade didn't complete, so no user event. + XCTAssertTrue(userEventSaver.events.isEmpty) + // Nothing should have been forwarded. + XCTAssertTrue(dataRecorder.receivedData().isEmpty) + // The upgrade handler should still be in the pipeline. + try channel.pipeline.assertContainsUpgrader() + } + + func testFailedUpgradeResponseWriteThrowsError() throws { + final class FailAllWritesHandler: ChannelOutboundHandler { + typealias OutboundIn = NIOAny + struct FailAllWritesError: Error {} + + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise?) { + promise?.fail(FailAllWritesError()) + } + } + + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try? channel.finish()) + } + + let encoder = HTTPResponseEncoder() + let handler = HTTPServerUpgradeHandler(upgraders: [SuccessfulUpgrader(forProtocol: "myproto", requiringHeaders: []) { _ in }], + httpEncoder: encoder, + extraHTTPHandlers: []) { (_: ChannelHandlerContext) in + () + } + + XCTAssertNoThrow(try channel.pipeline.addHandler(FailAllWritesHandler()).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(encoder).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait()) + + let userEventSaver = UserEventSaver() + let dataRecorder = DataRecorder() + XCTAssertNoThrow(try channel.pipeline.addHandler(userEventSaver).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(dataRecorder).wait()) + + let head = HTTPServerRequestPart.head(.init(version: .http1_1, method: .GET, uri: "/foo", headers: ["upgrade": "myproto"])) + XCTAssertNoThrow(try channel.writeInbound(head)) + XCTAssertThrowsError(try channel.writeInbound(HTTPServerRequestPart.end(nil))) { error in + XCTAssert(error is FailAllWritesHandler.FailAllWritesError) + } + + // Upgrade didn't complete, so no user event. + XCTAssertTrue(userEventSaver.events.isEmpty) + // Nothing should have been forwarded. + XCTAssertTrue(dataRecorder.receivedData().isEmpty) + // The upgrade handler should still be in the pipeline. + try channel.pipeline.assertContainsUpgrader() + } + + func testFailedUpgraderThrowsError() throws { + let channel = EmbeddedChannel() + defer { + XCTAssertNoThrow(try? channel.finish()) + } + + struct ImAfraidICantDoThatDave: Error {} + + let upgrader = DelayedUnsuccessfulUpgrader(forProtocol: "myproto") + let encoder = HTTPResponseEncoder() + let handler = HTTPServerUpgradeHandler(upgraders: [upgrader], + httpEncoder: encoder, + extraHTTPHandlers: []) { (_: ChannelHandlerContext) in + // no-op. + () + } + + let userEventSaver = UserEventSaver() + let dataRecorder = DataRecorder() + + XCTAssertNoThrow(try channel.pipeline.addHandler(encoder).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(handler).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(userEventSaver).wait()) + XCTAssertNoThrow(try channel.pipeline.addHandler(dataRecorder).wait()) + + let head = HTTPServerRequestPart.head(.init(version: .http1_1, method: .GET, uri: "/foo", headers: ["upgrade": "myproto"])) + XCTAssertNoThrow(try channel.writeInbound(head)) + XCTAssertNoThrow(try channel.writeInbound(HTTPServerRequestPart.end(nil))) + + // Write another head, on a successful upgrade it will be unbuffered. + XCTAssertNoThrow(try channel.writeInbound(head)) + + // Unblock the upgrade. + upgrader.unblockUpgrade(withError: ImAfraidICantDoThatDave()) + + // Upgrade didn't complete, so no user event. + XCTAssertTrue(userEventSaver.events.isEmpty) + // Nothing should have been forwarded. + XCTAssertTrue(dataRecorder.receivedData().isEmpty) + // The upgrade handler should still be in the pipeline. + try channel.pipeline.assertContainsUpgrader() + } }