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 Foundation
  15. import FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. import FirebaseMessagingInterop
  19. import FirebaseSharedSwift
  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. internal enum FunctionsConstants {
  34. static let defaultRegion = "us-central1"
  35. }
  36. /**
  37. * `Functions` is the client for Cloud Functions for a Firebase project.
  38. */
  39. @objc(FIRFunctions) open class Functions: NSObject {
  40. // MARK: - Private Variables
  41. /// The network client to use for http requests.
  42. private let fetcherService: GTMSessionFetcherService
  43. /// The projectID to use for all function references.
  44. private let projectID: String
  45. /// A serializer to encode/decode data and return values.
  46. private let serializer = FUNSerializer()
  47. /// A factory for getting the metadata to include with function calls.
  48. private let contextProvider: FunctionsContextProvider
  49. /// The custom domain to use for all functions references (optional).
  50. internal let customDomain: String?
  51. /// The region to use for all function references.
  52. internal let region: String
  53. // MARK: - Public APIs
  54. /**
  55. * The current emulator origin, or `nil` if it is not set.
  56. */
  57. open private(set) var emulatorOrigin: String?
  58. /**
  59. * Creates a Cloud Functions client using the default or returns a pre-existing instance if it already exists.
  60. * - Returns: A shared Functions instance initialized with the default `FirebaseApp`.
  61. */
  62. @objc(functions) open class func functions() -> Functions {
  63. return functions(
  64. app: FirebaseApp.app(),
  65. region: FunctionsConstants.defaultRegion,
  66. customDomain: nil
  67. )
  68. }
  69. /**
  70. * Creates a Cloud Functions client with the given app, or returns a pre-existing
  71. * instance if one already exists.
  72. * - Parameter app The app for the Firebase project.
  73. * - Returns: A shared Functions instance initialized with the specified `FirebaseApp`.
  74. */
  75. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  76. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  77. }
  78. /**
  79. * Creates a Cloud Functions client with the default app and given region.
  80. * - Parameter region The region for the HTTP trigger, such as `us-central1`.
  81. * - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a custom region.
  82. */
  83. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  84. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  85. }
  86. /**
  87. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  88. * instance if one already exists.
  89. * - Parameter customDomain A custom domain for the HTTP trigger, such as "https://mydomain.com".
  90. * - Returns: A shared Functions instance initialized with the default `FirebaseApp` and a custom HTTP trigger domain.
  91. */
  92. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  93. return functions(app: FirebaseApp.app(),
  94. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  95. }
  96. /**
  97. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  98. * instance if one already exists.
  99. * - Parameters:
  100. * - app: The app for the Firebase project.
  101. * - region: The region for the HTTP trigger, such as `us-central1`.
  102. * - Returns: An instance of `Functions` with a custom app and region.
  103. */
  104. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  105. region: String) -> Functions {
  106. return functions(app: app, region: region, customDomain: nil)
  107. }
  108. /**
  109. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  110. * instance if one already exists.
  111. * - Parameters:
  112. * - app The app for the Firebase project.
  113. * - customDomain A custom domain for the HTTP trigger, such as `https://mydomain.com`.
  114. * - Returns: An instance of `Functions` with a custom app and HTTP trigger domain.
  115. */
  116. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  117. customDomain: String)
  118. -> Functions {
  119. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  120. }
  121. /// Creates a reference to the Callable HTTPS trigger with the given name.
  122. /// - Parameter name: The name of the Callable HTTPS trigger.
  123. /// - Returns: A reference to a Callable HTTPS trigger.
  124. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  125. return HTTPSCallable(functions: self, name: name)
  126. }
  127. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration options.
  128. /// - Parameters:
  129. /// - name: The name of the Callable HTTPS trigger.
  130. /// - options: The options with which to customize the Callable HTTPS trigger.
  131. /// - Returns: A reference to a Callable HTTPS trigger.
  132. @objc(HTTPSCallableWithName:options:) public func httpsCallable(_ name: String,
  133. options: HTTPSCallableOptions)
  134. -> HTTPSCallable {
  135. return HTTPSCallable(functions: self, name: name, options: options)
  136. }
  137. /// Creates a reference to the Callable HTTPS trigger with the given name.
  138. /// - Parameter url: The URL of the Callable HTTPS trigger.
  139. /// - Returns: A reference to a Callable HTTPS trigger.
  140. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  141. return HTTPSCallable(functions: self, url: url)
  142. }
  143. /// Creates a reference to the Callable HTTPS trigger with the given name and configuration options.
  144. /// - Parameters:
  145. /// - url: The URL of the Callable HTTPS trigger.
  146. /// - options: The options with which to customize the Callable HTTPS trigger.
  147. /// - Returns: A reference to a Callable HTTPS trigger.
  148. @objc(HTTPSCallableWithURL:options:) public func httpsCallable(_ url: URL,
  149. options: HTTPSCallableOptions)
  150. -> HTTPSCallable {
  151. return HTTPSCallable(functions: self, url: url, options: options)
  152. }
  153. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  154. /// request and the type of a `Decodable` response.
  155. /// - Parameters:
  156. /// - name: The name of the Callable HTTPS trigger
  157. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  158. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  159. /// - encoder: The encoder instance to use to perform encoding.
  160. /// - decoder: The decoder instance to use to perform decoding.
  161. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  162. open func httpsCallable<Request: Encodable,
  163. Response: Decodable>(_ name: String,
  164. requestAs: Request.Type = Request.self,
  165. responseAs: Response.Type = Response.self,
  166. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  167. ),
  168. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  169. ))
  170. -> Callable<Request, Response> {
  171. return Callable(
  172. callable: httpsCallable(name),
  173. encoder: encoder,
  174. decoder: decoder
  175. )
  176. }
  177. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  178. /// request and the type of a `Decodable` response.
  179. /// - Parameters:
  180. /// - name: The name of the Callable HTTPS trigger
  181. /// - options: The options with which to customize the Callable HTTPS trigger.
  182. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  183. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  184. /// - encoder: The encoder instance to use to perform encoding.
  185. /// - decoder: The decoder instance to use to perform decoding.
  186. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  187. open func httpsCallable<Request: Encodable,
  188. Response: Decodable>(_ name: String,
  189. options: HTTPSCallableOptions,
  190. requestAs: Request.Type = Request.self,
  191. responseAs: Response.Type = Response.self,
  192. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  193. ),
  194. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  195. ))
  196. -> Callable<Request, Response> {
  197. return Callable(
  198. callable: httpsCallable(name, options: options),
  199. encoder: encoder,
  200. decoder: decoder
  201. )
  202. }
  203. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  204. /// request and the type of a `Decodable` response.
  205. /// - Parameters:
  206. /// - url: The url of the Callable HTTPS trigger
  207. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  208. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  209. /// - encoder: The encoder instance to use to perform encoding.
  210. /// - decoder: The decoder instance to use to perform decoding.
  211. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  212. open func httpsCallable<Request: Encodable,
  213. Response: Decodable>(_ url: URL,
  214. requestAs: Request.Type = Request.self,
  215. responseAs: Response.Type = Response.self,
  216. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  217. ),
  218. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  219. ))
  220. -> Callable<Request, Response> {
  221. return Callable(
  222. callable: httpsCallable(url),
  223. encoder: encoder,
  224. decoder: decoder
  225. )
  226. }
  227. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  228. /// request and the type of a `Decodable` response.
  229. /// - Parameters:
  230. /// - url: The url of the Callable HTTPS trigger
  231. /// - options: The options with which to customize the Callable HTTPS trigger.
  232. /// - requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  233. /// - responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  234. /// - encoder: The encoder instance to use to perform encoding.
  235. /// - decoder: The decoder instance to use to perform decoding.
  236. /// - Returns: A reference to an HTTPS-callable Cloud Function that can be used to make Cloud Functions invocations.
  237. open func httpsCallable<Request: Encodable,
  238. Response: Decodable>(_ url: URL,
  239. options: HTTPSCallableOptions,
  240. requestAs: Request.Type = Request.self,
  241. responseAs: Response.Type = Response.self,
  242. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  243. ),
  244. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  245. ))
  246. -> Callable<Request, Response> {
  247. return Callable(
  248. callable: httpsCallable(url, options: options),
  249. encoder: encoder,
  250. decoder: decoder
  251. )
  252. }
  253. /**
  254. * Changes this instance to point to a Cloud Functions emulator running locally.
  255. * See https://firebase.google.com/docs/functions/local-emulator
  256. * - Parameters:
  257. * - host: The host of the local emulator, such as "localhost".
  258. * - port: The port of the local emulator, for example 5005.
  259. */
  260. @objc open func useEmulator(withHost host: String, port: Int) {
  261. let prefix = host.hasPrefix("http") ? "" : "http://"
  262. let origin = String(format: "\(prefix)\(host):%li", port)
  263. emulatorOrigin = origin
  264. }
  265. // MARK: - Private Funcs (or Internal for tests)
  266. /// Solely used to have one precondition and one location where we fetch from the container. This
  267. /// previously was avoided due to default arguments but that doesn't work well with Obj-C 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 internal 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. internal 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. internal 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 = emulatorOrigin {
  318. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  319. }
  320. // Check the custom domain.
  321. if let customDomain = customDomain {
  322. return "\(customDomain)/\(name)"
  323. }
  324. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  325. }
  326. internal 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 = 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. internal 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 = 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 = 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. }