HeaderNormalizationTests.swift 6.2 KB

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