ServerTLSErrorTests.swift 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. /*
  2. * Copyright 2020, 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 EchoImplementation
  17. import EchoModel
  18. @testable import GRPC
  19. import GRPCSampleData
  20. import Logging
  21. import NIO
  22. import NIOSSL
  23. import XCTest
  24. class ServerErrorRecordingDelegate: ServerErrorDelegate {
  25. var errors: [Error] = []
  26. var expectation: XCTestExpectation
  27. init(expectation: XCTestExpectation) {
  28. self.expectation = expectation
  29. }
  30. func observeLibraryError(_ error: Error) {
  31. self.errors.append(error)
  32. self.expectation.fulfill()
  33. }
  34. }
  35. class ServerTLSErrorTests: GRPCTestCase {
  36. let defaultClientTLSConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  37. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  38. privateKey: .privateKey(SamplePrivateKey.client),
  39. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  40. hostnameOverride: SampleCertificate.server.commonName
  41. )
  42. var defaultTestTimeout: TimeInterval = 1.0
  43. var clientEventLoopGroup: EventLoopGroup!
  44. var serverEventLoopGroup: EventLoopGroup!
  45. func makeClientConfiguration(
  46. tls: GRPCTLSConfiguration,
  47. port: Int
  48. ) -> ClientConnection.Configuration {
  49. var configuration = ClientConnection.Configuration.default(
  50. target: .hostAndPort("localhost", port),
  51. eventLoopGroup: self.clientEventLoopGroup
  52. )
  53. configuration.tlsConfiguration = tls
  54. // No need to retry connecting.
  55. configuration.connectionBackoff = nil
  56. return configuration
  57. }
  58. func makeClientConnectionExpectation() -> XCTestExpectation {
  59. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  60. }
  61. override func setUp() {
  62. super.setUp()
  63. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  64. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  65. }
  66. override func tearDown() {
  67. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  68. self.clientEventLoopGroup = nil
  69. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  70. self.serverEventLoopGroup = nil
  71. super.tearDown()
  72. }
  73. func testErrorIsLoggedWhenSSLContextErrors() throws {
  74. let errorExpectation = self.expectation(description: "error")
  75. let errorDelegate = ServerErrorRecordingDelegate(expectation: errorExpectation)
  76. let server = try! Server.usingTLSBackedByNIOSSL(
  77. on: self.serverEventLoopGroup,
  78. certificateChain: [SampleCertificate.exampleServerWithExplicitCurve.certificate],
  79. privateKey: SamplePrivateKey.exampleServerWithExplicitCurve
  80. ).withServiceProviders([EchoProvider()])
  81. .withErrorDelegate(errorDelegate)
  82. .bind(host: "localhost", port: 0)
  83. .wait()
  84. defer {
  85. XCTAssertNoThrow(try server.close().wait())
  86. }
  87. let port = server.channel.localAddress!.port!
  88. var tls = self.defaultClientTLSConfiguration
  89. tls.updateNIOTrustRoots(
  90. to: .certificates([SampleCertificate.exampleServerWithExplicitCurve.certificate])
  91. )
  92. var configuration = self.makeClientConfiguration(tls: tls, port: port)
  93. let stateChangeDelegate = RecordingConnectivityDelegate()
  94. stateChangeDelegate.expectChanges(2) { changes in
  95. XCTAssertEqual(changes, [
  96. Change(from: .idle, to: .connecting),
  97. Change(from: .connecting, to: .shutdown),
  98. ])
  99. }
  100. configuration.connectivityStateDelegate = stateChangeDelegate
  101. // Start an RPC to trigger creating a channel.
  102. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  103. defer {
  104. XCTAssertNoThrow(try echo.channel.close().wait())
  105. }
  106. _ = echo.get(.with { $0.text = "foo" })
  107. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  108. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(1))
  109. if let nioSSLError = errorDelegate.errors.first as? NIOSSLError,
  110. case .failedToLoadCertificate = nioSSLError {
  111. // Expected case.
  112. } else {
  113. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  114. }
  115. }
  116. }