InterceptorsTests.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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. import GRPC
  19. import HelloWorldModel
  20. import NIO
  21. import NIOHPACK
  22. import SwiftProtobuf
  23. import XCTest
  24. class InterceptorsTests: GRPCTestCase {
  25. private var group: EventLoopGroup!
  26. private var server: Server!
  27. private var connection: ClientConnection!
  28. private var echo: Echo_EchoClient!
  29. override func setUp() {
  30. super.setUp()
  31. self.group = MultiThreadedEventLoopGroup(numberOfThreads: 1)
  32. self.server = try! Server.insecure(group: self.group)
  33. .withServiceProviders([
  34. EchoProvider(),
  35. HelloWorldProvider(interceptors: HelloWorldServerInterceptorFactory()),
  36. ])
  37. .withLogger(self.serverLogger)
  38. .bind(host: "localhost", port: 0)
  39. .wait()
  40. self.connection = ClientConnection.insecure(group: self.group)
  41. .withBackgroundActivityLogger(self.clientLogger)
  42. .connect(host: "localhost", port: self.server.channel.localAddress!.port!)
  43. self.echo = Echo_EchoClient(
  44. channel: self.connection,
  45. defaultCallOptions: CallOptions(logger: self.clientLogger),
  46. interceptors: ReversingInterceptors()
  47. )
  48. }
  49. override func tearDown() {
  50. super.tearDown()
  51. XCTAssertNoThrow(try self.connection.close().wait())
  52. XCTAssertNoThrow(try self.server.close().wait())
  53. XCTAssertNoThrow(try self.group.syncShutdownGracefully())
  54. }
  55. func testEcho() {
  56. let get = self.echo.get(.with { $0.text = "hello" })
  57. assertThat(try get.response.wait(), .is(.with { $0.text = "hello :teg ohce tfiwS" }))
  58. assertThat(try get.status.wait(), .hasCode(.ok))
  59. }
  60. func testCollect() {
  61. let collect = self.echo.collect()
  62. collect.sendMessage(.with { $0.text = "1 2" }, promise: nil)
  63. collect.sendMessage(.with { $0.text = "3 4" }, promise: nil)
  64. collect.sendEnd(promise: nil)
  65. assertThat(try collect.response.wait(), .is(.with { $0.text = "3 4 1 2 :tcelloc ohce tfiwS" }))
  66. assertThat(try collect.status.wait(), .hasCode(.ok))
  67. }
  68. func testExpand() {
  69. let expand = self.echo.expand(.with { $0.text = "hello" }) { response in
  70. // Expand splits on spaces, so we only expect one response.
  71. assertThat(response, .is(.with { $0.text = "hello :)0( dnapxe ohce tfiwS" }))
  72. }
  73. assertThat(try expand.status.wait(), .hasCode(.ok))
  74. }
  75. func testUpdate() {
  76. let update = self.echo.update { response in
  77. // We'll just send the one message, so only expect one response.
  78. assertThat(response, .is(.with { $0.text = "hello :)0( etadpu ohce tfiwS" }))
  79. }
  80. update.sendMessage(.with { $0.text = "hello" }, promise: nil)
  81. update.sendEnd(promise: nil)
  82. assertThat(try update.status.wait(), .hasCode(.ok))
  83. }
  84. func testSayHello() {
  85. let greeter = Helloworld_GreeterClient(
  86. channel: self.connection,
  87. defaultCallOptions: CallOptions(logger: self.clientLogger)
  88. )
  89. // Make a call without interceptors.
  90. let notAuthed = greeter.sayHello(.with { $0.name = "World" })
  91. assertThat(try notAuthed.response.wait(), .throws())
  92. assertThat(
  93. try notAuthed.trailingMetadata.wait(),
  94. .contains("www-authenticate", ["Magic"])
  95. )
  96. assertThat(try notAuthed.status.wait(), .hasCode(.unauthenticated))
  97. // Add an interceptor factory.
  98. greeter.interceptors = HelloWorldClientInterceptorFactory(client: greeter)
  99. // Make sure we break the reference cycle.
  100. defer {
  101. greeter.interceptors = nil
  102. }
  103. // Try again with the not-really-auth interceptor:
  104. let hello = greeter.sayHello(.with { $0.name = "PanCakes" })
  105. assertThat(
  106. try hello.response.map { $0.message }.wait(),
  107. .is(.equalTo("Hello, PanCakes, you're authorized!"))
  108. )
  109. assertThat(try hello.status.wait(), .hasCode(.ok))
  110. }
  111. }
  112. // MARK: - Helpers
  113. class HelloWorldProvider: Helloworld_GreeterProvider {
  114. var interceptors: Helloworld_GreeterServerInterceptorFactoryProtocol?
  115. init(interceptors: Helloworld_GreeterServerInterceptorFactoryProtocol? = nil) {
  116. self.interceptors = interceptors
  117. }
  118. func sayHello(
  119. request: Helloworld_HelloRequest,
  120. context: StatusOnlyCallContext
  121. ) -> EventLoopFuture<Helloworld_HelloReply> {
  122. // Since we're auth'd, the 'userInfo' should have some magic set.
  123. assertThat(context.userInfo.magic, .is("Magic"))
  124. let response = Helloworld_HelloReply.with {
  125. $0.message = "Hello, \(request.name), you're authorized!"
  126. }
  127. return context.eventLoop.makeSucceededFuture(response)
  128. }
  129. }
  130. private class HelloWorldClientInterceptorFactory:
  131. Helloworld_GreeterClientInterceptorFactoryProtocol {
  132. var client: Helloworld_GreeterClient
  133. init(client: Helloworld_GreeterClient) {
  134. self.client = client
  135. }
  136. func makeSayHelloInterceptors(
  137. ) -> [ClientInterceptor<Helloworld_HelloRequest, Helloworld_HelloReply>] {
  138. return [NotReallyAuthClientInterceptor(client: self.client)]
  139. }
  140. }
  141. class NotReallyAuthServerInterceptor<Request: Message, Response: Message>:
  142. ServerInterceptor<Request, Response> {
  143. override func receive(
  144. _ part: GRPCServerRequestPart<Request>,
  145. context: ServerInterceptorContext<Request, Response>
  146. ) {
  147. switch part {
  148. case let .metadata(headers):
  149. if let auth = headers.first(name: "authorization"), auth == "Magic" {
  150. context.userInfo.magic = auth
  151. context.receive(part)
  152. } else {
  153. // Not auth'd. Fail the RPC.
  154. let status = GRPCStatus(code: .unauthenticated, message: "You need some magic auth!")
  155. let trailers = HPACKHeaders([("www-authenticate", "Magic")])
  156. context.send(.end(status, trailers), promise: nil)
  157. }
  158. case .message, .end:
  159. context.receive(part)
  160. }
  161. }
  162. }
  163. class HelloWorldServerInterceptorFactory: Helloworld_GreeterServerInterceptorFactoryProtocol {
  164. func makeSayHelloInterceptors(
  165. ) -> [ServerInterceptor<Helloworld_HelloRequest, Helloworld_HelloReply>] {
  166. return [NotReallyAuthServerInterceptor()]
  167. }
  168. }
  169. class NotReallyAuthClientInterceptor<Request: Message, Response: Message>:
  170. ClientInterceptor<Request, Response> {
  171. private let client: Helloworld_GreeterClient
  172. private enum State {
  173. // We're trying the call, these are the parts we've sent so far.
  174. case trying([GRPCClientRequestPart<Request>])
  175. // We're retrying using this call.
  176. case retrying(Call<Request, Response>)
  177. }
  178. private var state: State = .trying([])
  179. init(client: Helloworld_GreeterClient) {
  180. self.client = client
  181. }
  182. override func cancel(
  183. promise: EventLoopPromise<Void>?,
  184. context: ClientInterceptorContext<Request, Response>
  185. ) {
  186. switch self.state {
  187. case .trying:
  188. context.cancel(promise: promise)
  189. case let .retrying(call):
  190. call.cancel(promise: promise)
  191. context.cancel(promise: nil)
  192. }
  193. }
  194. override func send(
  195. _ part: GRPCClientRequestPart<Request>,
  196. promise: EventLoopPromise<Void>?,
  197. context: ClientInterceptorContext<Request, Response>
  198. ) {
  199. switch self.state {
  200. case var .trying(parts):
  201. // Record the part, incase we need to retry.
  202. parts.append(part)
  203. self.state = .trying(parts)
  204. // Forward the request part.
  205. context.send(part, promise: promise)
  206. case let .retrying(call):
  207. // We're retrying, send the part to the retry call.
  208. call.send(part, promise: promise)
  209. }
  210. }
  211. override func receive(
  212. _ part: GRPCClientResponsePart<Response>,
  213. context: ClientInterceptorContext<Request, Response>
  214. ) {
  215. switch self.state {
  216. case var .trying(parts):
  217. switch part {
  218. // If 'authentication' fails this is the only part we expect, we can forward everything else.
  219. case let .end(status, trailers) where status.code == .unauthenticated:
  220. // We only know how to deal with magic.
  221. guard trailers.first(name: "www-authenticate") == "Magic" else {
  222. // We can't handle this, fail.
  223. context.receive(part)
  224. return
  225. }
  226. // We know how to handle this: make a new call.
  227. let call: Call<Request, Response> = self.client.channel.makeCall(
  228. path: context.path,
  229. type: context.type,
  230. callOptions: context.options,
  231. // We could grab interceptors from the client, but we don't need to.
  232. interceptors: []
  233. )
  234. // We're retying the call now.
  235. self.state = .retrying(call)
  236. // Invoke the call and redirect responses here.
  237. call.invoke(onError: context.errorCaught(_:), onResponsePart: context.receive(_:))
  238. // Parts must contain the metadata as the first item if we got that first response.
  239. if case var .some(.metadata(metadata)) = parts.first {
  240. metadata.replaceOrAdd(name: "authorization", value: "Magic")
  241. parts[0] = .metadata(metadata)
  242. }
  243. // Now replay any requests on the retry call.
  244. for part in parts {
  245. call.send(part, promise: nil)
  246. }
  247. default:
  248. context.receive(part)
  249. }
  250. case .retrying:
  251. // Ignore anything we receive on the original call.
  252. ()
  253. }
  254. }
  255. }
  256. class EchoReverseInterceptor: ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> {
  257. override func send(
  258. _ part: GRPCClientRequestPart<Echo_EchoRequest>,
  259. promise: EventLoopPromise<Void>?,
  260. context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
  261. ) {
  262. switch part {
  263. case .message(var request, let metadata):
  264. request.text = String(request.text.reversed())
  265. context.send(.message(request, metadata), promise: promise)
  266. default:
  267. context.send(part, promise: promise)
  268. }
  269. }
  270. override func receive(
  271. _ part: GRPCClientResponsePart<Echo_EchoResponse>,
  272. context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
  273. ) {
  274. switch part {
  275. case var .message(response):
  276. response.text = String(response.text.reversed())
  277. context.receive(.message(response))
  278. default:
  279. context.receive(part)
  280. }
  281. }
  282. }
  283. private class ReversingInterceptors: Echo_EchoClientInterceptorFactoryProtocol {
  284. // This interceptor is stateless, let's just share it.
  285. private let interceptors = [EchoReverseInterceptor()]
  286. func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  287. return self.interceptors
  288. }
  289. func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  290. return self.interceptors
  291. }
  292. func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  293. return self.interceptors
  294. }
  295. func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  296. return self.interceptors
  297. }
  298. }
  299. private enum MagicKey: UserInfo.Key {
  300. typealias Value = String
  301. }
  302. extension UserInfo {
  303. fileprivate var magic: MagicKey.Value? {
  304. get {
  305. return self[MagicKey.self]
  306. }
  307. set {
  308. self[MagicKey.self] = newValue
  309. }
  310. }
  311. }