From 8efedf33fa80ecb48982d9869ad5006073b4198c Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 1 Nov 2017 16:14:11 +0000 Subject: [PATCH] Add ALPN handler --- Sources/NIOOpenSSL/OpenSSLHandler.swift | 2 +- ...pplicationProtocolNegotiationHandler.swift | 98 +++++++++ Sources/NIOTLS/TLSEvents.swift | 13 +- Tests/LinuxMain.swift | 1 + .../OpenSSLIntegrationTest.swift | 6 +- ...otocolNegotiationHandlerTests+XCTest.swift | 39 ++++ ...ationProtocolNegotiationHandlerTests.swift | 193 ++++++++++++++++++ Tests/NIOTLSTests/SNIHandlerTests.swift | 2 +- 8 files changed, 348 insertions(+), 6 deletions(-) create mode 100644 Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift create mode 100644 Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests+XCTest.swift create mode 100644 Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift diff --git a/Sources/NIOOpenSSL/OpenSSLHandler.swift b/Sources/NIOOpenSSL/OpenSSLHandler.swift index 0512ee7b1..a96a763ef 100644 --- a/Sources/NIOOpenSSL/OpenSSLHandler.swift +++ b/Sources/NIOOpenSSL/OpenSSLHandler.swift @@ -164,7 +164,7 @@ public class OpenSSLHandler : ChannelInboundHandler, ChannelOutboundHandler { writeDataToNetwork(ctx: ctx, promise: nil) // TODO(cory): This event should probably fire out of the OpenSSL info callback. - ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted)) + ctx.fireUserInboundEventTriggered(event: wrapInboundUserEventOut(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil))) // We need to unbuffer any pending writes. We will have pending writes if the user attempted to write // before we completed the handshake. diff --git a/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift new file mode 100644 index 000000000..98915ef9c --- /dev/null +++ b/Sources/NIOTLS/ApplicationProtocolNegotiationHandler.swift @@ -0,0 +1,98 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 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 NIO + +public enum ALPNResult: Equatable { + case negotiated(String) + case fallback + + public static func ==(lhs: ALPNResult, rhs: ALPNResult) -> Bool { + switch (lhs, rhs) { + case (.negotiated(let p1), .negotiated(let p2)): + return p1 == p2 + case (.fallback, .fallback): + return true + default: + return false + } + } +} + +public class ApplicationProtocolNegotiationHandler: ChannelInboundHandler { + public typealias InboundIn = Any + public typealias InboundOut = Any + public typealias InboundUserEventIn = TLSUserEvent + + private let completionHandler: (ALPNResult) -> Future + private var waitingForUser: Bool + private var eventBuffer: [NIOAny] + + public init(alpnCompleteHandler: @escaping (ALPNResult) -> Future) { + self.completionHandler = alpnCompleteHandler + self.waitingForUser = false + self.eventBuffer = [] + } + + public func userInboundEventTriggered(ctx: ChannelHandlerContext, event: Any) { + guard let tlsEvent = tryUnwrapInboundUserEventIn(event) else { + ctx.fireUserInboundEventTriggered(event: event) + return + } + + switch tlsEvent { + case .handshakeCompleted(let p): + handshakeCompleted(context: ctx, negotiatedProtocol: p) + default: + ctx.fireUserInboundEventTriggered(event: event) + } + } + + public func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { + if waitingForUser { + eventBuffer.append(data) + } else { + ctx.fireChannelRead(data: data) + } + } + + private func handshakeCompleted(context: ChannelHandlerContext, negotiatedProtocol: String?) { + waitingForUser = true + + let result: ALPNResult + if let negotiatedProtocol = negotiatedProtocol { + result = .negotiated(negotiatedProtocol) + } else { + result = .fallback + } + + let switchFuture = completionHandler(result) + switchFuture.whenComplete { _ in + self.unbuffer(context: context) + _ = context.pipeline?.remove(handler: self) + } + } + + private func unbuffer(context: ChannelHandlerContext) { + for datum in eventBuffer { + context.fireChannelRead(data: datum) + } + let buffer = eventBuffer + eventBuffer = [] + waitingForUser = false + if buffer.count > 0 { + context.fireChannelReadComplete() + } + } +} diff --git a/Sources/NIOTLS/TLSEvents.swift b/Sources/NIOTLS/TLSEvents.swift index 74f212f3b..9fe0a7b13 100644 --- a/Sources/NIOTLS/TLSEvents.swift +++ b/Sources/NIOTLS/TLSEvents.swift @@ -14,6 +14,17 @@ /// Common user events sent by all TLS implementations. public enum TLSUserEvent: Equatable { - case handshakeCompleted + case handshakeCompleted(negotiatedProtocol: String?) case shutdownCompleted + + public static func ==(lhs: TLSUserEvent, rhs: TLSUserEvent) -> Bool { + switch (lhs, rhs) { + case (.handshakeCompleted(let p1), .handshakeCompleted(let p2)): + return p1 == p2 + case (.shutdownCompleted, .shutdownCompleted): + return true + default: + return false + } + } } diff --git a/Tests/LinuxMain.swift b/Tests/LinuxMain.swift index 9e0a01579..4ed28bd0a 100644 --- a/Tests/LinuxMain.swift +++ b/Tests/LinuxMain.swift @@ -30,6 +30,7 @@ import XCTest XCTMain([ testCase(AdaptiveRecvByteBufferAllocatorTest.allTests), + testCase(ApplicationProtocolNegotiationHandlerTests.allTests), testCase(BaseObjectTest.allTests), testCase(ByteBufferTest.allTests), testCase(ByteToMessageDecoderTest.allTests), diff --git a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift index be060a672..eb483cf5a 100644 --- a/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift +++ b/Tests/NIOOpenSSLTests/OpenSSLIntegrationTest.swift @@ -295,7 +295,7 @@ class OpenSSLIntegrationTest: XCTestCase { let expectedEvents: [EventRecorderHandler.RecordedEvents] = [ .Registered, .Active, - .UserEvent(TLSUserEvent.handshakeCompleted), + .UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)), .Read, .ReadComplete ] @@ -337,7 +337,7 @@ class OpenSSLIntegrationTest: XCTestCase { let expectedEvents: [EventRecorderHandler.RecordedEvents] = [ .Registered, .Active, - .UserEvent(TLSUserEvent.handshakeCompleted), + .UserEvent(TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)), .Read, .ReadComplete, .UserEvent(TLSUserEvent.shutdownCompleted), @@ -565,7 +565,7 @@ class OpenSSLIntegrationTest: XCTestCase { // At this point the handshake should be complete. try group.next().submit { - XCTAssertEqual(recorderHandler.events[..<3], [.Registered, .Active, .UserEvent(.handshakeCompleted)]) + XCTAssertEqual(recorderHandler.events[..<3], [.Registered, .Active, .UserEvent(.handshakeCompleted(negotiatedProtocol: nil))]) }.wait() } } diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests+XCTest.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests+XCTest.swift new file mode 100644 index 000000000..5a14fa021 --- /dev/null +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests+XCTest.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 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 +// +//===----------------------------------------------------------------------===// +/// +/// ApplicationProtocolNegotiationHandlerTests+XCTest.swift +/// +import XCTest + +/// +/// NOTE: This file was generated by generate_linux_tests.rb +/// +/// Do NOT edit this file directly as it will be regenerated automatically when needed. +/// + +extension ApplicationProtocolNegotiationHandlerTests { + + static var allTests : [(String, (ApplicationProtocolNegotiationHandlerTests) -> () throws -> Void)] { + return [ + ("testIgnoresUnknownUserEvents", testIgnoresUnknownUserEvents), + ("testCallbackReflectsNotificationResult", testCallbackReflectsNotificationResult), + ("testCallbackNotesFallbackForNoNegotiation", testCallbackNotesFallbackForNoNegotiation), + ("testNoBufferingBeforeEventFires", testNoBufferingBeforeEventFires), + ("testBufferingWhileWaitingForFuture", testBufferingWhileWaitingForFuture), + ("testNothingBufferedDoesNotFireReadCompleted", testNothingBufferedDoesNotFireReadCompleted), + ("testUnbufferingFiresReadCompleted", testUnbufferingFiresReadCompleted), + ] + } +} + diff --git a/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift new file mode 100644 index 000000000..64ccc9efb --- /dev/null +++ b/Tests/NIOTLSTests/ApplicationProtocolNegotiationHandlerTests.swift @@ -0,0 +1,193 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2017-2018 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 XCTest +@testable import NIO +import NIOTLS + +private class ReadCompletedHandler: ChannelInboundHandler { + public typealias InboundIn = Any + public var readCompleteCount: Int + + init() { + readCompleteCount = 0 + } + + public func channelReadComplete(ctx: ChannelHandlerContext) { + readCompleteCount += 1 + } +} + +class ApplicationProtocolNegotiationHandlerTests: XCTestCase { + private enum EventType { + case basic + } + + func testIgnoresUnknownUserEvents() throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + + let handler = ApplicationProtocolNegotiationHandler { result in + XCTFail("Negotiation fired") + return loop.newSucceedFuture(result: ()) + } + + try channel.pipeline.add(handler: handler).wait() + + // Fire a pair of events that should be ignored. + channel.pipeline.fireUserInboundEventTriggered(event: EventType.basic) + channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.shutdownCompleted) + + // The channel handler should still be in the pipeline. + try channel.pipeline.assertContains(handler: handler) + } + + private func negotiateTest(event: TLSUserEvent, expectedResult: ALPNResult) throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let expectedResult: ALPNResult = .negotiated("h2") + var called = false + + let handler = ApplicationProtocolNegotiationHandler { result in + XCTAssertEqual(expectedResult, result) + called = true + return continuePromise.futureResult + } + + try channel.pipeline.add(handler: handler).wait() + + // Fire the handshake complete event. + channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + + // At this time the callback should have fired, but the handler should still be in + // the pipeline. + XCTAssertTrue(called) + try channel.pipeline.assertContains(handler: handler) + + // Now we fire the future. + continuePromise.succeed(result: ()) + + // Now the handler should have removed itself from the pipeline. + try channel.pipeline.assertDoesNotContain(handler: handler) + } + + func testCallbackReflectsNotificationResult() throws { + try negotiateTest(event: .handshakeCompleted(negotiatedProtocol: "h2"), expectedResult: .negotiated("h2")) + } + + func testCallbackNotesFallbackForNoNegotiation() throws { + try negotiateTest(event: .handshakeCompleted(negotiatedProtocol: ""), expectedResult: .fallback) + } + + func testNoBufferingBeforeEventFires() throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + + let handler = ApplicationProtocolNegotiationHandler { result in + XCTFail("Should not be called") + return loop.newSucceedFuture(result: ()) + } + + try channel.pipeline.add(handler: handler).wait() + + // The data we write should not be buffered. + try channel.writeInbound(data: "hello") + XCTAssertEqual(channel.readInbound()!, "hello") + } + + func testBufferingWhileWaitingForFuture() throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let handler = ApplicationProtocolNegotiationHandler { result in + return continuePromise.futureResult + } + + try channel.pipeline.add(handler: handler).wait() + + // Fire in the event. + channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + + // At this point all writes should be buffered. + try channel.writeInbound(data: "writes") + try channel.writeInbound(data: "are") + try channel.writeInbound(data: "buffered") + XCTAssertNil(channel.readInbound()) + + // Complete the pipeline swap. + continuePromise.succeed(result: ()) + + // Now everything should have been unbuffered. + XCTAssertEqual(channel.readInbound()!, "writes") + XCTAssertEqual(channel.readInbound()!, "are") + XCTAssertEqual(channel.readInbound()!, "buffered") + } + + func testNothingBufferedDoesNotFireReadCompleted() throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let handler = ApplicationProtocolNegotiationHandler { result in + return continuePromise.futureResult + } + let readCompleteHandler = ReadCompletedHandler() + + try channel.pipeline.add(handler: handler).wait() + try channel.pipeline.add(handler: readCompleteHandler).wait() + + // Fire in the event. + channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + + // At this time, readComplete hasn't fired. + XCTAssertEqual(readCompleteHandler.readCompleteCount, 0) + + // Now satisfy the future, which forces data unbuffering. As we haven't buffered any data, + // readComplete should not be fired. + continuePromise.succeed(result: ()) + XCTAssertEqual(readCompleteHandler.readCompleteCount, 0) + } + + func testUnbufferingFiresReadCompleted() throws { + let channel = EmbeddedChannel() + let loop = channel.eventLoop as! EmbeddedEventLoop + let continuePromise: Promise = loop.newPromise() + + let handler = ApplicationProtocolNegotiationHandler { result in + return continuePromise.futureResult + } + let readCompleteHandler = ReadCompletedHandler() + + try channel.pipeline.add(handler: handler).wait() + try channel.pipeline.add(handler: readCompleteHandler).wait() + + // Fire in the event. + channel.pipeline.fireUserInboundEventTriggered(event: TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")) + + // Send a write, which is buffered. + try channel.writeInbound(data: "a write") + + // At this time, readComplete hasn't fired. + XCTAssertEqual(readCompleteHandler.readCompleteCount, 1) + + // Now satisfy the future, which forces data unbuffering. This should fire readComplete. + continuePromise.succeed(result: ()) + XCTAssertEqual(channel.readInbound()!, "a write") + + XCTAssertEqual(readCompleteHandler.readCompleteCount, 2) + } +} diff --git a/Tests/NIOTLSTests/SNIHandlerTests.swift b/Tests/NIOTLSTests/SNIHandlerTests.swift index 0dd2cdfda..c66656912 100644 --- a/Tests/NIOTLSTests/SNIHandlerTests.swift +++ b/Tests/NIOTLSTests/SNIHandlerTests.swift @@ -228,7 +228,7 @@ q6U/lEvy1/7zGQ== private let ludicrouslyTruncatedPacket = "FgMBAAEB" -private extension ChannelPipeline { +internal extension ChannelPipeline { func contains(handler: ChannelHandler) throws -> Bool { do { let _ = try self.context(handler: handler).wait()