2
0

ClientTLSFailureTests.swift 8.2 KB

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