ClientTLSFailureTests.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. /*
  2. * Copyright 2019, gRPC Authors All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. @testable import GRPC
  17. import GRPCSampleData
  18. import EchoModel
  19. import EchoImplementation
  20. import Logging
  21. import NIO
  22. import NIOSSL
  23. import XCTest
  24. class ErrorRecordingDelegate: ClientErrorDelegate {
  25. var errors: [Error] = []
  26. var expectation: XCTestExpectation
  27. init(expectation: XCTestExpectation) {
  28. self.expectation = expectation
  29. }
  30. func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int) {
  31. self.errors.append(error)
  32. self.expectation.fulfill()
  33. }
  34. }
  35. class ClientTLSFailureTests: GRPCTestCase {
  36. let defaultServerTLSConfiguration = Server.Configuration.TLS(
  37. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  38. privateKey: .privateKey(SamplePrivateKey.server))
  39. let defaultClientTLSConfiguration = ClientConnection.Configuration.TLS(
  40. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  41. privateKey: .privateKey(SamplePrivateKey.client),
  42. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  43. hostnameOverride: SampleCertificate.server.commonName)
  44. var defaultTestTimeout: TimeInterval = 1.0
  45. var clientEventLoopGroup: EventLoopGroup!
  46. var serverEventLoopGroup: EventLoopGroup!
  47. var server: Server!
  48. var port: Int!
  49. func makeClientConfiguration(
  50. tls: ClientConnection.Configuration.TLS
  51. ) -> ClientConnection.Configuration {
  52. return .init(
  53. target: .hostAndPort("localhost", self.port),
  54. eventLoopGroup: self.clientEventLoopGroup,
  55. tls: tls,
  56. // No need to retry connecting.
  57. connectionBackoff: nil,
  58. backgroundActivityLogger: self.clientLogger
  59. )
  60. }
  61. func makeClientConnectionExpectation() -> XCTestExpectation {
  62. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  63. }
  64. override func setUp() {
  65. super.setUp()
  66. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  67. self.server = try! Server.secure(
  68. group: self.serverEventLoopGroup,
  69. certificateChain: [SampleCertificate.server.certificate],
  70. privateKey: SamplePrivateKey.server
  71. ).withServiceProviders([EchoProvider()])
  72. .withLogger(self.serverLogger)
  73. .bind(host: "localhost", port: 0)
  74. .wait()
  75. self.port = self.server.channel.localAddress?.port
  76. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  77. // Delay the client connection creation until the test.
  78. }
  79. override func tearDown() {
  80. self.port = nil
  81. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  82. self.clientEventLoopGroup = nil
  83. XCTAssertNoThrow(try self.server.close().wait())
  84. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  85. self.server = nil
  86. self.serverEventLoopGroup = nil
  87. super.tearDown()
  88. }
  89. func testClientConnectionFailsWhenServerIsUnknown() throws {
  90. let errorExpectation = self.expectation(description: "error")
  91. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  92. // (because the handshake failed).
  93. errorExpectation.expectedFulfillmentCount = 2
  94. var tls = self.defaultClientTLSConfiguration
  95. tls.trustRoots = .certificates([])
  96. var configuration = self.makeClientConfiguration(tls: tls)
  97. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  98. configuration.errorDelegate = errorRecorder
  99. let stateChangeDelegate = RecordingConnectivityDelegate()
  100. stateChangeDelegate.expectChanges(2) { changes in
  101. XCTAssertEqual(changes, [
  102. Change(from: .idle, to: .connecting),
  103. Change(from: .connecting, to: .shutdown)
  104. ])
  105. }
  106. configuration.connectivityStateDelegate = stateChangeDelegate
  107. // Start an RPC to trigger creating a channel.
  108. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  109. _ = echo.get(.with { $0.text = "foo" })
  110. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  111. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  112. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  113. case .handshakeFailed(.sslError) = nioSSLError {
  114. // Expected case.
  115. } else {
  116. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  117. }
  118. }
  119. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  120. let errorExpectation = self.expectation(description: "error")
  121. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  122. // (because the handshake failed).
  123. errorExpectation.expectedFulfillmentCount = 2
  124. var tls = self.defaultClientTLSConfiguration
  125. tls.hostnameOverride = "not-the-server-hostname"
  126. var configuration = self.makeClientConfiguration(tls: tls)
  127. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  128. configuration.errorDelegate = errorRecorder
  129. let stateChangeDelegate = RecordingConnectivityDelegate()
  130. stateChangeDelegate.expectChanges(2) { changes in
  131. XCTAssertEqual(changes, [
  132. Change(from: .idle, to: .connecting),
  133. Change(from: .connecting, to: .shutdown)
  134. ])
  135. }
  136. configuration.connectivityStateDelegate = stateChangeDelegate
  137. // Start an RPC to trigger creating a channel.
  138. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  139. _ = echo.get(.with { $0.text = "foo" })
  140. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  141. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  142. if let nioSSLError = errorRecorder.errors.first as? NIOSSLExtraError {
  143. XCTAssertEqual(nioSSLError, .failedToValidateHostname)
  144. // Expected case.
  145. } else {
  146. XCTFail("Expected NIOSSLExtraError.failedToValidateHostname")
  147. }
  148. }
  149. }