ClientTLSFailureTests.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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: XCTestCase {
  34. let defaultServerTLSConfiguration = TLSConfiguration.forServer(
  35. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  36. privateKey: .privateKey(SamplePrivateKey.server),
  37. applicationProtocols: GRPCApplicationProtocolIdentifier.allCases.map { $0.rawValue })
  38. let defaultClientTLSConfiguration = TLSConfiguration.forClient(
  39. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  40. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  41. privateKey: .privateKey(SamplePrivateKey.client),
  42. applicationProtocols: GRPCApplicationProtocolIdentifier.allCases.map { $0.rawValue })
  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: TLSConfiguration,
  50. hostOverride: String? = SampleCertificate.server.commonName
  51. ) throws -> ClientConnection.Configuration {
  52. return ClientConnection.Configuration(
  53. target: .hostAndPort("localhost", self.port),
  54. eventLoopGroup: self.clientEventLoopGroup,
  55. tlsConfiguration: try .init(
  56. sslContext: NIOSSLContext(configuration: tls),
  57. hostnameOverride: hostOverride
  58. )
  59. )
  60. }
  61. func makeClientTLSConfiguration(
  62. tls: TLSConfiguration,
  63. hostOverride: String? = SampleCertificate.server.commonName
  64. ) throws -> ClientConnection.TLSConfiguration {
  65. let context = try NIOSSLContext(configuration: tls)
  66. return .init(sslContext: context, hostnameOverride: hostOverride)
  67. }
  68. func makeClientConnectionExpectation() -> XCTestExpectation {
  69. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  70. }
  71. override func setUp() {
  72. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  73. let sslContext = try! NIOSSLContext(configuration: self.defaultServerTLSConfiguration)
  74. let configuration = Server.Configuration(
  75. target: .hostAndPort("localhost", 0),
  76. eventLoopGroup: self.serverEventLoopGroup,
  77. serviceProviders: [EchoProvider()],
  78. errorDelegate: nil,
  79. tlsConfiguration: .init(sslContext: sslContext))
  80. self.server = try! Server.start(configuration: configuration).wait()
  81. self.port = self.server.channel.localAddress?.port
  82. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  83. // Delay the client connection creation until the test.
  84. }
  85. override func tearDown() {
  86. self.port = nil
  87. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  88. self.clientEventLoopGroup = nil
  89. XCTAssertNoThrow(try self.server.close().wait())
  90. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  91. self.server = nil
  92. self.serverEventLoopGroup = nil
  93. }
  94. func testClientConnectionFailsWhenProtocolCanNotBeNegotiated() throws {
  95. let shutdownExpectation = self.expectation(description: "client shutdown")
  96. let errorExpectation = self.expectation(description: "error")
  97. var tls = defaultClientTLSConfiguration
  98. tls.applicationProtocols = ["not-h2", "not-grpc-ext"]
  99. var configuration = try self.makeClientConfiguration(tls: tls)
  100. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  101. configuration.errorDelegate = errorRecorder
  102. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  103. configuration.connectivityStateDelegate = stateChangeDelegate
  104. _ = ClientConnection(configuration: configuration)
  105. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  106. let clientErrors = errorRecorder.errors.compactMap { $0 as? GRPCClientError }
  107. XCTAssertEqual(clientErrors, [.applicationLevelProtocolNegotiationFailed])
  108. }
  109. func testClientConnectionFailsWhenServerIsUnknown() throws {
  110. let shutdownExpectation = self.expectation(description: "client shutdown")
  111. let errorExpectation = self.expectation(description: "error")
  112. var tls = defaultClientTLSConfiguration
  113. tls.trustRoots = .certificates([])
  114. var configuration = try self.makeClientConfiguration(tls: tls)
  115. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  116. configuration.errorDelegate = errorRecorder
  117. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  118. configuration.connectivityStateDelegate = stateChangeDelegate
  119. _ = ClientConnection(configuration: configuration)
  120. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  121. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  122. case .handshakeFailed(.sslError) = nioSSLError {
  123. // Expected case.
  124. } else {
  125. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  126. }
  127. }
  128. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  129. let shutdownExpectation = self.expectation(description: "client shutdown")
  130. let errorExpectation = self.expectation(description: "error")
  131. var configuration = try self.makeClientConfiguration(
  132. tls: self.defaultClientTLSConfiguration,
  133. hostOverride: "not-the-server-hostname"
  134. )
  135. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  136. configuration.errorDelegate = errorRecorder
  137. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  138. configuration.connectivityStateDelegate = stateChangeDelegate
  139. let _ = ClientConnection(configuration: configuration)
  140. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  141. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  142. case .unableToValidateCertificate = nioSSLError {
  143. // Expected case.
  144. } else {
  145. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  146. }
  147. }
  148. }