HeaderNormalizationTests.swift 6.1 KB

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