ClientTLSFailureTests.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. )
  55. }
  56. func makeClientConnectionExpectation() -> XCTestExpectation {
  57. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  58. }
  59. override func setUp() {
  60. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  61. let configuration = Server.Configuration(
  62. target: .hostAndPort("localhost", 0),
  63. eventLoopGroup: self.serverEventLoopGroup,
  64. serviceProviders: [EchoProvider()],
  65. errorDelegate: nil,
  66. tls: self.defaultServerTLSConfiguration)
  67. self.server = try! Server.start(configuration: configuration).wait()
  68. self.port = self.server.channel.localAddress?.port
  69. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  70. // Delay the client connection creation until the test.
  71. }
  72. override func tearDown() {
  73. self.port = nil
  74. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  75. self.clientEventLoopGroup = nil
  76. XCTAssertNoThrow(try self.server.close().wait())
  77. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  78. self.server = nil
  79. self.serverEventLoopGroup = nil
  80. }
  81. func testClientConnectionFailsWhenProtocolCanNotBeNegotiated() throws {
  82. let shutdownExpectation = self.expectation(description: "client shutdown")
  83. let errorExpectation = self.expectation(description: "error")
  84. // We use the underlying configuration because `applicationProtocols` is not user-configurable
  85. // via `Configuration.TLS`.
  86. var tlsConfiguration = self.defaultClientTLSConfiguration.configuration
  87. tlsConfiguration.applicationProtocols = ["not-h2", "not-grpc-ext"]
  88. let tls = ClientConnection.Configuration.TLS(
  89. configuration: tlsConfiguration,
  90. hostnameOverride: self.defaultClientTLSConfiguration.hostnameOverride
  91. )
  92. var configuration = self.makeClientConfiguration(tls: tls)
  93. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  94. configuration.errorDelegate = errorRecorder
  95. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  96. configuration.connectivityStateDelegate = stateChangeDelegate
  97. _ = ClientConnection(configuration: configuration)
  98. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  99. let clientErrors = errorRecorder.errors.compactMap { $0 as? GRPCClientError }
  100. XCTAssertEqual(clientErrors, [.applicationLevelProtocolNegotiationFailed])
  101. }
  102. func testClientConnectionFailsWhenServerIsUnknown() throws {
  103. let shutdownExpectation = self.expectation(description: "client shutdown")
  104. let errorExpectation = self.expectation(description: "error")
  105. var tls = self.defaultClientTLSConfiguration
  106. tls.trustRoots = .certificates([])
  107. var configuration = self.makeClientConfiguration(tls: tls)
  108. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  109. configuration.errorDelegate = errorRecorder
  110. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  111. configuration.connectivityStateDelegate = stateChangeDelegate
  112. _ = ClientConnection(configuration: configuration)
  113. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  114. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  115. case .handshakeFailed(.sslError) = nioSSLError {
  116. // Expected case.
  117. } else {
  118. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  119. }
  120. }
  121. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  122. let shutdownExpectation = self.expectation(description: "client shutdown")
  123. let errorExpectation = self.expectation(description: "error")
  124. var tls = self.defaultClientTLSConfiguration
  125. tls.hostnameOverride = "not-the-server-hostname"
  126. var configuration = self.makeClientConfiguration(tls: tls)
  127. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  128. configuration.errorDelegate = errorRecorder
  129. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  130. configuration.connectivityStateDelegate = stateChangeDelegate
  131. let _ = ClientConnection(configuration: configuration)
  132. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  133. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  134. case .unableToValidateCertificate = nioSSLError {
  135. // Expected case.
  136. } else {
  137. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  138. }
  139. }
  140. }