ClientTLSFailureTests.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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 shutdownExpectation = self.expectation(description: "client shutdown")
  87. let errorExpectation = self.expectation(description: "error")
  88. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  89. // (because the handshake failed).
  90. errorExpectation.expectedFulfillmentCount = 2
  91. var tls = self.defaultClientTLSConfiguration
  92. tls.trustRoots = .certificates([])
  93. var configuration = self.makeClientConfiguration(tls: tls)
  94. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  95. configuration.errorDelegate = errorRecorder
  96. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  97. configuration.connectivityStateDelegate = stateChangeDelegate
  98. // Start an RPC to trigger creating a channel.
  99. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  100. _ = echo.get(.with { $0.text = "foo" })
  101. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  102. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  103. case .handshakeFailed(.sslError) = nioSSLError {
  104. // Expected case.
  105. } else {
  106. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  107. }
  108. }
  109. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  110. let shutdownExpectation = self.expectation(description: "client shutdown")
  111. let errorExpectation = self.expectation(description: "error")
  112. // 2 errors: one for the failed handshake, and another for failing the ready-channel promise
  113. // (because the handshake failed).
  114. errorExpectation.expectedFulfillmentCount = 2
  115. var tls = self.defaultClientTLSConfiguration
  116. tls.hostnameOverride = "not-the-server-hostname"
  117. var configuration = self.makeClientConfiguration(tls: tls)
  118. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  119. configuration.errorDelegate = errorRecorder
  120. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  121. configuration.connectivityStateDelegate = stateChangeDelegate
  122. // Start an RPC to trigger creating a channel.
  123. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  124. _ = echo.get(.with { $0.text = "foo" })
  125. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  126. if let nioSSLError = errorRecorder.errors.first as? NIOSSLExtraError {
  127. XCTAssertEqual(nioSSLError, .failedToValidateHostname)
  128. // Expected case.
  129. } else {
  130. XCTFail("Expected NIOSSLExtraError.failedToValidateHostname")
  131. }
  132. }
  133. }