Functions.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Copyright 2022 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import Foundation
  15. import FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. import FirebaseCoreExtension
  19. import FirebaseMessagingInterop
  20. import FirebaseSharedSwift
  21. #if COCOAPODS
  22. import GTMSessionFetcher
  23. #else
  24. import GTMSessionFetcherCore
  25. #endif
  26. /// File specific constants.
  27. private enum Constants {
  28. static let appCheckTokenHeader = "X-Firebase-AppCheck"
  29. static let fcmTokenHeader = "Firebase-Instance-ID-Token"
  30. }
  31. /// Cross SDK constants.
  32. internal enum FunctionsConstants {
  33. static let defaultRegion = "us-central1"
  34. }
  35. /**
  36. * `Functions` is the client for Cloud Functions for a Firebase project.
  37. */
  38. @objc(FIRFunctions) open class Functions: NSObject {
  39. // MARK: - Private Variables
  40. /// The network client to use for http requests.
  41. private let fetcherService: GTMSessionFetcherService
  42. // The projectID to use for all function references.
  43. private let projectID: String
  44. // A serializer to encode/decode data and return values.
  45. private let serializer = FUNSerializer()
  46. // A factory for getting the metadata to include with function calls.
  47. private let contextProvider: FunctionsContextProvider
  48. // The custom domain to use for all functions references (optional).
  49. internal let customDomain: String?
  50. // The region to use for all function references.
  51. internal let region: String
  52. // MARK: - Public APIs
  53. /**
  54. * The current emulator origin, or nil if it is not set.
  55. */
  56. open private(set) var emulatorOrigin: String?
  57. /**
  58. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  59. * instance if one already exists.
  60. * @param app The app for the Firebase project.
  61. * @param region The region for the http trigger, such as "us-central1".
  62. */
  63. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp = FirebaseApp.app()!,
  64. region: String) -> Functions {
  65. let provider = ComponentType<FunctionsProvider>.instance(for: FunctionsProvider.self,
  66. in: app.container)
  67. return provider.functions(for: app,
  68. region: region,
  69. customDomain: nil,
  70. type: self)
  71. }
  72. /**
  73. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  74. * instance if one already exists.
  75. * @param app The app for the Firebase project.
  76. * @param customDomain A custom domain for the http trigger, such as "https://mydomain.com".
  77. */
  78. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp = FirebaseApp
  79. .app()!,
  80. customDomain: String? = nil) -> Functions {
  81. let provider = app.container.instance(for: FunctionsProvider.self) as? FunctionsProvider
  82. return provider!.functions(for: app,
  83. region: FunctionsConstants.defaultRegion,
  84. customDomain: customDomain,
  85. type: self)
  86. }
  87. /**
  88. * Creates a reference to the Callable HTTPS trigger with the given name.
  89. * @param name The name of the Callable HTTPS trigger.
  90. */
  91. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  92. return HTTPSCallable(functions: self, name: name)
  93. }
  94. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  95. /// request and the type of a `Decodable` response.
  96. /// - Parameter name: The name of the Callable HTTPS trigger
  97. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  98. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  99. /// - Parameter encoder: The encoder instance to use to run the encoding.
  100. /// - Parameter decoder: The decoder instance to use to run the decoding.
  101. open func httpsCallable<Request: Encodable,
  102. Response: Decodable>(_ name: String,
  103. requestAs: Request.Type = Request.self,
  104. responseAs: Response.Type = Response.self,
  105. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  106. ),
  107. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  108. ))
  109. -> Callable<Request, Response> {
  110. return Callable(callable: httpsCallable(name), encoder: encoder, decoder: decoder)
  111. }
  112. /**
  113. * Changes this instance to point to a Cloud Functions emulator running locally.
  114. * See https://firebase.google.com/docs/functions/local-emulator
  115. * @param host The host of the local emulator, such as "localhost".
  116. * @param port The port of the local emulator, for example 5005.
  117. */
  118. @objc open func useEmulator(withHost host: String, port: Int) {
  119. let prefix = host.hasPrefix("http") ? "" : "http://"
  120. let origin = String(format: "\(prefix)\(host):%li", port)
  121. emulatorOrigin = origin
  122. }
  123. // MARK: - Public APIs only for Objective C
  124. /**
  125. * Creates a Cloud Functions client or returns a pre-existing instance if it already exists.
  126. */
  127. @objc(functions) open class func __functions() -> Functions {
  128. return functions()
  129. }
  130. /**
  131. * Creates a Cloud Functions client with the given app, or returns a pre-existing
  132. * instance if one already exists.
  133. * @param app The app for the Firebase project.
  134. */
  135. @objc(functionsForApp:) open class func __functionsForApp(app: FirebaseApp) -> Functions {
  136. return functions(app: app)
  137. }
  138. /**
  139. * Creates a Cloud Functions client with the default app and given region.
  140. * @param region The region for the http trigger, such as "us-central1".
  141. */
  142. @objc(functionsForRegion:) open class func __functionsForRegion(region: String) -> Functions {
  143. return functions(region: region)
  144. }
  145. /**
  146. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  147. * instance if one already exists.
  148. * @param customDomain A custom domain for the http trigger, such as "https://mydomain.com".
  149. */
  150. @objc(functionsForCustomDomain:) open class func __functionsForCustomDomain(customDomain: String?)
  151. -> Functions {
  152. return functions(customDomain: customDomain)
  153. }
  154. // MARK: - Private Funcs (or Internal for tests)
  155. @objc internal init(projectID: String,
  156. region: String,
  157. customDomain: String?,
  158. auth: AuthInterop?,
  159. messaging: MessagingInterop?,
  160. appCheck: AppCheckInterop?,
  161. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  162. self.projectID = projectID
  163. self.region = region
  164. self.customDomain = customDomain
  165. emulatorOrigin = nil
  166. contextProvider = FunctionsContextProvider(auth: auth,
  167. messaging: messaging,
  168. appCheck: appCheck)
  169. self.fetcherService = fetcherService
  170. }
  171. /// Using the component system for initialization.
  172. internal convenience init(app: FirebaseApp,
  173. region: String,
  174. customDomain: String?) {
  175. // TODO: These are not optionals, but they should be.
  176. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  177. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  178. in: app.container)
  179. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  180. in: app.container)
  181. guard let projectID = app.options.projectID else {
  182. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  183. }
  184. self.init(projectID: projectID,
  185. region: region,
  186. customDomain: customDomain,
  187. auth: auth,
  188. messaging: messaging,
  189. appCheck: appCheck)
  190. }
  191. internal func urlWithName(_ name: String) -> String {
  192. assert(!name.isEmpty, "Name cannot be empty")
  193. // Check if we're using the emulator
  194. if let emulatorOrigin = emulatorOrigin {
  195. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  196. }
  197. // Check the custom domain.
  198. if let customDomain = customDomain {
  199. return "\(customDomain)/\(name)"
  200. }
  201. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  202. }
  203. internal func callFunction(name: String,
  204. withObject data: Any?,
  205. timeout: TimeInterval,
  206. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  207. // Get context first.
  208. contextProvider.getContext { context, error in
  209. // Note: context is always non-nil since some checks could succeed, we're only failing if
  210. // there's an error.
  211. if let error = error {
  212. completion(.failure(error))
  213. } else {
  214. self.callFunction(name: name,
  215. withObject: data,
  216. timeout: timeout,
  217. context: context,
  218. completion: completion)
  219. }
  220. }
  221. }
  222. private func callFunction(name: String,
  223. withObject data: Any?,
  224. timeout: TimeInterval,
  225. context: FunctionsContext,
  226. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  227. let url = URL(string: urlWithName(name))!
  228. let request = URLRequest(url: url,
  229. cachePolicy: .useProtocolCachePolicy,
  230. timeoutInterval: timeout)
  231. let fetcher = fetcherService.fetcher(with: request)
  232. let body = NSMutableDictionary()
  233. // Encode the data in the body.
  234. var localData = data
  235. if data == nil {
  236. localData = NSNull()
  237. }
  238. // Force unwrap to match the old invalid argument thrown.
  239. let encoded = try! serializer.encode(localData!)
  240. body["data"] = encoded
  241. do {
  242. let payload = try JSONSerialization.data(withJSONObject: body)
  243. fetcher.bodyData = payload
  244. } catch {
  245. DispatchQueue.main.async {
  246. completion(.failure(error))
  247. }
  248. return
  249. }
  250. // Set the headers.
  251. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  252. if let authToken = context.authToken {
  253. let value = "Bearer \(authToken)"
  254. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  255. }
  256. if let fcmToken = context.fcmToken {
  257. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  258. }
  259. if let appCheckToken = context.appCheckToken {
  260. fetcher.setRequestValue(appCheckToken, forHTTPHeaderField: Constants.appCheckTokenHeader)
  261. }
  262. // Override normal security rules if this is a local test.
  263. if emulatorOrigin != nil {
  264. fetcher.allowLocalhostRequest = true
  265. fetcher.allowedInsecureSchemes = ["http"]
  266. }
  267. fetcher.beginFetch { data, error in
  268. // If there was an HTTP error, convert it to our own error domain.
  269. var localError: Error?
  270. if let error = error as NSError? {
  271. if error.domain == kGTMSessionFetcherStatusDomain {
  272. localError = FunctionsErrorForResponse(
  273. status: error.code,
  274. body: data,
  275. serializer: self.serializer
  276. )
  277. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  278. localError = FunctionsErrorCode.deadlineExceeded.generatedError(userInfo: nil)
  279. }
  280. // If there was an error, report it to the user and stop.
  281. if let localError = localError {
  282. completion(.failure(localError))
  283. } else {
  284. completion(.failure(error))
  285. }
  286. return
  287. } else {
  288. // If there wasn't an HTTP error, see if there was an error in the body.
  289. if let bodyError = FunctionsErrorForResponse(
  290. status: 200,
  291. body: data,
  292. serializer: self.serializer
  293. ) {
  294. completion(.failure(bodyError))
  295. return
  296. }
  297. }
  298. // Porting: this check is new since we didn't previously check if `data` was nil.
  299. guard let data = data else {
  300. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: nil)))
  301. return
  302. }
  303. let responseJSONObject: Any
  304. do {
  305. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  306. } catch {
  307. completion(.failure(error))
  308. return
  309. }
  310. guard let responseJSON = responseJSONObject as? NSDictionary else {
  311. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  312. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  313. return
  314. }
  315. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  316. let dataJSON = responseJSON["data"] ?? responseJSON["result"]
  317. guard let dataJSON = dataJSON as AnyObject? else {
  318. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  319. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  320. return
  321. }
  322. let resultData: Any?
  323. do {
  324. resultData = try self.serializer.decode(dataJSON)
  325. } catch {
  326. completion(.failure(error))
  327. return
  328. }
  329. // TODO: Force unwrap... gross
  330. let result = HTTPSCallableResult(data: resultData!)
  331. // TODO: This copied comment appears to be incorrect - it's impossible to have a nil callable result
  332. // If there's no result field, this will return nil, which is fine.
  333. completion(.success(result))
  334. }
  335. }
  336. }