ClientTLSFailureTests.swift 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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. @testable import GRPC
  17. import GRPCSampleData
  18. import EchoImplementation
  19. import Logging
  20. import NIO
  21. import NIOSSL
  22. import XCTest
  23. class ErrorRecordingDelegate: ClientErrorDelegate {
  24. var errors: [Error] = []
  25. var expectation: XCTestExpectation
  26. init(expectation: XCTestExpectation) {
  27. self.expectation = expectation
  28. }
  29. func didCatchError(_ error: Error, logger: Logger, file: StaticString, line: Int) {
  30. self.errors.append(error)
  31. self.expectation.fulfill()
  32. }
  33. }
  34. class ClientTLSFailureTests: GRPCTestCase {
  35. let defaultServerTLSConfiguration = Server.Configuration.TLS(
  36. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  37. privateKey: .privateKey(SamplePrivateKey.server))
  38. let defaultClientTLSConfiguration = ClientConnection.Configuration.TLS(
  39. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  40. privateKey: .privateKey(SamplePrivateKey.client),
  41. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  42. hostnameOverride: SampleCertificate.server.commonName)
  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: ClientConnection.Configuration.TLS
  50. ) -> ClientConnection.Configuration {
  51. return .init(
  52. target: .hostAndPort("localhost", self.port),
  53. eventLoopGroup: self.clientEventLoopGroup,
  54. tls: tls,
  55. // No need to retry connecting.
  56. connectionBackoff: nil
  57. )
  58. }
  59. func makeClientConnectionExpectation() -> XCTestExpectation {
  60. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  61. }
  62. override func setUp() {
  63. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  64. self.server = try! Server.secure(
  65. group: self.serverEventLoopGroup,
  66. certificateChain: [SampleCertificate.server.certificate],
  67. privateKey: SamplePrivateKey.server
  68. ).withServiceProviders([EchoProvider()])
  69. .bind(host: "localhost", port: 0)
  70. .wait()
  71. self.port = self.server.channel.localAddress?.port
  72. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  73. // Delay the client connection creation until the test.
  74. }
  75. override func tearDown() {
  76. self.port = nil
  77. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  78. self.clientEventLoopGroup = nil
  79. XCTAssertNoThrow(try self.server.close().wait())
  80. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  81. self.server = nil
  82. self.serverEventLoopGroup = nil
  83. }
  84. func testClientConnectionFailsWhenServerIsUnknown() throws {
  85. let shutdownExpectation = self.expectation(description: "client shutdown")
  86. let errorExpectation = self.expectation(description: "error")
  87. var tls = self.defaultClientTLSConfiguration
  88. tls.trustRoots = .certificates([])
  89. var configuration = self.makeClientConfiguration(tls: tls)
  90. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  91. configuration.errorDelegate = errorRecorder
  92. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  93. configuration.connectivityStateDelegate = stateChangeDelegate
  94. _ = ClientConnection(configuration: configuration)
  95. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  96. if let nioSSLError = errorRecorder.errors.first as? NIOSSLError,
  97. case .handshakeFailed(.sslError) = nioSSLError {
  98. // Expected case.
  99. } else {
  100. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  101. }
  102. }
  103. func testClientConnectionFailsWhenHostnameIsNotValid() throws {
  104. let shutdownExpectation = self.expectation(description: "client shutdown")
  105. let errorExpectation = self.expectation(description: "error")
  106. var tls = self.defaultClientTLSConfiguration
  107. tls.hostnameOverride = "not-the-server-hostname"
  108. var configuration = self.makeClientConfiguration(tls: tls)
  109. let errorRecorder = ErrorRecordingDelegate(expectation: errorExpectation)
  110. configuration.errorDelegate = errorRecorder
  111. let stateChangeDelegate = ConnectivityStateCollectionDelegate(shutdown: shutdownExpectation)
  112. configuration.connectivityStateDelegate = stateChangeDelegate
  113. let _ = ClientConnection(configuration: configuration)
  114. self.wait(for: [shutdownExpectation, errorExpectation], timeout: self.defaultTestTimeout)
  115. if let nioSSLError = errorRecorder.errors.first as? NIOSSLExtraError {
  116. XCTAssertEqual(nioSSLError, .failedToValidateHostname)
  117. // Expected case.
  118. } else {
  119. XCTFail("Expected NIOSSLExtraError.failedToValidateHostname")
  120. }
  121. }
  122. }