From 32101fe2f32712bb1c01bd312ed191ab669c176e Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 5 May 2022 10:51:41 +0200 Subject: [PATCH] Flush only after handshake (#362) * support additional certificate validation * run `scripts/generate_linux_tests.rb` * fix review comments - rename `CertificateChainVerificationCallback` to `AdditionalCertificateChainVerificationCallback` - switch over `result` instead of try/catch - add `. eofDuringAdditionalCertficiateChainValidation` error and throw it if channel becomes inactive while in `.additionalVerification` state * add `Channel` parameter to `AdditionalCertificateChainVerificationCallback` * get `context` from self instead of captering it * save progress * Only flush after handshake * run `./scripts/generate_linux_tests.rb` ` * Add NIOSSLCertficiateExtensions * adopt naming of ObjectIdentifier * address review comments - namespace top level types with `NIO` - add `withUnsafeBytes(_:)` that gives access to the buffer through an untyped buffer pointer - fix indentation * use real optional for `reference` in `_NIOSSLCertificateExtensions` * fix review comments part 2 - nest `_Extensions` and `_Extension` under `NIOSSLCertificate` - explain optional reference - remove empty and copy constructor - replace fancy force-unwraps with `!` * use channel from argument * fix review comments - buffer the flush instead of ignoring it - do not automatically flush after a succesfull handshake --- Sources/NIOSSL/NIOSSLHandler.swift | 10 +++- .../NIOSSLIntegrationTest+XCTest.swift | 1 + Tests/NIOSSLTests/NIOSSLIntegrationTest.swift | 59 +++++++++++++++++++ 3 files changed, 68 insertions(+), 2 deletions(-) diff --git a/Sources/NIOSSL/NIOSSLHandler.swift b/Sources/NIOSSL/NIOSSLHandler.swift index 9a8b02b3..d6fb9769 100644 --- a/Sources/NIOSSL/NIOSSLHandler.swift +++ b/Sources/NIOSSL/NIOSSLHandler.swift @@ -179,8 +179,14 @@ public class NIOSSLHandler : ChannelInboundHandler, ChannelOutboundHandler, Remo } public func flush(context: ChannelHandlerContext) { - bufferFlush() - doUnbufferWrites(context: context) + switch self.state { + case .idle, .handshaking, .additionalVerification: + // we should not flush immediately as we have not completed the handshake and instead buffer the flush + self.bufferFlush() + case .active, .unwrapping, .closing, .unwrapped, .closed: + self.bufferFlush() + self.doUnbufferWrites(context: context) + } } public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise?) { diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift index 83746515..fb07480f 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest+XCTest.swift @@ -39,6 +39,7 @@ extension NIOSSLIntegrationTest { ("testValidatesHostnameOnConnectionSucceeds", testValidatesHostnameOnConnectionSucceeds), ("testAdditionalValidationOnConnectionSucceeds", testAdditionalValidationOnConnectionSucceeds), ("testAdditionalValidationOnConnectionFails", testAdditionalValidationOnConnectionFails), + ("testFlushWhileAdditionalValidationIsInProgressDoesNotActuallyFlush", testFlushWhileAdditionalValidationIsInProgressDoesNotActuallyFlush), ("testDontLoseClosePromises", testDontLoseClosePromises), ("testTrustStoreOnDisk", testTrustStoreOnDisk), ("testChecksTrustStoreOnDisk", testChecksTrustStoreOnDisk), diff --git a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift index 9d5c2212..9c78cb0a 100644 --- a/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift +++ b/Tests/NIOSSLTests/NIOSSLIntegrationTest.swift @@ -402,6 +402,29 @@ fileprivate func _clientTLSChannel(context: NIOSSLCon .wait(), file: file, line: line) } +struct EventLoopFutureTimeoutError: Error {} + +extension EventLoopFuture { + func timeout(after failDelay: TimeAmount) -> EventLoopFuture { + let promise = self.eventLoop.makePromise(of: Value.self) + + self.whenComplete { result in + switch result { + case .success(let value): + promise.succeed(value) + case .failure(let error): + promise.fail(error) + } + } + + self.eventLoop.scheduleTask(in: failDelay) { + promise.fail(EventLoopFutureTimeoutError()) + } + + return promise.futureResult + } +} + class NIOSSLIntegrationTest: XCTestCase { static var cert: NIOSSLCertificate! static var key: NIOSSLPrivateKey! @@ -991,6 +1014,42 @@ class NIOSSLIntegrationTest: XCTestCase { XCTAssertEqual(actualErrors.count, 1) XCTAssertTrue(actualErrors.first is CustomUserError) } + + func testFlushWhileAdditionalValidationIsInProgressDoesNotActuallyFlush() throws { + let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) + defer { + XCTAssertNoThrow(try group.syncShutdownGracefully()) + } + + let additionalHandshakePromise = group.next().makePromise(of: Void.self) + let serverCtx = try configuredSSLContext() + let clientCtx = try configuredClientContext(additionalCertificateChainVerification: { channel in + channel.flush() + return additionalHandshakePromise.futureResult + }) + + let serverChannel = try serverTLSChannel(context: serverCtx, + handlers: [], + group: group) + defer { + XCTAssertNoThrow(try serverChannel.close().wait()) + } + + let eventHandler = EventRecorderHandler() + let clientChannel = try clientTLSChannel(context: clientCtx, + preHandlers: [], + postHandlers: [eventHandler], + group: group, + connectingTo: serverChannel.localAddress!, + serverHostname: "localhost") + let writeFuture = clientChannel.writeAndFlush(ByteBuffer(string: "Hello")) + XCTAssertThrowsError(try writeFuture.timeout(after: .milliseconds(100)).wait()) + additionalHandshakePromise.succeed(()) + writeFuture.whenComplete { _ in + XCTAssertEqual(eventHandler.events[..<3], [.Registered, .Active, .UserEvent(.handshakeCompleted(negotiatedProtocol: nil))]) + } + try writeFuture.wait() + } func testDontLoseClosePromises() throws { let serverChannel = EmbeddedChannel()