ServerTLSErrorTests.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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(
  87. changes,
  88. [
  89. Change(from: .idle, to: .connecting),
  90. Change(from: .connecting, to: .shutdown),
  91. ]
  92. )
  93. }
  94. configuration.connectivityStateDelegate = stateChangeDelegate
  95. // Start an RPC to trigger creating a channel.
  96. let echo = Echo_EchoNIOClient(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. {
  106. // Expected case.
  107. } else {
  108. XCTFail("Expected NIOSSLError.handshakeFailed(BoringSSL.sslError)")
  109. }
  110. }
  111. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
  112. func testServerCustomVerificationCallback() async throws {
  113. let verificationCallbackInvoked = self.serverEventLoopGroup.next().makePromise(of: Void.self)
  114. let configuration = GRPCTLSConfiguration.makeServerConfigurationBackedByNIOSSL(
  115. certificateChain: [.certificate(SampleCertificate.server.certificate)],
  116. privateKey: .privateKey(SamplePrivateKey.server),
  117. certificateVerification: .fullVerification,
  118. customVerificationCallback: { _, promise in
  119. verificationCallbackInvoked.succeed()
  120. promise.succeed(.failed)
  121. }
  122. )
  123. let server = try await Server.usingTLS(with: configuration, on: self.serverEventLoopGroup)
  124. .withServiceProviders([EchoProvider()])
  125. .bind(host: "localhost", port: 0)
  126. .get()
  127. defer {
  128. XCTAssertNoThrow(try server.close().wait())
  129. }
  130. let clientTLSConfiguration = GRPCTLSConfiguration.makeClientConfigurationBackedByNIOSSL(
  131. certificateChain: [.certificate(SampleCertificate.client.certificate)],
  132. privateKey: .privateKey(SamplePrivateKey.client),
  133. trustRoots: .certificates([SampleCertificate.ca.certificate]),
  134. certificateVerification: .noHostnameVerification,
  135. hostnameOverride: SampleCertificate.server.commonName
  136. )
  137. let client = try GRPCChannelPool.with(
  138. target: .hostAndPort("localhost", server.channel.localAddress!.port!),
  139. transportSecurity: .tls(clientTLSConfiguration),
  140. eventLoopGroup: self.clientEventLoopGroup
  141. )
  142. defer {
  143. XCTAssertNoThrow(try client.close().wait())
  144. }
  145. let echo = Echo_EchoAsyncClient(channel: client)
  146. enum TaskResult {
  147. case rpcFailed
  148. case rpcSucceeded
  149. case verificationCallbackInvoked
  150. }
  151. await withTaskGroup(of: TaskResult.self, returning: Void.self) { group in
  152. group.addTask {
  153. // Call the service to start an RPC.
  154. do {
  155. _ = try await echo.get(.with { $0.text = "foo" })
  156. return .rpcSucceeded
  157. } catch {
  158. return .rpcFailed
  159. }
  160. }
  161. group.addTask {
  162. // '!' is okay, the promise is only ever succeeded.
  163. try! await verificationCallbackInvoked.futureResult.get()
  164. return .verificationCallbackInvoked
  165. }
  166. while let next = await group.next() {
  167. switch next {
  168. case .verificationCallbackInvoked:
  169. // Expected.
  170. group.cancelAll()
  171. case .rpcFailed:
  172. // Expected, carry on.
  173. continue
  174. case .rpcSucceeded:
  175. XCTFail("RPC succeeded but shouldn't have")
  176. }
  177. }
  178. }
  179. }
  180. }
  181. #endif // canImport(NIOSSL)