ClientTLSFailureTests.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. )
  59. }
  60. func makeClientConnectionExpectation() -> XCTestExpectation {
  61. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  62. }
  63. override func setUp() {
  64. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  65. self.server = try! Server.secure(
  66. group: self.serverEventLoopGroup,
  67. certificateChain: [SampleCertificate.server.certificate],
  68. privateKey: SamplePrivateKey.server
  69. ).withServiceProviders([EchoProvider()])
  70. .bind(host: "localhost", port: 0)
  71. .wait()
  72. self.port = self.server.channel.localAddress?.port
  73. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  74. // Delay the client connection creation until the test.
  75. }
  76. override func tearDown() {
  77. self.port = nil
  78. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  79. self.clientEventLoopGroup = nil
  80. XCTAssertNoThrow(try self.server.close().wait())
  81. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  82. self.server = nil
  83. self.serverEventLoopGroup = nil
  84. }
  85. func testClientConnectionFailsWhenServerIsUnknown() throws {
  86. let errorExpectation = self.expectation(description: "error")
  87. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  88. // (because the handshake failed).
  89. errorExpectation.expectedFulfillmentCount = 2
  90. var tls = self.defaultClientTLSConfiguration
  91. tls.trustRoots = .certificates([])
  92. var configuration = self.makeClientConfiguration(tls: tls)
  93. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  94. configuration.errorDelegate = errorRecorder
  95. let stateChangeDelegate = RecordingConnectivityDelegate()
  96. stateChangeDelegate.expectChanges(2) { changes in
  97. XCTAssertEqual(changes, [
  98. Change(from: .idle, to: .connecting),
  99. Change(from: .connecting, to: .shutdown)
  100. ])
  101. }
  102. configuration.connectivityStateDelegate = stateChangeDelegate
  103. // Start an RPC to trigger creating a channel.
  104. let echo = Echo_EchoClient(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. // Expected case.
  111. } else {
  112. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  113. }
  114. }
  115. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  116. let errorExpectation = self.expectation(description: "error")
  117. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  118. // (because the handshake failed).
  119. errorExpectation.expectedFulfillmentCount = 2
  120. var tls = self.defaultClientTLSConfiguration
  121. tls.hostnameOverride = "not-the-server-hostname"
  122. var configuration = self.makeClientConfiguration(tls: tls)
  123. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  124. configuration.errorDelegate = errorRecorder
  125. let stateChangeDelegate = RecordingConnectivityDelegate()
  126. stateChangeDelegate.expectChanges(2) { changes in
  127. XCTAssertEqual(changes, [
  128. Change(from: .idle, to: .connecting),
  129. Change(from: .connecting, to: .shutdown)
  130. ])
  131. }
  132. configuration.connectivityStateDelegate = stateChangeDelegate
  133. // Start an RPC to trigger creating a channel.
  134. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  135. _ = echo.get(.with { $0.text = "foo" })
  136. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  137. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(5))
  138. if let nioSSLError = errorRecorder.errors.first as? NIOSSLExtraError {
  139. XCTAssertEqual(nioSSLError, .failedToValidateHostname)
  140. // Expected case.
  141. } else {
  142. XCTFail("Expected NIOSSLExtraError.failedToValidateHostname")
  143. }
  144. }
  145. }