ClientTLSFailureTests.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 Foundation
  17. import GRPC
  18. import GRPCSampleData
  19. import EchoImplementation
  20. import NIO
  21. import NIOSSL
  22. import XCTest
  23. class ErrorRecordingDelegate: ClientErrorDelegate {
  24. var errors: [Error] = []
  25. var expectation: XCTestExpectation
  26. init(expectation: XCTestExpectation) {
  27. self.expectation = expectation
  28. }
  29. func didCatchError(_ error: Error, file: StaticString, line: Int) {
  30. self.errors.append(error)
  31. self.expectation.fulfill()
  32. }
  33. }
  34. class ClientTLSFailureTests: GRPCTestCase {
  35. let defaultServerTLSConfiguration = Server.Configuration.TLS(
  36. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  37. privateKey: .privateKey(SamplePrivateKey.server))
  38. let defaultClientTLSConfiguration = ClientConnection.Configuration.TLS(
  39. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  40. privateKey: .privateKey(SamplePrivateKey.client),
  41. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  42. hostnameOverride: SampleCertificate.server.commonName)
  43. var defaultTestTimeout: TimeInterval = 1.0
  44. var clientEventLoopGroup: EventLoopGroup!
  45. var serverEventLoopGroup: EventLoopGroup!
  46. var server: Server!
  47. var port: Int!
  48. func makeClientConfiguration(
  49. tls: ClientConnection.Configuration.TLS
  50. ) -> ClientConnection.Configuration {
  51. return .init(
  52. target: .hostAndPort("localhost", self.port),
  53. eventLoopGroup: self.clientEventLoopGroup,
  54. tls: tls,
  55. // No need to retry connecting.
  56. connectionBackoff: nil
  57. )
  58. }
  59. func makeClientConnectionExpectation() -> XCTestExpectation {
  60. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  61. }
  62. override func setUp() {
  63. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  64. let configuration = Server.Configuration(
  65. target: .hostAndPort("localhost", 0),
  66. eventLoopGroup: self.serverEventLoopGroup,
  67. serviceProviders: [EchoProvider()],
  68. errorDelegate: nil,
  69. tls: self.defaultServerTLSConfiguration)
  70. self.server = try! Server.start(configuration: configuration).wait()
  71. self.port = self.server.channel.localAddress?.port
  72. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  73. // Delay the client connection creation until the test.
  74. }
  75. override func tearDown() {
  76. self.port = nil
  77. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  78. self.clientEventLoopGroup = nil
  79. XCTAssertNoThrow(try self.server.close().wait())
  80. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  81. self.server = nil
  82. self.serverEventLoopGroup = nil
  83. }
  84. func testClientConnectionFailsWhenProtocolCanNotBeNegotiated() throws {
  85. let shutdownExpectation = self.expectation(description: "client shutdown")
  86. let errorExpectation = self.expectation(description: "error")
  87. // We use the underlying configuration because `applicationProtocols` is not user-configurable
  88. // via `Configuration.TLS`.
  89. var tlsConfiguration = self.defaultClientTLSConfiguration.configuration
  90. tlsConfiguration.applicationProtocols = ["not-h2", "not-grpc-ext"]
  91. let tls = ClientConnection.Configuration.TLS(
  92. configuration: tlsConfiguration,
  93. hostnameOverride: self.defaultClientTLSConfiguration.hostnameOverride
  94. )
  95. var configuration = self.makeClientConfiguration(tls: tls)
  96. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  97. configuration.errorDelegate = errorRecorder
  98. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  99. configuration.connectivityStateDelegate = stateChangeDelegate
  100. _ = ClientConnection(configuration: configuration)
  101. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  102. let clientErrors = errorRecorder.errors.compactMap { $0 as? GRPCClientError }
  103. XCTAssertEqual(clientErrors, [.applicationLevelProtocolNegotiationFailed])
  104. }
  105. func testClientConnectionFailsWhenServerIsUnknown() throws {
  106. let shutdownExpectation = self.expectation(description: "client shutdown")
  107. let errorExpectation = self.expectation(description: "error")
  108. var tls = self.defaultClientTLSConfiguration
  109. tls.trustRoots = .certificates([])
  110. var configuration = self.makeClientConfiguration(tls: tls)
  111. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  112. configuration.errorDelegate = errorRecorder
  113. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  114. configuration.connectivityStateDelegate = stateChangeDelegate
  115. _ = ClientConnection(configuration: configuration)
  116. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  117. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  118. case .handshakeFailed(.sslError) = nioSSLError {
  119. // Expected case.
  120. } else {
  121. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  122. }
  123. }
  124. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  125. let shutdownExpectation = self.expectation(description: "client shutdown")
  126. let errorExpectation = self.expectation(description: "error")
  127. var tls = self.defaultClientTLSConfiguration
  128. tls.hostnameOverride = "not-the-server-hostname"
  129. var configuration = self.makeClientConfiguration(tls: tls)
  130. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  131. configuration.errorDelegate = errorRecorder
  132. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  133. configuration.connectivityStateDelegate = stateChangeDelegate
  134. let _ = ClientConnection(configuration: configuration)
  135. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  136. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  137. case .unableToValidateCertificate = nioSSLError {
  138. // Expected case.
  139. } else {
  140. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  141. }
  142. }
  143. }