ClientTLSFailureTests.swift 8.2 KB

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