ClientTLSFailureTests.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 testClientConnectionFailsWhenServerIsUnknown() throws {
  86. let shutdownExpectation = self.expectation(description: "client shutdown")
  87. let errorExpectation = self.expectation(description: "error")
  88. var tls = self.defaultClientTLSConfiguration
  89. tls.trustRoots = .certificates([])
  90. var configuration = self.makeClientConfiguration(tls: tls)
  91. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  92. configuration.errorDelegate = errorRecorder
  93. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  94. configuration.connectivityStateDelegate = stateChangeDelegate
  95. _ = ClientConnection(configuration: configuration)
  96. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  97. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  98. case .handshakeFailed(.sslError) = nioSSLError {
  99. // Expected case.
  100. } else {
  101. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  102. }
  103. }
  104. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  105. let shutdownExpectation = self.expectation(description: "client shutdown")
  106. let errorExpectation = self.expectation(description: "error")
  107. var tls = self.defaultClientTLSConfiguration
  108. tls.hostnameOverride = "not-the-server-hostname"
  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. let _ = ClientConnection(configuration: configuration)
  115. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  116. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  117. case .unableToValidateCertificate = nioSSLError {
  118. // Expected case.
  119. } else {
  120. XCTFail("Expected NIOSSLError.unableToValidateCertificate")
  121. }
  122. }
  123. }