ServerTLSErrorTests.swift 4.4 KB

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