HeaderNormalizationTests.swift 6.3 KB

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