ServerTLSErrorTests.swift 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. #if canImport(NIOSSL)
  17. import EchoImplementation
  18. import EchoModel
  19. @testable import GRPC
  20. import GRPCSampleData
  21. import Logging
  22. import NIOCore
  23. import NIOPosix
  24. import NIOSSL
  25. import XCTest
  26. class ServerTLSErrorTests: GRPCTestCase {
  27. let defaultClientTLSConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  28. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  29. privateKey: .privateKey(SamplePrivateKey.client),
  30. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  31. hostnameOverride: SampleCertificate.server.commonName
  32. )
  33. var defaultTestTimeout: TimeInterval = 1.0
  34. var clientEventLoopGroup: EventLoopGroup!
  35. var serverEventLoopGroup: EventLoopGroup!
  36. func makeClientConfiguration(
  37. tls: GRPCTLSConfiguration,
  38. port: Int
  39. ) -> ClientConnection.Configuration {
  40. var configuration = ClientConnection.Configuration.default(
  41. target: .hostAndPort("localhost", port),
  42. eventLoopGroup: self.clientEventLoopGroup
  43. )
  44. configuration.tlsConfiguration = tls
  45. // No need to retry connecting.
  46. configuration.connectionBackoff = nil
  47. return configuration
  48. }
  49. func makeClientConnectionExpectation() -> XCTestExpectation {
  50. return self.expectation(description: "EventLoopFuture<ClientConnection> resolved")
  51. }
  52. override func setUp() {
  53. super.setUp()
  54. self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  55. self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  56. }
  57. override func tearDown() {
  58. XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
  59. self.clientEventLoopGroup = nil
  60. XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
  61. self.serverEventLoopGroup = nil
  62. super.tearDown()
  63. }
  64. func testErrorIsLoggedWhenSSLContextErrors() throws {
  65. let errorExpectation = self.expectation(description: "error")
  66. let errorDelegate = ServerErrorRecordingDelegate(expectation: errorExpectation)
  67. let server = try! Server.usingTLSBackedByNIOSSL(
  68. on: self.serverEventLoopGroup,
  69. certificateChain: [SampleCertificate.exampleServerWithExplicitCurve.certificate],
  70. privateKey: SamplePrivateKey.exampleServerWithExplicitCurve
  71. ).withServiceProviders([EchoProvider()])
  72. .withErrorDelegate(errorDelegate)
  73. .bind(host: "localhost", port: 0)
  74. .wait()
  75. defer {
  76. XCTAssertNoThrow(try server.close().wait())
  77. }
  78. let port = server.channel.localAddress!.port!
  79. var tls = self.defaultClientTLSConfiguration
  80. tls.updateNIOTrustRoots(
  81. to: .certificates([SampleCertificate.exampleServerWithExplicitCurve.certificate])
  82. )
  83. var configuration = self.makeClientConfiguration(tls: tls, port: port)
  84. let stateChangeDelegate = RecordingConnectivityDelegate()
  85. stateChangeDelegate.expectChanges(2) { changes in
  86. XCTAssertEqual(changes, [
  87. Change(from: .idle, to: .connecting),
  88. Change(from: .connecting, to: .shutdown),
  89. ])
  90. }
  91. configuration.connectivityStateDelegate = stateChangeDelegate
  92. // Start an RPC to trigger creating a channel.
  93. let echo = Echo_EchoNIOClient(channel: ClientConnection(configuration: configuration))
  94. defer {
  95. XCTAssertNoThrow(try echo.channel.close().wait())
  96. }
  97. _ = echo.get(.with { $0.text = "foo" })
  98. self.wait(for: [errorExpectation], timeout: self.defaultTestTimeout)
  99. stateChangeDelegate.waitForExpectedChanges(timeout: .seconds(1))
  100. if let nioSSLError = errorDelegate.errors.first as? NIOSSLError,
  101. case .failedToLoadCertificate = nioSSLError {
  102. // Expected case.
  103. } else {
  104. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  105. }
  106. }
  107. func testServerCustomVerificationCallback() async throws {
  108. let verificationCallbackInvoked = self.serverEventLoopGroup.next().makePromise(of: Void.self)
  109. let configuration = GRPCTLSConfiguration.makeServerConfigurationBackedByNIOSSL(
  110. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  111. privateKey: .privateKey(SamplePrivateKey.server),
  112. certificateVerification: .fullVerification,
  113. customVerificationCallback: { _, promise in
  114. verificationCallbackInvoked.succeed()
  115. promise.succeed(.failed)
  116. }
  117. )
  118. let server = try await Server.usingTLS(with: configuration, on: self.serverEventLoopGroup)
  119. .withServiceProviders([EchoProvider()])
  120. .bind(host: "localhost", port: 0)
  121. .get()
  122. defer {
  123. XCTAssertNoThrow(try server.close().wait())
  124. }
  125. let clientTLSConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  126. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  127. privateKey: .privateKey(SamplePrivateKey.client),
  128. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  129. certificateVerification: .noHostnameVerification,
  130. hostnameOverride: SampleCertificate.server.commonName
  131. )
  132. let client = try GRPCChannelPool.with(
  133. target: .hostAndPort("localhost", server.channel.localAddress!.port!),
  134. transportSecurity: .tls(clientTLSConfiguration),
  135. eventLoopGroup: self.clientEventLoopGroup
  136. )
  137. defer {
  138. XCTAssertNoThrow(try client.close().wait())
  139. }
  140. let echo = Echo_EchoAsyncClient(channel: client)
  141. enum TaskResult {
  142. case rpcFailed
  143. case rpcSucceeded
  144. case verificationCallbackInvoked
  145. }
  146. await withTaskGroup(of: TaskResult.self, returning: Void.self) { group in
  147. group.addTask {
  148. // Call the service to start an RPC.
  149. do {
  150. _ = try await echo.get(.with { $0.text = "foo" })
  151. return .rpcSucceeded
  152. } catch {
  153. return .rpcFailed
  154. }
  155. }
  156. group.addTask {
  157. // '!' is okay, the promise is only ever succeeded.
  158. try! await verificationCallbackInvoked.futureResult.get()
  159. return .verificationCallbackInvoked
  160. }
  161. while let next = await group.next() {
  162. switch next {
  163. case .verificationCallbackInvoked:
  164. // Expected.
  165. group.cancelAll()
  166. case .rpcFailed:
  167. // Expected, carry on.
  168. continue
  169. case .rpcSucceeded:
  170. XCTFail("RPC succeeded but shouldn't have")
  171. }
  172. }
  173. }
  174. }
  175. }
  176. #endif // canImport(NIOSSL)