ClientTLSFailureTests.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. import EchoImplementation
  17. import EchoModel
  18. @testable import GRPC
  19. import GRPCSampleData
  20. import Logging
  21. import NIO
  22. import NIOConcurrencyHelpers
  23. import NIOSSL
  24. import XCTest
  25. class ErrorRecordingDelegate: ClientErrorDelegate {
  26. private let lock: Lock
  27. private var _errors: [Error] = []
  28. internal var errors: [Error] {
  29. return self.lock.withLock {
  30. return self._errors
  31. }
  32. }
  33. var expectation: XCTestExpectation
  34. init(expectation: XCTestExpectation) {
  35. self.expectation = expectation
  36. self.lock = Lock()
  37. }
  38. func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int) {
  39. self.lock.withLockVoid {
  40. self._errors.append(error)
  41. }
  42. self.expectation.fulfill()
  43. }
  44. }
  45. class ClientTLSFailureTests: GRPCTestCase {
  46. let defaultServerTLSConfiguration = GRPCTLSConfiguration.makeServerConfigurationBackedByNIOSSL(
  47. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  48. privateKey: .privateKey(SamplePrivateKey.server)
  49. )
  50. let defaultClientTLSConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  51. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  52. privateKey: .privateKey(SamplePrivateKey.client),
  53. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  54. hostnameOverride: SampleCertificate.server.commonName
  55. )
  56. var defaultTestTimeout: TimeInterval = 1.0
  57. var clientEventLoopGroup: EventLoopGroup!
  58. var serverEventLoopGroup: EventLoopGroup!
  59. var server: Server!
  60. var port: Int!
  61. func makeClientConfiguration(
  62. tls: GRPCTLSConfiguration
  63. ) -> ClientConnection.Configuration {
  64. var configuration = ClientConnection.Configuration.default(
  65. target: .hostAndPort("localhost", self.port),
  66. eventLoopGroup: self.clientEventLoopGroup
  67. )
  68. configuration.tlsConfiguration = tls
  69. // No need to retry connecting.
  70. configuration.connectionBackoff = nil
  71. configuration.backgroundActivityLogger = self.clientLogger
  72. return configuration
  73. }
  74. func makeClientConnectionExpectation() -> XCTestExpectation {
  75. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  76. }
  77. override func setUp() {
  78. super.setUp()
  79. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  80. self.server = try! Server.usingTLSBackedByNIOSSL(
  81. on: self.serverEventLoopGroup,
  82. certificateChain: [SampleCertificate.server.certificate],
  83. privateKey: SamplePrivateKey.server
  84. ).withServiceProviders([EchoProvider()])
  85. .withLogger(self.serverLogger)
  86. .bind(host: "localhost", port: 0)
  87. .wait()
  88. self.port = self.server.channel.localAddress?.port
  89. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  90. // Delay the client connection creation until the test.
  91. }
  92. override func tearDown() {
  93. self.port = nil
  94. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  95. self.clientEventLoopGroup = nil
  96. XCTAssertNoThrow(try self.server.close().wait())
  97. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  98. self.server = nil
  99. self.serverEventLoopGroup = nil
  100. super.tearDown()
  101. }
  102. func testClientConnectionFailsWhenServerIsUnknown() throws {
  103. let errorExpectation = self.expectation(description: "error")
  104. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  105. // (because the handshake failed).
  106. errorExpectation.expectedFulfillmentCount = 2
  107. var tls = self.defaultClientTLSConfiguration
  108. tls.updateNIOTrustRoots(to: .certificates([]))
  109. var configuration = self.makeClientConfiguration(tls: tls)
  110. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  111. configuration.errorDelegate = errorRecorder
  112. let stateChangeDelegate = RecordingConnectivityDelegate()
  113. stateChangeDelegate.expectChanges(2) { changes in
  114. XCTAssertEqual(changes, [
  115. Change(from: .idle, to: .connecting),
  116. Change(from: .connecting, to: .shutdown),
  117. ])
  118. }
  119. configuration.connectivityStateDelegate = stateChangeDelegate
  120. // Start an RPC to trigger creating a channel.
  121. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  122. _ = echo.get(.with { $0.text = "foo" })
  123. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  124. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  125. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  126. case .handshakeFailed(.sslError) = nioSSLError {
  127. // Expected case.
  128. } else {
  129. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  130. }
  131. }
  132. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  133. let errorExpectation = self.expectation(description: "error")
  134. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  135. // (because the handshake failed).
  136. errorExpectation.expectedFulfillmentCount = 2
  137. var tls = self.defaultClientTLSConfiguration
  138. tls.hostnameOverride = "not-the-server-hostname"
  139. var configuration = self.makeClientConfiguration(tls: tls)
  140. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  141. configuration.errorDelegate = errorRecorder
  142. let stateChangeDelegate = RecordingConnectivityDelegate()
  143. stateChangeDelegate.expectChanges(2) { changes in
  144. XCTAssertEqual(changes, [
  145. Change(from: .idle, to: .connecting),
  146. Change(from: .connecting, to: .shutdown),
  147. ])
  148. }
  149. configuration.connectivityStateDelegate = stateChangeDelegate
  150. // Start an RPC to trigger creating a channel.
  151. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  152. _ = echo.get(.with { $0.text = "foo" })
  153. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  154. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  155. if let nioSSLError = errorRecorder.errors.first as? NIOSSLExtraError {
  156. XCTAssertEqual(nioSSLError, .failedToValidateHostname)
  157. // Expected case.
  158. } else {
  159. XCTFail("Expected NIOSSLExtraError.failedToValidateHostname")
  160. }
  161. }
  162. func testClientConnectionFailsWhenCertificateValidationDenied() throws {
  163. let errorExpectation = self.expectation(description: "error")
  164. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  165. // (because the handshake failed).
  166. errorExpectation.expectedFulfillmentCount = 2
  167. let tlsConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  168. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  169. privateKey: .privateKey(SamplePrivateKey.client),
  170. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  171. hostnameOverride: SampleCertificate.server.commonName,
  172. customVerificationCallback: { _, promise in
  173. // The certificate validation is forced to fail
  174. promise.fail(NIOSSLError.unableToValidateCertificate)
  175. }
  176. )
  177. var configuration = self.makeClientConfiguration(tls: tlsConfiguration)
  178. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  179. configuration.errorDelegate = errorRecorder
  180. let stateChangeDelegate = RecordingConnectivityDelegate()
  181. stateChangeDelegate.expectChanges(2) { changes in
  182. XCTAssertEqual(changes, [
  183. Change(from: .idle, to: .connecting),
  184. Change(from: .connecting, to: .shutdown),
  185. ])
  186. }
  187. configuration.connectivityStateDelegate = stateChangeDelegate
  188. // Start an RPC to trigger creating a channel.
  189. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  190. _ = echo.get(.with { $0.text = "foo" })
  191. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  192. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  193. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  194. case .handshakeFailed(.sslError) = nioSSLError {
  195. // Expected case.
  196. } else {
  197. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  198. }
  199. }
  200. }