ServerTLSErrorTests.swift 4.5 KB

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