Functions.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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 or returns a pre-existing instance if it already exists.
  59. */
  60. @objc(functions) open class func functions() -> Functions {
  61. return functions(
  62. app: FirebaseApp.app(),
  63. region: FunctionsConstants.defaultRegion,
  64. customDomain: nil
  65. )
  66. }
  67. /**
  68. * Creates a Cloud Functions client with the given app, or returns a pre-existing
  69. * instance if one already exists.
  70. * @param app The app for the Firebase project.
  71. */
  72. @objc(functionsForApp:) open class func functions(app: FirebaseApp) -> Functions {
  73. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: nil)
  74. }
  75. /**
  76. * Creates a Cloud Functions client with the default app and given region.
  77. * @param region The region for the http trigger, such as "us-central1".
  78. */
  79. @objc(functionsForRegion:) open class func functions(region: String) -> Functions {
  80. return functions(app: FirebaseApp.app(), region: region, customDomain: nil)
  81. }
  82. /**
  83. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  84. * instance if one already exists.
  85. * @param customDomain A custom domain for the http trigger, such as "https://mydomain.com".
  86. */
  87. @objc(functionsForCustomDomain:) open class func functions(customDomain: String) -> Functions {
  88. return functions(app: FirebaseApp.app(),
  89. region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  90. }
  91. /**
  92. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  93. * instance if one already exists.
  94. * @param app The app for the Firebase project.
  95. * @param region The region for the http trigger, such as "us-central1".
  96. */
  97. @objc(functionsForApp:region:) open class func functions(app: FirebaseApp,
  98. region: String) -> Functions {
  99. return functions(app: app, region: region, customDomain: nil)
  100. }
  101. /**
  102. * Creates a Cloud Functions client with the given app and region, or returns a pre-existing
  103. * instance if one already exists.
  104. * @param app The app for the Firebase project.
  105. * @param customDomain A custom domain for the http trigger, such as "https://mydomain.com".
  106. */
  107. @objc(functionsForApp:customDomain:) open class func functions(app: FirebaseApp,
  108. customDomain: String)
  109. -> Functions {
  110. return functions(app: app, region: FunctionsConstants.defaultRegion, customDomain: customDomain)
  111. }
  112. /**
  113. * Creates a reference to the Callable HTTPS trigger with the given name.
  114. * @param name The name of the Callable HTTPS trigger.
  115. */
  116. @objc(HTTPSCallableWithName:) open func httpsCallable(_ name: String) -> HTTPSCallable {
  117. return HTTPSCallable(functions: self, name: name)
  118. }
  119. @objc(HTTPSCallableWithURL:) open func httpsCallable(_ url: URL) -> HTTPSCallable {
  120. return HTTPSCallable(functions: self, url: url)
  121. }
  122. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  123. /// request and the type of a `Decodable` response.
  124. /// - Parameter name: The name of the Callable HTTPS trigger
  125. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  126. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  127. /// - Parameter encoder: The encoder instance to use to run the encoding.
  128. /// - Parameter decoder: The decoder instance to use to run the decoding.
  129. open func httpsCallable<Request: Encodable,
  130. Response: Decodable>(_ name: String,
  131. requestAs: Request.Type = Request.self,
  132. responseAs: Response.Type = Response.self,
  133. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  134. ),
  135. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  136. ))
  137. -> Callable<Request, Response> {
  138. return Callable(callable: httpsCallable(name), encoder: encoder, decoder: decoder)
  139. }
  140. /// Creates a reference to the Callable HTTPS trigger with the given name, the type of an `Encodable`
  141. /// request and the type of a `Decodable` response.
  142. /// - Parameter url: The url of the Callable HTTPS trigger
  143. /// - Parameter requestAs: The type of the `Encodable` entity to use for requests to this `Callable`
  144. /// - Parameter responseAs: The type of the `Decodable` entity to use for responses from this `Callable`
  145. /// - Parameter encoder: The encoder instance to use to run the encoding.
  146. /// - Parameter decoder: The decoder instance to use to run the decoding.
  147. open func httpsCallable<Request: Encodable,
  148. Response: Decodable>(_ url: URL,
  149. requestAs: Request.Type = Request.self,
  150. responseAs: Response.Type = Response.self,
  151. encoder: FirebaseDataEncoder = FirebaseDataEncoder(
  152. ),
  153. decoder: FirebaseDataDecoder = FirebaseDataDecoder(
  154. ))
  155. -> Callable<Request, Response> {
  156. return Callable(callable: httpsCallable(url), encoder: encoder, decoder: decoder)
  157. }
  158. /**
  159. * Changes this instance to point to a Cloud Functions emulator running locally.
  160. * See https://firebase.google.com/docs/functions/local-emulator
  161. * @param host The host of the local emulator, such as "localhost".
  162. * @param port The port of the local emulator, for example 5005.
  163. */
  164. @objc open func useEmulator(withHost host: String, port: Int) {
  165. let prefix = host.hasPrefix("http") ? "" : "http://"
  166. let origin = String(format: "\(prefix)\(host):%li", port)
  167. emulatorOrigin = origin
  168. }
  169. // MARK: - Private Funcs (or Internal for tests)
  170. /// Solely used to have one precondition and one location where we fetch from the container. This
  171. /// previously was avoided due to default arguments but that doesn't work well with Obj-C compatibility.
  172. private class func functions(app: FirebaseApp?, region: String,
  173. customDomain: String?) -> Functions {
  174. precondition(app != nil,
  175. "`FirebaseApp.configure()` needs to be called before using Functions.")
  176. let provider = app!.container.instance(for: FunctionsProvider.self) as? FunctionsProvider
  177. return provider!.functions(for: app!,
  178. region: region,
  179. customDomain: customDomain,
  180. type: self)
  181. }
  182. @objc internal init(projectID: String,
  183. region: String,
  184. customDomain: String?,
  185. auth: AuthInterop?,
  186. messaging: MessagingInterop?,
  187. appCheck: AppCheckInterop?,
  188. fetcherService: GTMSessionFetcherService = GTMSessionFetcherService()) {
  189. self.projectID = projectID
  190. self.region = region
  191. self.customDomain = customDomain
  192. emulatorOrigin = nil
  193. contextProvider = FunctionsContextProvider(auth: auth,
  194. messaging: messaging,
  195. appCheck: appCheck)
  196. self.fetcherService = fetcherService
  197. }
  198. /// Using the component system for initialization.
  199. internal convenience init(app: FirebaseApp,
  200. region: String,
  201. customDomain: String?) {
  202. // TODO: These are not optionals, but they should be.
  203. let auth = ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container)
  204. let messaging = ComponentType<MessagingInterop>.instance(for: MessagingInterop.self,
  205. in: app.container)
  206. let appCheck = ComponentType<AppCheckInterop>.instance(for: AppCheckInterop.self,
  207. in: app.container)
  208. guard let projectID = app.options.projectID else {
  209. fatalError("Firebase Functions requires the projectID to be set in the App's Options.")
  210. }
  211. self.init(projectID: projectID,
  212. region: region,
  213. customDomain: customDomain,
  214. auth: auth,
  215. messaging: messaging,
  216. appCheck: appCheck)
  217. }
  218. internal func urlWithName(_ name: String) -> String {
  219. assert(!name.isEmpty, "Name cannot be empty")
  220. // Check if we're using the emulator
  221. if let emulatorOrigin = emulatorOrigin {
  222. return "\(emulatorOrigin)/\(projectID)/\(region)/\(name)"
  223. }
  224. // Check the custom domain.
  225. if let customDomain = customDomain {
  226. return "\(customDomain)/\(name)"
  227. }
  228. return "https://\(region)-\(projectID).cloudfunctions.net/\(name)"
  229. }
  230. internal func callFunction(name: String,
  231. withObject data: Any?,
  232. timeout: TimeInterval,
  233. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  234. // Get context first.
  235. contextProvider.getContext { context, error in
  236. // Note: context is always non-nil since some checks could succeed, we're only failing if
  237. // there's an error.
  238. if let error = error {
  239. completion(.failure(error))
  240. } else {
  241. let url = self.urlWithName(name)
  242. self.callFunction(url: URL(string: url)!,
  243. withObject: data,
  244. timeout: timeout,
  245. context: context,
  246. completion: completion)
  247. }
  248. }
  249. }
  250. internal func callFunction(url: URL,
  251. withObject data: Any?,
  252. timeout: TimeInterval,
  253. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  254. // Get context first.
  255. contextProvider.getContext { context, error in
  256. // Note: context is always non-nil since some checks could succeed, we're only failing if
  257. // there's an error.
  258. if let error = error {
  259. completion(.failure(error))
  260. } else {
  261. self.callFunction(url: url,
  262. withObject: data,
  263. timeout: timeout,
  264. context: context,
  265. completion: completion)
  266. }
  267. }
  268. }
  269. private func callFunction(url: URL,
  270. withObject data: Any?,
  271. timeout: TimeInterval,
  272. context: FunctionsContext,
  273. completion: @escaping ((Result<HTTPSCallableResult, Error>) -> Void)) {
  274. let request = URLRequest(url: url,
  275. cachePolicy: .useProtocolCachePolicy,
  276. timeoutInterval: timeout)
  277. let fetcher = fetcherService.fetcher(with: request)
  278. let body = NSMutableDictionary()
  279. // Encode the data in the body.
  280. var localData = data
  281. if data == nil {
  282. localData = NSNull()
  283. }
  284. // Force unwrap to match the old invalid argument thrown.
  285. let encoded = try! serializer.encode(localData!)
  286. body["data"] = encoded
  287. do {
  288. let payload = try JSONSerialization.data(withJSONObject: body)
  289. fetcher.bodyData = payload
  290. } catch {
  291. DispatchQueue.main.async {
  292. completion(.failure(error))
  293. }
  294. return
  295. }
  296. // Set the headers.
  297. fetcher.setRequestValue("application/json", forHTTPHeaderField: "Content-Type")
  298. if let authToken = context.authToken {
  299. let value = "Bearer \(authToken)"
  300. fetcher.setRequestValue(value, forHTTPHeaderField: "Authorization")
  301. }
  302. if let fcmToken = context.fcmToken {
  303. fetcher.setRequestValue(fcmToken, forHTTPHeaderField: Constants.fcmTokenHeader)
  304. }
  305. if let appCheckToken = context.appCheckToken {
  306. fetcher.setRequestValue(appCheckToken, forHTTPHeaderField: Constants.appCheckTokenHeader)
  307. }
  308. // Override normal security rules if this is a local test.
  309. if emulatorOrigin != nil {
  310. fetcher.allowLocalhostRequest = true
  311. fetcher.allowedInsecureSchemes = ["http"]
  312. }
  313. fetcher.beginFetch { data, error in
  314. // If there was an HTTP error, convert it to our own error domain.
  315. var localError: Error?
  316. if let error = error as NSError? {
  317. if error.domain == kGTMSessionFetcherStatusDomain {
  318. localError = FunctionsErrorForResponse(
  319. status: error.code,
  320. body: data,
  321. serializer: self.serializer
  322. )
  323. } else if error.domain == NSURLErrorDomain, error.code == NSURLErrorTimedOut {
  324. localError = FunctionsErrorCode.deadlineExceeded.generatedError(userInfo: nil)
  325. }
  326. // If there was an error, report it to the user and stop.
  327. if let localError = localError {
  328. completion(.failure(localError))
  329. } else {
  330. completion(.failure(error))
  331. }
  332. return
  333. } else {
  334. // If there wasn't an HTTP error, see if there was an error in the body.
  335. if let bodyError = FunctionsErrorForResponse(
  336. status: 200,
  337. body: data,
  338. serializer: self.serializer
  339. ) {
  340. completion(.failure(bodyError))
  341. return
  342. }
  343. }
  344. // Porting: this check is new since we didn't previously check if `data` was nil.
  345. guard let data = data else {
  346. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: nil)))
  347. return
  348. }
  349. let responseJSONObject: Any
  350. do {
  351. responseJSONObject = try JSONSerialization.jsonObject(with: data)
  352. } catch {
  353. completion(.failure(error))
  354. return
  355. }
  356. guard let responseJSON = responseJSONObject as? NSDictionary else {
  357. let userInfo = [NSLocalizedDescriptionKey: "Response was not a dictionary."]
  358. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  359. return
  360. }
  361. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  362. let dataJSON = responseJSON["data"] ?? responseJSON["result"]
  363. guard let dataJSON = dataJSON as AnyObject? else {
  364. let userInfo = [NSLocalizedDescriptionKey: "Response is missing data field."]
  365. completion(.failure(FunctionsErrorCode.internal.generatedError(userInfo: userInfo)))
  366. return
  367. }
  368. let resultData: Any?
  369. do {
  370. resultData = try self.serializer.decode(dataJSON)
  371. } catch {
  372. completion(.failure(error))
  373. return
  374. }
  375. // TODO: Force unwrap... gross
  376. let result = HTTPSCallableResult(data: resultData!)
  377. // TODO: This copied comment appears to be incorrect - it's impossible to have a nil callable result
  378. // If there's no result field, this will return nil, which is fine.
  379. completion(.success(result))
  380. }
  381. }
  382. }