FIRFunctions.m 13 KB

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