HeaderNormalizationTests.swift 6.2 KB

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