InterceptorsTests.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 RemoteAddressExistsInterceptor<Request, Response>: ServerInterceptor<Request, Response> {
  142. override func receive(
  143. _ part: GRPCServerRequestPart<Request>,
  144. context: ServerInterceptorContext<Request, Response>
  145. ) {
  146. XCTAssertNotNil(context.remoteAddress)
  147. super.receive(part, context: context)
  148. }
  149. }
  150. class NotReallyAuthServerInterceptor<Request: Message, Response: Message>:
  151. ServerInterceptor<Request, Response> {
  152. override func receive(
  153. _ part: GRPCServerRequestPart<Request>,
  154. context: ServerInterceptorContext<Request, Response>
  155. ) {
  156. switch part {
  157. case let .metadata(headers):
  158. if let auth = headers.first(name: "authorization"), auth == "Magic" {
  159. context.userInfo.magic = auth
  160. context.receive(part)
  161. } else {
  162. // Not auth'd. Fail the RPC.
  163. let status = GRPCStatus(code: .unauthenticated, message: "You need some magic auth!")
  164. let trailers = HPACKHeaders([("www-authenticate", "Magic")])
  165. context.send(.end(status, trailers), promise: nil)
  166. }
  167. case .message, .end:
  168. context.receive(part)
  169. }
  170. }
  171. }
  172. class HelloWorldServerInterceptorFactory: Helloworld_GreeterServerInterceptorFactoryProtocol {
  173. func makeSayHelloInterceptors(
  174. ) -> [ServerInterceptor<Helloworld_HelloRequest, Helloworld_HelloReply>] {
  175. return [RemoteAddressExistsInterceptor(), NotReallyAuthServerInterceptor()]
  176. }
  177. }
  178. class NotReallyAuthClientInterceptor<Request: Message, Response: Message>:
  179. ClientInterceptor<Request, Response> {
  180. private let client: Helloworld_GreeterClient
  181. private enum State {
  182. // We're trying the call, these are the parts we've sent so far.
  183. case trying([GRPCClientRequestPart<Request>])
  184. // We're retrying using this call.
  185. case retrying(Call<Request, Response>)
  186. }
  187. private var state: State = .trying([])
  188. init(client: Helloworld_GreeterClient) {
  189. self.client = client
  190. }
  191. override func cancel(
  192. promise: EventLoopPromise<Void>?,
  193. context: ClientInterceptorContext<Request, Response>
  194. ) {
  195. switch self.state {
  196. case .trying:
  197. context.cancel(promise: promise)
  198. case let .retrying(call):
  199. call.cancel(promise: promise)
  200. context.cancel(promise: nil)
  201. }
  202. }
  203. override func send(
  204. _ part: GRPCClientRequestPart<Request>,
  205. promise: EventLoopPromise<Void>?,
  206. context: ClientInterceptorContext<Request, Response>
  207. ) {
  208. switch self.state {
  209. case var .trying(parts):
  210. // Record the part, incase we need to retry.
  211. parts.append(part)
  212. self.state = .trying(parts)
  213. // Forward the request part.
  214. context.send(part, promise: promise)
  215. case let .retrying(call):
  216. // We're retrying, send the part to the retry call.
  217. call.send(part, promise: promise)
  218. }
  219. }
  220. override func receive(
  221. _ part: GRPCClientResponsePart<Response>,
  222. context: ClientInterceptorContext<Request, Response>
  223. ) {
  224. switch self.state {
  225. case var .trying(parts):
  226. switch part {
  227. // If 'authentication' fails this is the only part we expect, we can forward everything else.
  228. case let .end(status, trailers) where status.code == .unauthenticated:
  229. // We only know how to deal with magic.
  230. guard trailers.first(name: "www-authenticate") == "Magic" else {
  231. // We can't handle this, fail.
  232. context.receive(part)
  233. return
  234. }
  235. // We know how to handle this: make a new call.
  236. let call: Call<Request, Response> = self.client.channel.makeCall(
  237. path: context.path,
  238. type: context.type,
  239. callOptions: context.options,
  240. // We could grab interceptors from the client, but we don't need to.
  241. interceptors: []
  242. )
  243. // We're retying the call now.
  244. self.state = .retrying(call)
  245. // Invoke the call and redirect responses here.
  246. call.invoke(onError: context.errorCaught(_:), onResponsePart: context.receive(_:))
  247. // Parts must contain the metadata as the first item if we got that first response.
  248. if case var .some(.metadata(metadata)) = parts.first {
  249. metadata.replaceOrAdd(name: "authorization", value: "Magic")
  250. parts[0] = .metadata(metadata)
  251. }
  252. // Now replay any requests on the retry call.
  253. for part in parts {
  254. call.send(part, promise: nil)
  255. }
  256. default:
  257. context.receive(part)
  258. }
  259. case .retrying:
  260. // Ignore anything we receive on the original call.
  261. ()
  262. }
  263. }
  264. }
  265. class EchoReverseInterceptor: ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse> {
  266. override func send(
  267. _ part: GRPCClientRequestPart<Echo_EchoRequest>,
  268. promise: EventLoopPromise<Void>?,
  269. context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
  270. ) {
  271. switch part {
  272. case .message(var request, let metadata):
  273. request.text = String(request.text.reversed())
  274. context.send(.message(request, metadata), promise: promise)
  275. default:
  276. context.send(part, promise: promise)
  277. }
  278. }
  279. override func receive(
  280. _ part: GRPCClientResponsePart<Echo_EchoResponse>,
  281. context: ClientInterceptorContext<Echo_EchoRequest, Echo_EchoResponse>
  282. ) {
  283. switch part {
  284. case var .message(response):
  285. response.text = String(response.text.reversed())
  286. context.receive(.message(response))
  287. default:
  288. context.receive(part)
  289. }
  290. }
  291. }
  292. private class ReversingInterceptors: Echo_EchoClientInterceptorFactoryProtocol {
  293. // This interceptor is stateless, let's just share it.
  294. private let interceptors = [EchoReverseInterceptor()]
  295. func makeGetInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  296. return self.interceptors
  297. }
  298. func makeExpandInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  299. return self.interceptors
  300. }
  301. func makeCollectInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  302. return self.interceptors
  303. }
  304. func makeUpdateInterceptors() -> [ClientInterceptor<Echo_EchoRequest, Echo_EchoResponse>] {
  305. return self.interceptors
  306. }
  307. }
  308. private enum MagicKey: UserInfo.Key {
  309. typealias Value = String
  310. }
  311. extension UserInfo {
  312. fileprivate var magic: MagicKey.Value? {
  313. get {
  314. return self[MagicKey.self]
  315. }
  316. set {
  317. self[MagicKey.self] = newValue
  318. }
  319. }
  320. }