Functions.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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 FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseCore
  17. import FirebaseMessagingInterop
  18. import FirebaseSharedSwift
  19. import Foundation
  20. #if COCOAPODS
  21. import GTMSessionFetcher
  22. #else
  23. import GTMSessionFetcherCore
  24. #endif
  25. // Avoids exposing internal FirebaseCore APIs to Swift users.
  26. @_implementationOnly import FirebaseCoreExtension
  27. /// File specific constants.
  28. private enum Constants {
  29. static let appCheckTokenHeader = "X-Firebase-AppCheck"
  30. static let fcmTokenHeader = "Firebase-Instance-ID-Token"
  31. }
  32. /// Cross SDK constants.
  33. enum FunctionsConstants {
  34. static let defaultRegion = "us-central1"
  35. }
  36. /// `Functions` is the client for Cloud Functions for a Firebase project.
  37. @objc(FIRFunctions) open class Functions: NSObject {
  38. // MARK: - Private Variables
  39. /// The network client to use for http requests.
  40. private let fetcherService: GTMSessionFetcherService
  41. /// The projectID to use for all function references.
  42. private let projectID: String
  43. /// A serializer to encode/decode data and return values.
  44. private let serializer = FUNSerializer()
  45. /// A factory for getting the metadata to include with function calls.
  46. private let contextProvider: FunctionsContextProvider
  47. /// The custom domain to use for all functions references (optional).
  48. let customDomain: String?
  49. /// The region to use for all function references.
  50. let region: String
  51. // MARK: - Public APIs
  52. /// The current emulator origin, or `nil` if it is not set.
  53. open private(set) var emulatorOrigin: String?
  54. /// Creates a Cloud Functions client using the default or returns a pre-existing instance if it
  55. /// already exists.
  56. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  57. @objc(functions) open class func functions() -> Functions {
  58. return functions(
  59. app: FirebaseApp.app(),
  60. region: FunctionsConstants.defaultRegion,
  61. customDomain: nil
  62. )
  63. }
  64. /// Creates a Cloud Functions client with the given app, or returns a pre-existing
  65. /// instance if one already exists.
  66. /// - Parameter app: The app for the Firebase project.
  67. /// - Returns: A shared Functions instance initialized with the specified `FirebaseApp`.
  68. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  69. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  70. }
  71. /// Creates a Cloud Functions client with the default app and given region.
  72. /// - Parameter region: The region for the HTTP trigger, such as `us-central1`.
  73. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  74. /// custom region.
  75. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  76. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  77. }
  78. /// Creates a Cloud Functions client with the given custom domain or returns a pre-existing
  79. /// instance if one already exists.
  80. /// - Parameter customDomain: A custom domain for the HTTP trigger, such as
  81. /// "https://mydomain.com".
  82. /// - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a
  83. /// custom HTTP trigger domain.
  84. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  85. return functions(app: FirebaseApp.app(),
  86. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  87. }
  88. /// Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  89. /// instance if one already exists.
  90. /// - Parameters:
  91. /// - app: The app for the Firebase project.
  92. /// - region: The region for the HTTP trigger, such as `us-central1`.
  93. /// - Returns: An instance of `Functions` with a custom app and region.
  94. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  95. region: String) -> Functions {
  96. return functions(app: app, region: region, customDomain: nil)
  97. }
  98. /// Creates a Cloud Functions client with the given app and custom domain, or returns a
  99. /// pre-existing
  100. /// instance if one already exists.
  101. /// - Parameters:
  102. /// - app: The app for the Firebase project.
  103. /// - customDomain: A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  104. /// - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  105. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  106. customDomain: String)
  107. -> Functions {
  108. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  109. }
  110. /// Creates a reference to the Callable HTTPS trigger with the given name.
  111. /// - Parameter name: The name of the Callable HTTPS trigger.
  112. /// - Returns: A reference to a Callable HTTPS trigger.
  113. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  114. return HTTPSCallable(functions: self, name: name)
  115. }
  116. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  117. /// options.
  118. /// - Parameters:
  119. /// - name: The name of the Callable HTTPS trigger.
  120. /// - options: The options with which to customize the Callable HTTPS trigger.
  121. /// - Returns: A reference to a Callable HTTPS trigger.
  122. @objc(HTTPSCallableWithName:options:) public func httpsCallable(_ name: String,
  123. options: HTTPSCallableOptions)
  124. -> HTTPSCallable {
  125. return HTTPSCallable(functions: self, name: name, options: options)
  126. }
  127. /// Creates a reference to the Callable HTTPS trigger with the given name.
  128. /// - Parameter url: The URL of the Callable HTTPS trigger.
  129. /// - Returns: A reference to a Callable HTTPS trigger.
  130. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  131. return HTTPSCallable(functions: self, url: url)
  132. }
  133. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration
  134. /// options.
  135. /// - Parameters:
  136. /// - url: The URL of the Callable HTTPS trigger.
  137. /// - options: The options with which to customize the Callable HTTPS trigger.
  138. /// - Returns: A reference to a Callable HTTPS trigger.
  139. @objc(HTTPSCallableWithURL:options:) public func httpsCallable(_ url: URL,
  140. options: HTTPSCallableOptions)
  141. -> HTTPSCallable {
  142. return HTTPSCallable(functions: self, url: url, options: options)
  143. }
  144. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  145. /// `Encodable`
  146. /// request and the type of a `Decodable` response.
  147. /// - Parameters:
  148. /// - name: The name of the Callable HTTPS trigger
  149. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  150. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  151. /// - encoder: The encoder instance to use to perform encoding.
  152. /// - decoder: The decoder instance to use to perform decoding.
  153. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  154. /// Functions invocations.
  155. open func httpsCallable<Request: Encodable,
  156. Response: Decodable>(_ name: String,
  157. requestAs: Request.Type = Request.self,
  158. responseAs: Response.Type = Response.self,
  159. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  160. ),
  161. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  162. ))
  163. -> Callable<Request, Response> {
  164. return Callable(
  165. callable: httpsCallable(name),
  166. encoder: encoder,
  167. decoder: decoder
  168. )
  169. }
  170. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  171. /// `Encodable`
  172. /// request and the type of a `Decodable` response.
  173. /// - Parameters:
  174. /// - name: The name of the Callable HTTPS trigger
  175. /// - options: The options with which to customize the Callable HTTPS trigger.
  176. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  177. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  178. /// - encoder: The encoder instance to use to perform encoding.
  179. /// - decoder: The decoder instance to use to perform decoding.
  180. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  181. /// Functions invocations.
  182. open func httpsCallable<Request: Encodable,
  183. Response: Decodable>(_ name: String,
  184. options: HTTPSCallableOptions,
  185. requestAs: Request.Type = Request.self,
  186. responseAs: Response.Type = Response.self,
  187. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  188. ),
  189. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  190. ))
  191. -> Callable<Request, Response> {
  192. return Callable(
  193. callable: httpsCallable(name, options: options),
  194. encoder: encoder,
  195. decoder: decoder
  196. )
  197. }
  198. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  199. /// `Encodable`
  200. /// request and the type of a `Decodable` response.
  201. /// - Parameters:
  202. /// - url: The url of the Callable HTTPS trigger
  203. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  204. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  205. /// - encoder: The encoder instance to use to perform encoding.
  206. /// - decoder: The decoder instance to use to perform decoding.
  207. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  208. /// Functions invocations.
  209. open func httpsCallable<Request: Encodable,
  210. Response: Decodable>(_ url: URL,
  211. requestAs: Request.Type = Request.self,
  212. responseAs: Response.Type = Response.self,
  213. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  214. ),
  215. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  216. ))
  217. -> Callable<Request, Response> {
  218. return Callable(
  219. callable: httpsCallable(url),
  220. encoder: encoder,
  221. decoder: decoder
  222. )
  223. }
  224. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an
  225. /// `Encodable`
  226. /// request and the type of a `Decodable` response.
  227. /// - Parameters:
  228. /// - url: The url of the Callable HTTPS trigger
  229. /// - options: The options with which to customize the Callable HTTPS trigger.
  230. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  231. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  232. /// - encoder: The encoder instance to use to perform encoding.
  233. /// - decoder: The decoder instance to use to perform decoding.
  234. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud
  235. /// Functions invocations.
  236. open func httpsCallable<Request: Encodable,
  237. Response: Decodable>(_ url: URL,
  238. options: HTTPSCallableOptions,
  239. requestAs: Request.Type = Request.self,
  240. responseAs: Response.Type = Response.self,
  241. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  242. ),
  243. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  244. ))
  245. -> Callable<Request, Response> {
  246. return Callable(
  247. callable: httpsCallable(url, options: options),
  248. encoder: encoder,
  249. decoder: decoder
  250. )
  251. }
  252. /**
  253. * Changes this instance to point to a Cloud Functions emulator running locally.
  254. * See https://firebase.google.com/docs/functions/local-emulator
  255. * - Parameters:
  256. * - host: The host of the local emulator, such as "localhost".
  257. * - port: The port of the local emulator, for example 5005.
  258. */
  259. @objc open func useEmulator(withHost host: String, port: Int) {
  260. let prefix = host.hasPrefix("http") ? "" : "http://"
  261. let origin = String(format: "\(prefix)\(host):%li", port)
  262. emulatorOrigin = origin
  263. }
  264. // MARK: - Private Funcs (or Internal for tests)
  265. /// Solely used to have one precondition and one location where we fetch from the container. This
  266. /// previously was avoided due to default arguments but that doesn't work well with Obj-C
  267. /// compatibility.
  268. private class func functions(app: FirebaseApp?, region: String,
  269. customDomain: String?) -> Functions {
  270. precondition(app != nil,
  271. "`FirebaseApp.configure()` needs to be called before using Functions.")
  272. let provider = app!.container.instance(for: FunctionsProvider.self) as? FunctionsProvider
  273. return provider!.functions(for: app!,
  274. region: region,
  275. customDomain: customDomain,
  276. type: self)
  277. }
  278. @objc init(projectID: String,
  279. region: String,
  280. customDomain: String?,
  281. auth: AuthInterop?,
  282. messaging: MessagingInterop?,
  283. appCheck: AppCheckInterop?,
  284. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  285. self.projectID = projectID
  286. self.region = region
  287. self.customDomain = customDomain
  288. emulatorOrigin = nil
  289. contextProvider = FunctionsContextProvider(auth: auth,
  290. messaging: messaging,
  291. appCheck: appCheck)
  292. self.fetcherService = fetcherService
  293. }
  294. /// Using the component system for initialization.
  295. convenience init(app: FirebaseApp,
  296. region: String,
  297. customDomain: String?) {
  298. // TODO: These are not optionals, but they should be.
  299. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  300. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  301. in: app.container)
  302. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  303. in: app.container)
  304. guard let projectID = app.options.projectID else {
  305. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  306. }
  307. self.init(projectID: projectID,
  308. region: region,
  309. customDomain: customDomain,
  310. auth: auth,
  311. messaging: messaging,
  312. appCheck: appCheck)
  313. }
  314. func urlWithName(_ name: String) -> String {
  315. assert(!name.isEmpty, "Name cannot be empty")
  316. // Check if we're using the emulator
  317. if let emulatorOrigin {
  318. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  319. }
  320. // Check the custom domain.
  321. if let customDomain {
  322. return "\(customDomain)/\(name)"
  323. }
  324. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  325. }
  326. func callFunction(name: String,
  327. withObject data: Any?,
  328. options: HTTPSCallableOptions?,
  329. timeout: TimeInterval,
  330. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  331. // Get context first.
  332. contextProvider.getContext(options: options) { context, error in
  333. // Note: context is always non-nil since some checks could succeed, we're only failing if
  334. // there's an error.
  335. if let error {
  336. completion(.failure(error))
  337. } else {
  338. let url = self.urlWithName(name)
  339. self.callFunction(url: URL(string: url)!,
  340. withObject: data,
  341. options: options,
  342. timeout: timeout,
  343. context: context,
  344. completion: completion)
  345. }
  346. }
  347. }
  348. func callFunction(url: URL,
  349. withObject data: Any?,
  350. options: HTTPSCallableOptions?,
  351. timeout: TimeInterval,
  352. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  353. // Get context first.
  354. contextProvider.getContext(options: options) { context, error in
  355. // Note: context is always non-nil since some checks could succeed, we're only failing if
  356. // there's an error.
  357. if let error {
  358. completion(.failure(error))
  359. } else {
  360. self.callFunction(url: url,
  361. withObject: data,
  362. options: options,
  363. timeout: timeout,
  364. context: context,
  365. completion: completion)
  366. }
  367. }
  368. }
  369. private func callFunction(url: URL,
  370. withObject data: Any?,
  371. options: HTTPSCallableOptions?,
  372. timeout: TimeInterval,
  373. context: FunctionsContext,
  374. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  375. let request = URLRequest(url: url,
  376. cachePolicy: .useProtocolCachePolicy,
  377. timeoutInterval: timeout)
  378. let fetcher = fetcherService.fetcher(with: request)
  379. let body = NSMutableDictionary()
  380. // Encode the data in the body.
  381. var localData = data
  382. if data == nil {
  383. localData = NSNull()
  384. }
  385. // Force unwrap to match the old invalid argument thrown.
  386. let encoded = try! serializer.encode(localData!)
  387. body["data"] = encoded
  388. do {
  389. let payload = try JSONSerialization.data(withJSONObject: body)
  390. fetcher.bodyData = payload
  391. } catch {
  392. DispatchQueue.main.async {
  393. completion(.failure(error))
  394. }
  395. return
  396. }
  397. // Set the headers.
  398. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  399. if let authToken = context.authToken {
  400. let value = "Bearer \(authToken)"
  401. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  402. }
  403. if let fcmToken = context.fcmToken {
  404. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  405. }
  406. if options?.requireLimitedUseAppCheckTokens == true {
  407. if let appCheckToken = context.limitedUseAppCheckToken {
  408. fetcher.setRequestValue(
  409. appCheckToken,
  410. forHTTPHeaderField: Constants.appCheckTokenHeader
  411. )
  412. }
  413. } else if let appCheckToken = context.appCheckToken {
  414. fetcher.setRequestValue(
  415. appCheckToken,
  416. forHTTPHeaderField: Constants.appCheckTokenHeader
  417. )
  418. }
  419. // Override normal security rules if this is a local test.
  420. if emulatorOrigin != nil {
  421. fetcher.allowLocalhostRequest = true
  422. fetcher.allowedInsecureSchemes = ["http"]
  423. }
  424. fetcher.beginFetch { data, error in
  425. // If there was an HTTP error, convert it to our own error domain.
  426. var localError: Error?
  427. if let error = error as NSError? {
  428. if error.domain == kGTMSessionFetcherStatusDomain {
  429. localError = FunctionsErrorForResponse(
  430. status: error.code,
  431. body: data,
  432. serializer: self.serializer
  433. )
  434. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  435. localError = FunctionsErrorCode.deadlineExceeded.generatedError(userInfo: nil)
  436. }
  437. // If there was an error, report it to the user and stop.
  438. if let localError {
  439. completion(.failure(localError))
  440. } else {
  441. completion(.failure(error))
  442. }
  443. return
  444. } else {
  445. // If there wasn't an HTTP error, see if there was an error in the body.
  446. if let bodyError = FunctionsErrorForResponse(
  447. status: 200,
  448. body: data,
  449. serializer: self.serializer
  450. ) {
  451. completion(.failure(bodyError))
  452. return
  453. }
  454. }
  455. // Porting: this check is new since we didn't previously check if `data` was nil.
  456. guard let data = data else {
  457. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: nil)))
  458. return
  459. }
  460. let responseJSONObject: Any
  461. do {
  462. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  463. } catch {
  464. completion(.failure(error))
  465. return
  466. }
  467. guard let responseJSON = responseJSONObject as? NSDictionary else {
  468. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  469. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  470. return
  471. }
  472. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  473. let dataJSON = responseJSON["data"] ?? responseJSON["result"]
  474. guard let dataJSON = dataJSON as AnyObject? else {
  475. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  476. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  477. return
  478. }
  479. let resultData: Any?
  480. do {
  481. resultData = try self.serializer.decode(dataJSON)
  482. } catch {
  483. completion(.failure(error))
  484. return
  485. }
  486. // TODO: Force unwrap... gross
  487. let result = HTTPSCallableResult(data: resultData!)
  488. // TODO: This copied comment appears to be incorrect - it's impossible to have a nil callable result
  489. // If there's no result field, this will return nil, which is fine.
  490. completion(.success(result))
  491. }
  492. }
  493. }