ClientTLSFailureTests.swift 6.6 KB

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