InterceptorsTests.swift 12 KB

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