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.
This commit is contained in:
George Barnett authored and GitHub committed 2022-10-28 07:32:43 -07:00
1 parent 1abe64c5e6
commit 73eb597aa3
3 files changed
+176 -23

No files matched your search

+17 -21
View File
@@ -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<Void> 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<Void, Error>) 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<Void> {
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<Void> {
guard self.extraHTTPHandlers.count > 0 else {
@@ -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),
]
}
}
@@ -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<Void>?
init(forProtocol `protocol`: String) {
self.supportedProtocol = `protocol`
self.requiredUpgradeHeaders = []
}
func buildUpgradeResponse(channel: Channel,
upgradeRequest: HTTPRequestHead,
initialResponseHeaders: HTTPHeaders) -> EventLoopFuture<HTTPHeaders> {
return channel.eventLoop.makeSucceededFuture([:])
}
func upgrade(context: ChannelHandlerContext, upgradeRequest: HTTPRequestHead) -> EventLoopFuture<Void> {
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<HTTPServerUpgradeEvents>()
let dataRecorder = DataRecorder<HTTPServerRequestPart>()
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<Void>?) {
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<HTTPServerUpgradeEvents>()
let dataRecorder = DataRecorder<HTTPServerRequestPart>()
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<HTTPServerUpgradeEvents>()
let dataRecorder = DataRecorder<HTTPServerRequestPart>()
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()
}
}