FIRFunctions.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. // Copyright 2017 Google
  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 "Functions/FirebaseFunctions/Public/FirebaseFunctions/FIRFunctions.h"
  15. #import "Functions/FirebaseFunctions/FIRFunctions+Internal.h"
  16. #import "FirebaseAppCheck/Sources/Interop/FIRAppCheckInterop.h"
  17. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  18. #import "FirebaseMessaging/Sources/Interop/FIRMessagingInterop.h"
  19. #import "Interop/Auth/Public/FIRAuthInterop.h"
  20. #import "Functions/FirebaseFunctions/FIRHTTPSCallable+Internal.h"
  21. #import "Functions/FirebaseFunctions/FUNContext.h"
  22. #import "Functions/FirebaseFunctions/FUNError.h"
  23. #import "Functions/FirebaseFunctions/FUNSerializer.h"
  24. #import "Functions/FirebaseFunctions/FUNUsageValidation.h"
  25. #import "Functions/FirebaseFunctions/Public/FirebaseFunctions/FIRError.h"
  26. #import "Functions/FirebaseFunctions/Public/FirebaseFunctions/FIRHTTPSCallable.h"
  27. #if SWIFT_PACKAGE
  28. @import GTMSessionFetcherCore;
  29. #else
  30. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  31. #endif
  32. NS_ASSUME_NONNULL_BEGIN
  33. NSString *const kFUNAppCheckTokenHeader = @"X-Firebase-AppCheck";
  34. NSString *const kFUNFCMTokenHeader = @"Firebase-Instance-ID-Token";
  35. NSString *const kFUNDefaultRegion = @"us-central1";
  36. /// Empty protocol to register Functions as a component with Core.
  37. @protocol FIRFunctionsInstanceProvider
  38. @end
  39. @interface FIRFunctions () <FIRLibrary, FIRFunctionsInstanceProvider> {
  40. // The network client to use for http requests.
  41. GTMSessionFetcherService *_fetcherService;
  42. // The projectID to use for all function references.
  43. NSString *_projectID;
  44. // The region to use for all function references.
  45. NSString *_region;
  46. // The custom domain to use for all functions references (optional).
  47. NSString *_customDomain;
  48. // A serializer to encode/decode data and return values.
  49. FUNSerializer *_serializer;
  50. // A factory for getting the metadata to include with function calls.
  51. FUNContextProvider *_contextProvider;
  52. // For testing only. If this is set, functions will be called against it instead of Firebase.
  53. NSString *_emulatorOrigin;
  54. }
  55. // Re-declare this initializer here in order to attribute it as the designated initializer.
  56. - (instancetype)initWithProjectID:(NSString *)projectID
  57. region:(NSString *)region
  58. customDomain:(nullable NSString *)customDomain
  59. auth:(nullable id<FIRAuthInterop>)auth
  60. messaging:(nullable id<FIRMessagingInterop>)messaging
  61. appCheck:(nullable id<FIRAppCheckInterop>)appCheck
  62. fetcherService:(GTMSessionFetcherService *)fetcherService
  63. NS_DESIGNATED_INITIALIZER;
  64. @end
  65. @implementation FIRFunctions
  66. + (void)load {
  67. [FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-fun"];
  68. }
  69. + (NSArray<FIRComponent *> *)componentsToRegister {
  70. FIRComponentCreationBlock creationBlock =
  71. ^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
  72. *isCacheable = YES;
  73. return [self functionsForApp:container.app];
  74. };
  75. FIRDependency *auth = [FIRDependency dependencyWithProtocol:@protocol(FIRAuthInterop)
  76. isRequired:NO];
  77. FIRComponent *internalProvider =
  78. [FIRComponent componentWithProtocol:@protocol(FIRFunctionsInstanceProvider)
  79. instantiationTiming:FIRInstantiationTimingLazy
  80. dependencies:@[ auth ]
  81. creationBlock:creationBlock];
  82. return @[ internalProvider ];
  83. }
  84. + (instancetype)functions {
  85. return [[self alloc] initWithApp:[FIRApp defaultApp] region:kFUNDefaultRegion customDomain:nil];
  86. }
  87. + (instancetype)functionsForApp:(FIRApp *)app {
  88. return [[self alloc] initWithApp:app region:kFUNDefaultRegion customDomain:nil];
  89. }
  90. + (instancetype)functionsForRegion:(NSString *)region {
  91. return [[self alloc] initWithApp:[FIRApp defaultApp] region:region customDomain:nil];
  92. }
  93. + (instancetype)functionsForCustomDomain:(NSString *)customDomain {
  94. return [[self alloc] initWithApp:[FIRApp defaultApp]
  95. region:kFUNDefaultRegion
  96. customDomain:customDomain];
  97. }
  98. + (instancetype)functionsForApp:(FIRApp *)app region:(NSString *)region {
  99. return [[self alloc] initWithApp:app region:region customDomain:nil];
  100. }
  101. + (instancetype)functionsForApp:(FIRApp *)app customDomain:(NSString *)customDomain {
  102. return [[self alloc] initWithApp:app region:kFUNDefaultRegion customDomain:customDomain];
  103. }
  104. - (instancetype)initWithApp:(FIRApp *)app
  105. region:(NSString *)region
  106. customDomain:(nullable NSString *)customDomain {
  107. return [self initWithProjectID:app.options.projectID
  108. region:region
  109. customDomain:customDomain
  110. auth:FIR_COMPONENT(FIRAuthInterop, app.container)
  111. messaging:FIR_COMPONENT(FIRMessagingInterop, app.container)
  112. appCheck:FIR_COMPONENT(FIRAppCheckInterop, app.container)];
  113. }
  114. - (instancetype)initWithProjectID:(NSString *)projectID
  115. region:(NSString *)region
  116. customDomain:(nullable NSString *)customDomain
  117. auth:(nullable id<FIRAuthInterop>)auth
  118. messaging:(nullable id<FIRMessagingInterop>)messaging
  119. appCheck:(nullable id<FIRAppCheckInterop>)appCheck {
  120. return [self initWithProjectID:projectID
  121. region:region
  122. customDomain:customDomain
  123. auth:auth
  124. messaging:messaging
  125. appCheck:appCheck
  126. fetcherService:[[GTMSessionFetcherService alloc] init]];
  127. }
  128. - (instancetype)initWithProjectID:(NSString *)projectID
  129. region:(NSString *)region
  130. customDomain:(nullable NSString *)customDomain
  131. auth:(nullable id<FIRAuthInterop>)auth
  132. messaging:(nullable id<FIRMessagingInterop>)messaging
  133. appCheck:(nullable id<FIRAppCheckInterop>)appCheck
  134. fetcherService:(GTMSessionFetcherService *)fetcherService {
  135. self = [super init];
  136. if (self) {
  137. if (!region) {
  138. FUNThrowInvalidArgument(@"FIRFunctions region cannot be nil.");
  139. }
  140. _fetcherService = fetcherService;
  141. _projectID = [projectID copy];
  142. _region = [region copy];
  143. _customDomain = [customDomain copy];
  144. _serializer = [[FUNSerializer alloc] init];
  145. _contextProvider = [[FUNContextProvider alloc] initWithAuth:auth
  146. messaging:messaging
  147. appCheck:appCheck];
  148. _emulatorOrigin = nil;
  149. }
  150. return self;
  151. }
  152. - (void)useLocalhost {
  153. [self useEmulatorWithHost:@"localhost" port:5005];
  154. }
  155. - (void)useEmulatorWithHost:(NSString *)host port:(NSInteger)port {
  156. NSAssert(host.length > 0, @"Cannot connect to nil or empty host");
  157. NSString *prefix = [host hasPrefix:@"http"] ? @"" : @"http://";
  158. NSString *origin = [NSString stringWithFormat:@"%@%@:%li", prefix, host, (long)port];
  159. _emulatorOrigin = origin;
  160. }
  161. - (void)useFunctionsEmulatorOrigin:(NSString *)origin {
  162. _emulatorOrigin = origin;
  163. }
  164. - (NSString *)URLWithName:(NSString *)name {
  165. if (!name) {
  166. FUNThrowInvalidArgument(@"FIRFunctions function name cannot be nil.");
  167. }
  168. if (!_projectID) {
  169. FUNThrowInvalidArgument(@"FIRFunctions app projectID cannot be nil.");
  170. }
  171. if (_emulatorOrigin) {
  172. return [NSString stringWithFormat:@"%@/%@/%@/%@", _emulatorOrigin, _projectID, _region, name];
  173. }
  174. if (_customDomain) {
  175. return [NSString stringWithFormat:@"%@/%@", _customDomain, name];
  176. }
  177. return
  178. [NSString stringWithFormat:@"https://%@-%@.cloudfunctions.net/%@", _region, _projectID, name];
  179. }
  180. - (void)callFunction:(NSString *)name
  181. withObject:(nullable id)data
  182. timeout:(NSTimeInterval)timeout
  183. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  184. NSError *_Nullable error))completion {
  185. [_contextProvider getContext:^(FUNContext *context, NSError *_Nullable error) {
  186. if (error) {
  187. if (completion) {
  188. completion(nil, error);
  189. }
  190. return;
  191. }
  192. return [self callFunction:name
  193. withObject:data
  194. timeout:timeout
  195. context:context
  196. completion:completion];
  197. }];
  198. }
  199. - (void)callFunction:(NSString *)name
  200. withObject:(nullable id)data
  201. timeout:(NSTimeInterval)timeout
  202. context:(FUNContext *)context
  203. completion:(void (^)(FIRHTTPSCallableResult *_Nullable result,
  204. NSError *_Nullable error))completion {
  205. NSURL *url = [NSURL URLWithString:[self URLWithName:name]];
  206. NSURLRequest *request = [NSURLRequest requestWithURL:url
  207. cachePolicy:NSURLRequestUseProtocolCachePolicy
  208. timeoutInterval:timeout];
  209. GTMSessionFetcher *fetcher = [_fetcherService fetcherWithRequest:request];
  210. NSMutableDictionary *body = [NSMutableDictionary dictionary];
  211. // Encode the data in the body.
  212. if (!data) {
  213. data = [NSNull null];
  214. }
  215. id encoded = [_serializer encode:data];
  216. if (!encoded) {
  217. FUNThrowInvalidArgument(@"FIRFunctions data encoded as nil. This should not happen.");
  218. }
  219. body[@"data"] = encoded;
  220. NSError *error = nil;
  221. NSData *payload = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  222. if (error) {
  223. if (completion) {
  224. dispatch_async(dispatch_get_main_queue(), ^{
  225. completion(nil, error);
  226. });
  227. }
  228. return;
  229. }
  230. fetcher.bodyData = payload;
  231. // Set the headers.
  232. [fetcher setRequestValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  233. if (context.authToken) {
  234. NSString *value = [NSString stringWithFormat:@"Bearer %@", context.authToken];
  235. [fetcher setRequestValue:value forHTTPHeaderField:@"Authorization"];
  236. }
  237. if (context.FCMToken) {
  238. [fetcher setRequestValue:context.FCMToken forHTTPHeaderField:kFUNFCMTokenHeader];
  239. }
  240. if (context.appCheckToken) {
  241. [fetcher setRequestValue:context.appCheckToken forHTTPHeaderField:kFUNAppCheckTokenHeader];
  242. }
  243. // Override normal security rules if this is a local test.
  244. if (_emulatorOrigin) {
  245. fetcher.allowLocalhostRequest = YES;
  246. fetcher.allowedInsecureSchemes = @[ @"http" ];
  247. }
  248. FUNSerializer *serializer = _serializer;
  249. [fetcher beginFetchWithCompletionHandler:^(NSData *_Nullable data, NSError *_Nullable error) {
  250. // If there was an HTTP error, convert it to our own error domain.
  251. if (error) {
  252. if ([error.domain isEqualToString:kGTMSessionFetcherStatusDomain]) {
  253. error = FUNErrorForResponse(error.code, data, serializer);
  254. }
  255. if ([error.domain isEqualToString:NSURLErrorDomain]) {
  256. if (error.code == NSURLErrorTimedOut) {
  257. error = FUNErrorForCode(FIRFunctionsErrorCodeDeadlineExceeded);
  258. }
  259. }
  260. } else {
  261. // If there wasn't an HTTP error, see if there was an error in the body.
  262. error = FUNErrorForResponse(200, data, serializer);
  263. }
  264. // If there was an error, report it to the user and stop.
  265. if (error) {
  266. if (completion) {
  267. completion(nil, error);
  268. }
  269. return;
  270. }
  271. id responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
  272. if (error) {
  273. if (completion) {
  274. completion(nil, error);
  275. }
  276. return;
  277. }
  278. if (![responseJSON isKindOfClass:[NSDictionary class]]) {
  279. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response was not a dictionary."};
  280. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  281. code:FIRFunctionsErrorCodeInternal
  282. userInfo:userInfo];
  283. if (completion) {
  284. completion(nil, error);
  285. }
  286. return;
  287. }
  288. id dataJSON = responseJSON[@"data"];
  289. // TODO(klimt): Allow "result" instead of "data" for now, for backwards compatibility.
  290. if (!dataJSON) {
  291. dataJSON = responseJSON[@"result"];
  292. }
  293. if (!dataJSON) {
  294. NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"Response is missing data field."};
  295. error = [NSError errorWithDomain:FIRFunctionsErrorDomain
  296. code:FIRFunctionsErrorCodeInternal
  297. userInfo:userInfo];
  298. if (completion) {
  299. completion(nil, error);
  300. }
  301. return;
  302. }
  303. id resultData = [serializer decode:dataJSON error:&error];
  304. if (error) {
  305. if (completion) {
  306. completion(nil, error);
  307. }
  308. return;
  309. }
  310. id result = [[FIRHTTPSCallableResult alloc] initWithData:resultData];
  311. if (completion) {
  312. // If there's no result field, this will return nil, which is fine.
  313. completion(result, nil);
  314. }
  315. }];
  316. }
  317. - (FIRHTTPSCallable *)HTTPSCallableWithName:(NSString *)name {
  318. return [[FIRHTTPSCallable alloc] initWithFunctions:self name:name];
  319. }
  320. - (nullable NSString *)emulatorOrigin {
  321. return _emulatorOrigin;
  322. }
  323. @end
  324. NS_ASSUME_NONNULL_END