HeaderNormalizationTests.swift 6.4 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. @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. let clientConfig = ClientConnection.Configuration(
  94. target: .hostAndPort("localhost", self.server.channel.localAddress!.port!),
  95. eventLoopGroup: self.group
  96. )
  97. self.channel = ClientConnection(configuration: clientConfig)
  98. self.client = Echo_EchoClient(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. }
  105. private func assertCustomMetadataIsLowercased(
  106. _ headers: EventLoopFuture<HPACKHeaders>,
  107. expectation: XCTestExpectation,
  108. file: StaticString = #file,
  109. line: UInt = #line
  110. ) {
  111. // Header lookup is case-insensitive so we need to pull out the values we know the server sent
  112. // us as trailing-metadata and then compare a new set of headers.
  113. headers.map { trailers -> HPACKHeaders in
  114. let filtered = trailers.filter {
  115. $0.value == "server"
  116. }.map { (name, value, indexing) in
  117. return (name, value)
  118. }
  119. return HPACKHeaders(filtered)
  120. }.assertEqual(["server": "server"], fulfill: expectation, file: file, line: line)
  121. }
  122. func testHeadersAreNormalizedForUnary() throws {
  123. let trailingMetadata = self.expectation(description: "received trailing metadata")
  124. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  125. let rpc = self.client.get(.with { $0.text = "foo" }, callOptions: options)
  126. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  127. self.wait(for: [trailingMetadata], timeout: 1.0)
  128. }
  129. func testHeadersAreNormalizedForClientStreaming() throws {
  130. let trailingMetadata = self.expectation(description: "received trailing metadata")
  131. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  132. let rpc = self.client.collect(callOptions: options)
  133. rpc.sendEnd(promise: nil)
  134. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  135. self.wait(for: [trailingMetadata], timeout: 1.0)
  136. }
  137. func testHeadersAreNormalizedForServerStreaming() throws {
  138. let trailingMetadata = self.expectation(description: "received trailing metadata")
  139. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  140. let rpc = self.client.expand(.with { $0.text = "foo" }, callOptions: options) {
  141. XCTFail("unexpected response: \($0)")
  142. }
  143. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  144. self.wait(for: [trailingMetadata], timeout: 1.0)
  145. }
  146. func testHeadersAreNormalizedForBidirectionalStreaming() throws {
  147. let trailingMetadata = self.expectation(description: "received trailing metadata")
  148. let options = CallOptions(customMetadata: ["CLIENT": "client"])
  149. let rpc = self.client.update(callOptions: options) {
  150. XCTFail("unexpected response: \($0)")
  151. }
  152. rpc.sendEnd(promise: nil)
  153. self.assertCustomMetadataIsLowercased(rpc.trailingMetadata, expectation: trailingMetadata)
  154. self.wait(for: [trailingMetadata], timeout: 1.0)
  155. }
  156. }