ClientTLSFailureTests.swift 6.7 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 connection = ClientConnection(configuration: configuration)
  103. connection.connectivity.onNext(state: .shutdown) {
  104. shutdownExpectation.fulfill()
  105. }
  106. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  107. let clientErrors = errorRecorder.errors.compactMap { $0 as? GRPCClientError }
  108. XCTAssertEqual(clientErrors, [.applicationLevelProtocolNegotiationFailed])
  109. }
  110. func testClientConnectionFailsWhenServerIsUnknown() throws {
  111. let shutdownExpectation = self.expectation(description: "client shutdown")
  112. let errorExpectation = self.expectation(description: "error")
  113. var tls = defaultClientTLSConfiguration
  114. tls.trustRoots = .certificates([])
  115. var configuration = try self.makeClientConfiguration(tls: tls)
  116. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  117. configuration.errorDelegate = errorRecorder
  118. let connection = ClientConnection(configuration: configuration)
  119. connection.connectivity.onNext(state: .shutdown) {
  120. shutdownExpectation.fulfill()
  121. }
  122. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  123. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  124. case .handshakeFailed(.sslError) = nioSSLError {
  125. // Expected case.
  126. } else {
  127. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  128. }
  129. }
  130. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  131. let shutdownExpectation = self.expectation(description: "client shutdown")
  132. let errorExpectation = self.expectation(description: "error")
  133. var configuration = try self.makeClientConfiguration(
  134. tls: self.defaultClientTLSConfiguration,
  135. hostOverride: "not-the-server-hostname"
  136. )
  137. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  138. configuration.errorDelegate = errorRecorder
  139. let connection = ClientConnection(configuration: configuration)
  140. connection.connectivity.onNext(state: .shutdown) {
  141. shutdownExpectation.fulfill()
  142. }
  143. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  144. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  145. case .unableToValidateCertificate = nioSSLError {
  146. // Expected case.
  147. } else {
  148. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  149. }
  150. }
  151. }