HeaderNormalizationTests.swift 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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 EchoModel
  18. import EchoImplementation
  19. import NIO
  20. import NIOHTTP1
  21. import NIOHPACK
  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 { name, 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. }
  99. private func assertCustomMetadataIsLowercased(
  100. _ headers: EventLoopFuture<HPACKHeaders>,
  101. expectation: XCTestExpectation,
  102. file: StaticString = #file,
  103. line: UInt = #line
  104. ) {
  105. // Header lookup is case-insensitive so we need to pull out the values we know the server sent
  106. // us as trailing-metadata and then compare a new set of headers.
  107. headers.map { trailers -> HPACKHeaders in
  108. let filtered = trailers.filter {
  109. $0.value == "server"
  110. }.map { (name, value, indexing) in
  111. return (name, value)
  112. }
  113. return HPACKHeaders(filtered)
  114. }.assertEqual(["server": "server"], fulfill: expectation, file: file, line: line)
  115. }
  116. func testHeadersAreNormalizedForUnary() throws {
  117. let trailingMetadata = self.expectation(description: "received trailing metadata")
  118. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  119. let rpc = self.client.get(.with { $0.text = "foo" }, callOptions: options)
  120. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  121. self.wait(for: [trailingMetadata], timeout: 1.0)
  122. }
  123. func testHeadersAreNormalizedForClientStreaming() throws {
  124. let trailingMetadata = self.expectation(description: "received trailing metadata")
  125. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  126. let rpc = self.client.collect(callOptions: options)
  127. rpc.sendEnd(promise: nil)
  128. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  129. self.wait(for: [trailingMetadata], timeout: 1.0)
  130. }
  131. func testHeadersAreNormalizedForServerStreaming() throws {
  132. let trailingMetadata = self.expectation(description: "received trailing metadata")
  133. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  134. let rpc = self.client.expand(.with { $0.text = "foo" }, callOptions: options) {
  135. XCTFail("unexpected response: \($0)")
  136. }
  137. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  138. self.wait(for: [trailingMetadata], timeout: 1.0)
  139. }
  140. func testHeadersAreNormalizedForBidirectionalStreaming() throws {
  141. let trailingMetadata = self.expectation(description: "received trailing metadata")
  142. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  143. let rpc = self.client.update(callOptions: options) {
  144. XCTFail("unexpected response: \($0)")
  145. }
  146. rpc.sendEnd(promise: nil)
  147. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  148. self.wait(for: [trailingMetadata], timeout: 1.0)
  149. }
  150. }