ServerTLSErrorTests.swift 4.4 KB

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