ClientTLSTests.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. /*
  2. * Copyright 2019, 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. import Foundation
  20. import GRPC
  21. import GRPCSampleData
  22. import NIOCore
  23. import NIOPosix
  24. import NIOSSL
  25. import XCTest
  26. class ClientTLSHostnameOverrideTests: GRPCTestCase {
  27. var eventLoopGroup: EventLoopGroup!
  28. var server: Server!
  29. var connection: ClientConnection!
  30. override func setUp() {
  31. super.setUp()
  32. self.eventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  33. }
  34. override func tearDown() {
  35. XCTAssertNoThrow(try self.server.close().wait())
  36. XCTAssertNoThrow(try self.connection.close().wait())
  37. XCTAssertNoThrow(try self.eventLoopGroup.syncShutdownGracefully())
  38. super.tearDown()
  39. }
  40. func doTestUnary() throws {
  41. let client = Echo_EchoNIOClient(
  42. channel: self.connection,
  43. defaultCallOptions: self.callOptionsWithLogger
  44. )
  45. let get = client.get(.with { $0.text = "foo" })
  46. let response = try get.response.wait()
  47. XCTAssertEqual(response.text, "Swift echo get: foo")
  48. let status = try get.status.wait()
  49. XCTAssertEqual(status.code, .ok)
  50. }
  51. func testTLSWithHostnameOverride() throws {
  52. // Run a server presenting a certificate for example.com on localhost.
  53. let cert = SampleCertificate.exampleServer.certificate
  54. let key = SamplePrivateKey.exampleServer
  55. self.server = try Server.usingTLSBackedByNIOSSL(
  56. on: self.eventLoopGroup,
  57. certificateChain: [cert],
  58. privateKey: key
  59. )
  60. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  61. .withServiceProviders([EchoProvider()])
  62. .withLogger(self.serverLogger)
  63. .bind(host: "localhost", port: 0)
  64. .wait()
  65. guard let port = self.server.channel.localAddress?.port else {
  66. XCTFail("could not get server port")
  67. return
  68. }
  69. self.connection = ClientConnection.usingTLSBackedByNIOSSL(on: self.eventLoopGroup)
  70. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  71. .withTLS(serverHostnameOverride: "example.com")
  72. .withBackgroundActivityLogger(self.clientLogger)
  73. .connect(host: "localhost", port: port)
  74. try self.doTestUnary()
  75. }
  76. func testTLSWithoutHostnameOverride() throws {
  77. // Run a server presenting a certificate for localhost on localhost.
  78. let cert = SampleCertificate.server.certificate
  79. let key = SamplePrivateKey.server
  80. self.server = try Server.usingTLSBackedByNIOSSL(
  81. on: self.eventLoopGroup,
  82. certificateChain: [cert],
  83. privateKey: key
  84. )
  85. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  86. .withServiceProviders([EchoProvider()])
  87. .withLogger(self.serverLogger)
  88. .bind(host: "localhost", port: 0)
  89. .wait()
  90. guard let port = self.server.channel.localAddress?.port else {
  91. XCTFail("could not get server port")
  92. return
  93. }
  94. self.connection = ClientConnection.usingTLSBackedByNIOSSL(on: self.eventLoopGroup)
  95. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  96. .withBackgroundActivityLogger(self.clientLogger)
  97. .connect(host: "localhost", port: port)
  98. try self.doTestUnary()
  99. }
  100. func testTLSWithNoCertificateVerification() throws {
  101. self.server = try Server.usingTLSBackedByNIOSSL(
  102. on: self.eventLoopGroup,
  103. certificateChain: [SampleCertificate.server.certificate],
  104. privateKey: SamplePrivateKey.server
  105. )
  106. .withServiceProviders([EchoProvider()])
  107. .withLogger(self.serverLogger)
  108. .bind(host: "localhost", port: 0)
  109. .wait()
  110. guard let port = self.server.channel.localAddress?.port else {
  111. XCTFail("could not get server port")
  112. return
  113. }
  114. self.connection = ClientConnection.usingTLSBackedByNIOSSL(on: self.eventLoopGroup)
  115. .withTLS(trustRoots: .certificates([]))
  116. .withTLS(certificateVerification: .none)
  117. .withBackgroundActivityLogger(self.clientLogger)
  118. .connect(host: "localhost", port: port)
  119. try self.doTestUnary()
  120. }
  121. func testAuthorityUsesTLSHostnameOverride() throws {
  122. // This test validates that when suppled with a server hostname override, the client uses it
  123. // as the ":authority" pseudo-header.
  124. self.server = try Server.usingTLSBackedByNIOSSL(
  125. on: self.eventLoopGroup,
  126. certificateChain: [SampleCertificate.exampleServer.certificate],
  127. privateKey: SamplePrivateKey.exampleServer
  128. )
  129. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  130. .withServiceProviders([AuthorityCheckingEcho()])
  131. .withLogger(self.serverLogger)
  132. .bind(host: "localhost", port: 0)
  133. .wait()
  134. guard let port = self.server.channel.localAddress?.port else {
  135. XCTFail("could not get server port")
  136. return
  137. }
  138. self.connection = ClientConnection.usingTLSBackedByNIOSSL(on: self.eventLoopGroup)
  139. .withTLS(trustRoots: .certificates([SampleCertificate.ca.certificate]))
  140. .withTLS(serverHostnameOverride: "example.com")
  141. .withBackgroundActivityLogger(self.clientLogger)
  142. .connect(host: "localhost", port: port)
  143. try self.doTestUnary()
  144. }
  145. }
  146. private class AuthorityCheckingEcho: Echo_EchoProvider {
  147. var interceptors: Echo_EchoServerInterceptorFactoryProtocol?
  148. func get(
  149. request: Echo_EchoRequest,
  150. context: StatusOnlyCallContext
  151. ) -> EventLoopFuture<Echo_EchoResponse> {
  152. guard let authority = context.headers.first(name: ":authority") else {
  153. let status = GRPCStatus(
  154. code: .failedPrecondition,
  155. message: "Missing ':authority' pseudo header"
  156. )
  157. return context.eventLoop.makeFailedFuture(status)
  158. }
  159. XCTAssertEqual(authority, SampleCertificate.exampleServer.commonName)
  160. XCTAssertNotEqual(authority, "localhost")
  161. return context.eventLoop.makeSucceededFuture(
  162. .with {
  163. $0.text = "Swift echo get: \(request.text)"
  164. }
  165. )
  166. }
  167. func expand(
  168. request: Echo_EchoRequest,
  169. context: StreamingResponseCallContext<Echo_EchoResponse>
  170. ) -> EventLoopFuture<GRPCStatus> {
  171. preconditionFailure("Not implemented")
  172. }
  173. func collect(
  174. context: UnaryResponseCallContext<Echo_EchoResponse>
  175. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  176. preconditionFailure("Not implemented")
  177. }
  178. func update(
  179. context: StreamingResponseCallContext<Echo_EchoResponse>
  180. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  181. preconditionFailure("Not implemented")
  182. }
  183. }
  184. #endif // canImport(NIOSSL)