InterceptorsTests.swift 12 KB

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