HeaderNormalizationTests.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. import EchoImplementation
  17. import EchoModel
  18. import NIOCore
  19. import NIOHPACK
  20. import NIOHTTP1
  21. import NIOPosix
  22. import XCTest
  23. @testable import GRPC
  24. class EchoMetadataValidator: Echo_EchoProvider {
  25. let interceptors: Echo_EchoServerInterceptorFactoryProtocol? = nil
  26. private func assertCustomMetadataIsLowercased(
  27. _ headers: HPACKHeaders,
  28. line: UInt = #line
  29. ) {
  30. // Header lookup is case-insensitive so we need to pull out the values we know the client sent
  31. // as custom-metadata and then compare a new set of headers.
  32. let customMetadata = HPACKHeaders(
  33. headers.filter { _, value, _ in
  34. value == "client"
  35. }.map {
  36. ($0.name, $0.value)
  37. }
  38. )
  39. XCTAssertEqual(customMetadata, ["client": "client"], line: line)
  40. }
  41. func get(
  42. request: Echo_EchoRequest,
  43. context: StatusOnlyCallContext
  44. ) -> EventLoopFuture<Echo_EchoResponse> {
  45. self.assertCustomMetadataIsLowercased(context.headers)
  46. context.trailers.add(name: "SERVER", value: "server")
  47. return context.eventLoop.makeSucceededFuture(.with { $0.text = request.text })
  48. }
  49. func expand(
  50. request: Echo_EchoRequest,
  51. context: StreamingResponseCallContext<Echo_EchoResponse>
  52. ) -> EventLoopFuture<GRPCStatus> {
  53. self.assertCustomMetadataIsLowercased(context.headers)
  54. context.trailers.add(name: "SERVER", value: "server")
  55. return context.eventLoop.makeSucceededFuture(.ok)
  56. }
  57. func collect(
  58. context: UnaryResponseCallContext<Echo_EchoResponse>
  59. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  60. self.assertCustomMetadataIsLowercased(context.headers)
  61. context.trailers.add(name: "SERVER", value: "server")
  62. return context.eventLoop.makeSucceededFuture({ event in
  63. switch event {
  64. case .message:
  65. ()
  66. case .end:
  67. context.responsePromise.succeed(.with { $0.text = "foo" })
  68. }
  69. })
  70. }
  71. func update(
  72. context: StreamingResponseCallContext<Echo_EchoResponse>
  73. ) -> EventLoopFuture<(StreamEvent<Echo_EchoRequest>) -> Void> {
  74. self.assertCustomMetadataIsLowercased(context.headers)
  75. context.trailers.add(name: "SERVER", value: "server")
  76. return context.eventLoop.makeSucceededFuture({ event in
  77. switch event {
  78. case .message:
  79. ()
  80. case .end:
  81. context.statusPromise.succeed(.ok)
  82. }
  83. })
  84. }
  85. }
  86. class HeaderNormalizationTests: GRPCTestCase {
  87. var group: EventLoopGroup!
  88. var server: Server!
  89. var channel: GRPCChannel!
  90. var client: Echo_EchoNIOClient!
  91. override func setUp() {
  92. super.setUp()
  93. self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  94. self.server = try! Server.insecure(group: self.group)
  95. .withServiceProviders([EchoMetadataValidator()])
  96. .bind(host: "localhost", port: 0)
  97. .wait()
  98. self.channel = ClientConnection.insecure(group: self.group)
  99. .connect(host: "localhost", port: self.server.channel.localAddress!.port!)
  100. self.client = Echo_EchoNIOClient(channel: self.channel)
  101. }
  102. override func tearDown() {
  103. XCTAssertNoThrow(try self.channel.close().wait())
  104. XCTAssertNoThrow(try self.server.close().wait())
  105. XCTAssertNoThrow(try self.group.syncShutdownGracefully())
  106. super.tearDown()
  107. }
  108. private func assertCustomMetadataIsLowercased(
  109. _ headers: EventLoopFuture<HPACKHeaders>,
  110. expectation: XCTestExpectation,
  111. file: StaticString = #filePath,
  112. line: UInt = #line
  113. ) {
  114. // Header lookup is case-insensitive so we need to pull out the values we know the server sent
  115. // us as trailing-metadata and then compare a new set of headers.
  116. headers.map { trailers -> HPACKHeaders in
  117. let filtered = trailers.filter {
  118. $0.value == "server"
  119. }.map { name, value, _ in
  120. (name, value)
  121. }
  122. return HPACKHeaders(filtered)
  123. }.assertEqual(["server": "server"], fulfill: expectation, file: file, line: line)
  124. }
  125. func testHeadersAreNormalizedForUnary() throws {
  126. let trailingMetadata = self.expectation(description: "received trailing metadata")
  127. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  128. let rpc = self.client.get(.with { $0.text = "foo" }, callOptions: options)
  129. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  130. self.wait(for: [trailingMetadata], timeout: 1.0)
  131. }
  132. func testHeadersAreNormalizedForClientStreaming() throws {
  133. let trailingMetadata = self.expectation(description: "received trailing metadata")
  134. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  135. let rpc = self.client.collect(callOptions: options)
  136. rpc.sendEnd(promise: nil)
  137. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  138. self.wait(for: [trailingMetadata], timeout: 1.0)
  139. }
  140. func testHeadersAreNormalizedForServerStreaming() throws {
  141. let trailingMetadata = self.expectation(description: "received trailing metadata")
  142. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  143. let rpc = self.client.expand(.with { $0.text = "foo" }, callOptions: options) {
  144. XCTFail("unexpected response: \($0)")
  145. }
  146. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  147. self.wait(for: [trailingMetadata], timeout: 1.0)
  148. }
  149. func testHeadersAreNormalizedForBidirectionalStreaming() throws {
  150. let trailingMetadata = self.expectation(description: "received trailing metadata")
  151. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  152. let rpc = self.client.update(callOptions: options) {
  153. XCTFail("unexpected response: \($0)")
  154. }
  155. rpc.sendEnd(promise: nil)
  156. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  157. self.wait(for: [trailingMetadata], timeout: 1.0)
  158. }
  159. }