GRPCServerPipelineConfiguratorTests.swift 7.7 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. @testable import GRPC
  17. import NIO
  18. import NIOHTTP2
  19. import NIOTLS
  20. import XCTest
  21. class GRPCServerPipelineConfiguratorTests: GRPCTestCase {
  22. private var channel: EmbeddedChannel!
  23. private func assertConfigurator(isPresent: Bool) {
  24. assertThat(
  25. try self.channel.pipeline.handler(type: GRPCServerPipelineConfigurator.self).wait(),
  26. isPresent ? .doesNotThrow() : .throws()
  27. )
  28. }
  29. private func assertHTTP2Handler(isPresent: Bool) {
  30. assertThat(
  31. try self.channel.pipeline.handler(type: NIOHTTP2Handler.self).wait(),
  32. isPresent ? .doesNotThrow() : .throws()
  33. )
  34. }
  35. private func assertGRPCWebToHTTP2Handler(isPresent: Bool) {
  36. assertThat(
  37. try self.channel.pipeline.handler(type: GRPCWebToHTTP2ServerCodec.self).wait(),
  38. isPresent ? .doesNotThrow() : .throws()
  39. )
  40. }
  41. private func setUp(tls: Bool, requireALPN: Bool = true) {
  42. self.channel = EmbeddedChannel()
  43. var configuration = Server.Configuration.default(
  44. target: .unixDomainSocket("/ignored"),
  45. eventLoopGroup: self.channel.eventLoop,
  46. serviceProviders: []
  47. )
  48. configuration.logger = self.serverLogger
  49. if tls {
  50. configuration.tlsConfiguration = .makeServerConfigurationBackedByNIOSSL(
  51. certificateChain: [],
  52. privateKey: .file("not used"),
  53. requireALPN: requireALPN
  54. )
  55. }
  56. let handler = GRPCServerPipelineConfigurator(configuration: configuration)
  57. assertThat(try self.channel.pipeline.addHandler(handler).wait(), .doesNotThrow())
  58. }
  59. func testHTTP2SetupViaALPN() {
  60. self.setUp(tls: true, requireALPN: true)
  61. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")
  62. self.channel.pipeline.fireUserInboundEventTriggered(event)
  63. self.assertConfigurator(isPresent: false)
  64. self.assertHTTP2Handler(isPresent: true)
  65. }
  66. func testGRPCExpSetupViaALPN() {
  67. self.setUp(tls: true, requireALPN: true)
  68. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: "grpc-exp")
  69. self.channel.pipeline.fireUserInboundEventTriggered(event)
  70. self.assertConfigurator(isPresent: false)
  71. self.assertHTTP2Handler(isPresent: true)
  72. }
  73. func testHTTP1Dot1SetupViaALPN() {
  74. self.setUp(tls: true, requireALPN: true)
  75. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: "http/1.1")
  76. self.channel.pipeline.fireUserInboundEventTriggered(event)
  77. self.assertConfigurator(isPresent: false)
  78. self.assertGRPCWebToHTTP2Handler(isPresent: true)
  79. }
  80. func testUnrecognisedALPNCloses() {
  81. self.setUp(tls: true, requireALPN: true)
  82. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: "unsupported")
  83. self.channel.pipeline.fireUserInboundEventTriggered(event)
  84. self.channel.embeddedEventLoop.run()
  85. assertThat(try self.channel.closeFuture.wait(), .doesNotThrow())
  86. }
  87. func testNoNegotiatedProtocolCloses() {
  88. self.setUp(tls: true, requireALPN: true)
  89. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)
  90. self.channel.pipeline.fireUserInboundEventTriggered(event)
  91. self.channel.embeddedEventLoop.run()
  92. assertThat(try self.channel.closeFuture.wait(), .doesNotThrow())
  93. }
  94. func testNoNegotiatedProtocolFallbackToBytesWhenALPNNotRequired() throws {
  95. self.setUp(tls: true, requireALPN: false)
  96. // Require ALPN is disabled, so this is a no-op.
  97. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)
  98. self.channel.pipeline.fireUserInboundEventTriggered(event)
  99. // Configure via bytes.
  100. let bytes = ByteBuffer(staticString: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  101. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  102. self.assertConfigurator(isPresent: false)
  103. self.assertHTTP2Handler(isPresent: true)
  104. }
  105. func testHTTP2SetupViaBytes() {
  106. self.setUp(tls: false)
  107. let bytes = ByteBuffer(staticString: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  108. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  109. self.assertConfigurator(isPresent: false)
  110. self.assertHTTP2Handler(isPresent: true)
  111. }
  112. func testHTTP1Dot1SetupViaBytes() {
  113. self.setUp(tls: false)
  114. let bytes = ByteBuffer(staticString: "GET http://www.foo.bar HTTP/1.1\r\n")
  115. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  116. self.assertConfigurator(isPresent: false)
  117. self.assertGRPCWebToHTTP2Handler(isPresent: true)
  118. }
  119. func testReadsAreUnbufferedAfterConfiguration() throws {
  120. self.setUp(tls: false)
  121. var bytes = ByteBuffer(staticString: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  122. // A SETTINGS frame MUST follow the connection preface. Append one so that the HTTP/2 handler
  123. // responds with its initial settings (and we validate that we forward frames once configuring).
  124. let emptySettingsFrameBytes: [UInt8] = [
  125. 0x00, 0x00, 0x00, // 3-byte payload length (0 bytes)
  126. 0x04, // 1-byte frame type (SETTINGS)
  127. 0x00, // 1-byte flags (none)
  128. 0x00, 0x00, 0x00, 0x00, // 4-byte stream identifier
  129. ]
  130. bytes.writeBytes(emptySettingsFrameBytes)
  131. // Do the setup.
  132. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  133. self.assertConfigurator(isPresent: false)
  134. self.assertHTTP2Handler(isPresent: true)
  135. // We expect the server to respond with a SETTINGS frame now.
  136. let ioData = try channel.readOutbound(as: IOData.self)
  137. switch ioData {
  138. case var .some(.byteBuffer(buffer)):
  139. if let frame = buffer.readBytes(length: 9) {
  140. // Just check it's a SETTINGS frame.
  141. assertThat(frame[3], .is(0x04))
  142. } else {
  143. XCTFail("Expected more bytes")
  144. }
  145. default:
  146. XCTFail("Expected ByteBuffer but got \(String(describing: ioData))")
  147. }
  148. }
  149. func testALPNIsPreferredOverBytes() throws {
  150. self.setUp(tls: true, requireALPN: true)
  151. // Write in an HTTP/1 request line. This should just be buffered.
  152. let bytes = ByteBuffer(staticString: "GET http://www.foo.bar HTTP/1.1\r\n")
  153. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  154. self.assertConfigurator(isPresent: true)
  155. self.assertHTTP2Handler(isPresent: false)
  156. self.assertGRPCWebToHTTP2Handler(isPresent: false)
  157. // Now configure HTTP/2 with ALPN. This should be used to configure the pipeline.
  158. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: "h2")
  159. self.channel.pipeline.fireUserInboundEventTriggered(event)
  160. self.assertConfigurator(isPresent: false)
  161. self.assertGRPCWebToHTTP2Handler(isPresent: false)
  162. self.assertHTTP2Handler(isPresent: true)
  163. }
  164. func testALPNFallbackToAlreadyBufferedBytes() throws {
  165. self.setUp(tls: true, requireALPN: false)
  166. // Write in an HTTP/2 connection preface. This should just be buffered.
  167. let bytes = ByteBuffer(staticString: "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
  168. assertThat(try self.channel.writeInbound(bytes), .doesNotThrow())
  169. self.assertConfigurator(isPresent: true)
  170. self.assertHTTP2Handler(isPresent: false)
  171. // Complete the handshake with no protocol negotiated, we should fallback to the buffered bytes.
  172. let event = TLSUserEvent.handshakeCompleted(negotiatedProtocol: nil)
  173. self.channel.pipeline.fireUserInboundEventTriggered(event)
  174. self.assertConfigurator(isPresent: false)
  175. self.assertHTTP2Handler(isPresent: true)
  176. }
  177. }