ServerTLSErrorTests.swift 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  61. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  62. }
  63. override func tearDown() {
  64. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  65. self.clientEventLoopGroup = nil
  66. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  67. self.serverEventLoopGroup = nil
  68. }
  69. func testErrorIsLoggedWhenSSLContextErrors() throws {
  70. let errorExpectation = self.expectation(description: "error")
  71. let errorDelegate = ServerErrorRecordingDelegate(expectation: errorExpectation)
  72. let server = try! Server.secure(
  73. group: self.serverEventLoopGroup,
  74. certificateChain: [SampleCertificate.exampleServerWithExplicitCurve.certificate],
  75. privateKey: SamplePrivateKey.exampleServerWithExplicitCurve
  76. ).withServiceProviders([EchoProvider()])
  77. .withErrorDelegate(errorDelegate)
  78. .bind(host: "localhost", port: 0)
  79. .wait()
  80. defer {
  81. XCTAssertNoThrow(try server.close().wait())
  82. }
  83. let port = server.channel.localAddress!.port!
  84. var tls = self.defaultClientTLSConfiguration
  85. tls.trustRoots = .certificates([SampleCertificate.exampleServerWithExplicitCurve.certificate])
  86. var configuration = self.makeClientConfiguration(tls: tls, port: port)
  87. let stateChangeDelegate = RecordingConnectivityDelegate()
  88. stateChangeDelegate.expectChanges(2) { changes in
  89. XCTAssertEqual(changes, [
  90. Change(from: .idle, to: .connecting),
  91. Change(from: .connecting, to: .shutdown)
  92. ])
  93. }
  94. configuration.connectivityStateDelegate = stateChangeDelegate
  95. // Start an RPC to trigger creating a channel.
  96. let echo = Echo_EchoClient(channel: ClientConnection(configuration: configuration))
  97. defer {
  98. XCTAssertNoThrow(try echo.channel.close().wait())
  99. }
  100. _ = echo.get(.with { $0.text = "foo" })
  101. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  102. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(1))
  103. if let nioSSLError = errorDelegate.errors.first as? NIOSSLError,
  104. case .failedToLoadCertificate = nioSSLError {
  105. // Expected case.
  106. } else {
  107. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  108. }
  109. }
  110. }