ClientTLSFailureTests.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 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. let configuration = Server.Configuration(
  66. target: .hostAndPort("localhost", 0),
  67. eventLoopGroup: self.serverEventLoopGroup,
  68. serviceProviders: [EchoProvider()],
  69. errorDelegate: nil,
  70. tls: self.defaultServerTLSConfiguration)
  71. self.server = try! Server.start(configuration: configuration).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 testClientConnectionFailsWhenProtocolCanNotBeNegotiated() throws {
  86. let shutdownExpectation = self.expectation(description: "client shutdown")
  87. let errorExpectation = self.expectation(description: "error")
  88. // We use the underlying configuration because `applicationProtocols` is not user-configurable
  89. // via `Configuration.TLS`.
  90. var tlsConfiguration = self.defaultClientTLSConfiguration.configuration
  91. tlsConfiguration.applicationProtocols = ["not-h2", "not-grpc-ext"]
  92. let tls = ClientConnection.Configuration.TLS(
  93. configuration: tlsConfiguration,
  94. hostnameOverride: self.defaultClientTLSConfiguration.hostnameOverride
  95. )
  96. var configuration = self.makeClientConfiguration(tls: tls)
  97. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  98. configuration.errorDelegate = errorRecorder
  99. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  100. configuration.connectivityStateDelegate = stateChangeDelegate
  101. _ = ClientConnection(configuration: configuration)
  102. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  103. let clientErrors = errorRecorder.errors.compactMap { $0 as? GRPCClientError }
  104. XCTAssertEqual(clientErrors, [.applicationLevelProtocolNegotiationFailed])
  105. }
  106. func testClientConnectionFailsWhenServerIsUnknown() throws {
  107. let shutdownExpectation = self.expectation(description: "client shutdown")
  108. let errorExpectation = self.expectation(description: "error")
  109. var tls = self.defaultClientTLSConfiguration
  110. tls.trustRoots = .certificates([])
  111. var configuration = self.makeClientConfiguration(tls: tls)
  112. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  113. configuration.errorDelegate = errorRecorder
  114. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  115. configuration.connectivityStateDelegate = stateChangeDelegate
  116. _ = ClientConnection(configuration: configuration)
  117. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  118. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  119. case .handshakeFailed(.sslError) = nioSSLError {
  120. // Expected case.
  121. } else {
  122. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  123. }
  124. }
  125. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  126. let shutdownExpectation = self.expectation(description: "client shutdown")
  127. let errorExpectation = self.expectation(description: "error")
  128. var tls = self.defaultClientTLSConfiguration
  129. tls.hostnameOverride = "not-the-server-hostname"
  130. var configuration = self.makeClientConfiguration(tls: tls)
  131. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  132. configuration.errorDelegate = errorRecorder
  133. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  134. configuration.connectivityStateDelegate = stateChangeDelegate
  135. let _ = ClientConnection(configuration: configuration)
  136. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  137. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  138. case .unableToValidateCertificate = nioSSLError {
  139. // Expected case.
  140. } else {
  141. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  142. }
  143. }
  144. }