FIRInstallationsAPIService.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. /*
  2. * Copyright 2019 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseInstallations/Source/Library/InstallationsAPI/FIRInstallationsAPIService.h"
  17. #if __has_include(<FBLPromises/FBLPromises.h>)
  18. #import <FBLPromises/FBLPromises.h>
  19. #else
  20. #import "FBLPromises.h"
  21. #endif
  22. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  23. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsErrorUtil.h"
  24. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsHTTPError.h"
  25. #import "FirebaseInstallations/Source/Library/FIRInstallationsLogger.h"
  26. #import "FirebaseInstallations/Source/Library/InstallationsAPI/FIRInstallationsItem+RegisterInstallationAPI.h"
  27. NSString *const kFIRInstallationsAPIBaseURL = @"https://firebaseinstallations.googleapis.com";
  28. NSString *const kFIRInstallationsAPIKey = @"X-Goog-Api-Key";
  29. NSString *const kFIRInstallationsBundleId = @"X-Ios-Bundle-Identifier";
  30. NSString *const kFIRInstallationsIIDMigrationAuthHeader = @"x-goog-fis-ios-iid-migration-auth";
  31. NSString *const kFIRInstallationsHeartbeatKey = @"X-firebase-client";
  32. NS_ASSUME_NONNULL_BEGIN
  33. @interface FIRInstallationsURLSessionResponse : NSObject
  34. @property(nonatomic) NSHTTPURLResponse *HTTPResponse;
  35. @property(nonatomic) NSData *data;
  36. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data;
  37. @end
  38. @implementation FIRInstallationsURLSessionResponse
  39. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data {
  40. self = [super init];
  41. if (self) {
  42. _HTTPResponse = response;
  43. _data = data ?: [NSData data];
  44. }
  45. return self;
  46. }
  47. @end
  48. @interface FIRInstallationsAPIService ()
  49. @property(nonatomic, readonly) NSURLSession *URLSession;
  50. @property(nonatomic, readonly) NSString *APIKey;
  51. @property(nonatomic, readonly) NSString *projectID;
  52. @property(readonly) id<FIRHeartbeatLoggerProtocol> heartbeatLogger;
  53. @end
  54. NS_ASSUME_NONNULL_END
  55. @implementation FIRInstallationsAPIService
  56. - (instancetype)initWithAPIKey:(NSString *)APIKey
  57. projectID:(NSString *)projectID
  58. heartbeatLogger:(id<FIRHeartbeatLoggerProtocol>)heartbeatLogger {
  59. NSURLSession *URLSession = [NSURLSession
  60. sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
  61. return [self initWithURLSession:URLSession
  62. APIKey:APIKey
  63. projectID:projectID
  64. heartbeatLogger:heartbeatLogger];
  65. }
  66. /// The initializer for tests.
  67. - (instancetype)initWithURLSession:(NSURLSession *)URLSession
  68. APIKey:(NSString *)APIKey
  69. projectID:(NSString *)projectID
  70. heartbeatLogger:(id<FIRHeartbeatLoggerProtocol>)heartbeatLogger {
  71. self = [super init];
  72. if (self) {
  73. _URLSession = URLSession;
  74. _APIKey = [APIKey copy];
  75. _projectID = [projectID copy];
  76. _heartbeatLogger = heartbeatLogger;
  77. }
  78. return self;
  79. }
  80. #pragma mark - Public
  81. - (FBLPromise<FIRInstallationsItem *> *)registerInstallation:(FIRInstallationsItem *)installation {
  82. return [self validateInstallation:installation]
  83. .then(^id _Nullable(FIRInstallationsItem *_Nullable validInstallation) {
  84. return [self registerRequestWithInstallation:validInstallation];
  85. })
  86. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  87. return [self sendURLRequest:request];
  88. })
  89. .then(^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  90. return [self registeredInstallationWithInstallation:installation serverResponse:response];
  91. });
  92. }
  93. - (FBLPromise<FIRInstallationsItem *> *)refreshAuthTokenForInstallation:
  94. (FIRInstallationsItem *)installation {
  95. return [self authTokenRequestWithInstallation:installation]
  96. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  97. return [self sendURLRequest:request];
  98. })
  99. .then(^FBLPromise<FIRInstallationsStoredAuthToken *> *(
  100. FIRInstallationsURLSessionResponse *response) {
  101. return [self authTokenWithServerResponse:response];
  102. })
  103. .then(^FIRInstallationsItem *(FIRInstallationsStoredAuthToken *authToken) {
  104. FIRInstallationsItem *updatedInstallation = [installation copy];
  105. updatedInstallation.authToken = authToken;
  106. return updatedInstallation;
  107. });
  108. }
  109. - (FBLPromise<FIRInstallationsItem *> *)deleteInstallation:(FIRInstallationsItem *)installation {
  110. return [self deleteInstallationRequestWithInstallation:installation]
  111. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  112. return [self sendURLRequest:request];
  113. })
  114. .then(^id _Nullable(FIRInstallationsURLSessionResponse *_Nullable value) {
  115. // Return the original installation on success.
  116. return installation;
  117. });
  118. }
  119. #pragma mark - Register Installation
  120. - (FBLPromise<NSURLRequest *> *)registerRequestWithInstallation:
  121. (FIRInstallationsItem *)installation {
  122. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/",
  123. kFIRInstallationsAPIBaseURL, self.projectID];
  124. NSURL *URL = [NSURL URLWithString:URLString];
  125. NSDictionary *bodyDict = @{
  126. // `firebaseInstallationID` is validated before but let's make sure it is not `nil` one more
  127. // time to prevent a crash.
  128. @"fid" : installation.firebaseInstallationID ?: @"",
  129. @"authVersion" : @"FIS_v2",
  130. @"appId" : installation.appID,
  131. @"sdkVersion" : [self SDKVersion]
  132. };
  133. NSDictionary *headers;
  134. if (installation.IIDDefaultToken) {
  135. headers = @{kFIRInstallationsIIDMigrationAuthHeader : installation.IIDDefaultToken};
  136. }
  137. return [self requestWithURL:URL
  138. HTTPMethod:@"POST"
  139. bodyDict:bodyDict
  140. refreshToken:nil
  141. additionalHeaders:headers];
  142. }
  143. - (FBLPromise<FIRInstallationsItem *> *)
  144. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  145. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  146. return [FBLPromise do:^id {
  147. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  148. @"Parsing server response for %@.", response.HTTPResponse.URL);
  149. NSError *error;
  150. FIRInstallationsItem *registeredInstallation =
  151. [installation registeredInstallationWithJSONData:response.data
  152. date:[NSDate date]
  153. error:&error];
  154. if (registeredInstallation == nil) {
  155. FIRLogDebug(kFIRLoggerInstallations,
  156. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  157. @"Failed to parse FIRInstallationsItem: %@.", error);
  158. return error;
  159. }
  160. FIRLogDebug(kFIRLoggerInstallations,
  161. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  162. @"FIRInstallationsItem parsed successfully.");
  163. return registeredInstallation;
  164. }];
  165. }
  166. #pragma mark - Auth token
  167. - (FBLPromise<NSURLRequest *> *)authTokenRequestWithInstallation:
  168. (FIRInstallationsItem *)installation {
  169. NSString *URLString =
  170. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  171. kFIRInstallationsAPIBaseURL, self.projectID,
  172. installation.firebaseInstallationID];
  173. NSURL *URL = [NSURL URLWithString:URLString];
  174. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  175. return [self requestWithURL:URL
  176. HTTPMethod:@"POST"
  177. bodyDict:bodyDict
  178. refreshToken:installation.refreshToken];
  179. }
  180. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  181. (FIRInstallationsURLSessionResponse *)response {
  182. return [FBLPromise do:^id {
  183. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  184. @"Parsing server response for %@.", response.HTTPResponse.URL);
  185. NSError *error;
  186. FIRInstallationsStoredAuthToken *token =
  187. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  188. date:[NSDate date]
  189. error:&error];
  190. if (token == nil) {
  191. FIRLogDebug(kFIRLoggerInstallations,
  192. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  193. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  194. return error;
  195. }
  196. FIRLogDebug(kFIRLoggerInstallations,
  197. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  198. @"FIRInstallationsStoredAuthToken parsed successfully.");
  199. return token;
  200. }];
  201. }
  202. #pragma mark - Delete Installation
  203. - (FBLPromise<NSURLRequest *> *)deleteInstallationRequestWithInstallation:
  204. (FIRInstallationsItem *)installation {
  205. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  206. kFIRInstallationsAPIBaseURL, self.projectID,
  207. installation.firebaseInstallationID];
  208. NSURL *URL = [NSURL URLWithString:URLString];
  209. return [self requestWithURL:URL
  210. HTTPMethod:@"DELETE"
  211. bodyDict:@{}
  212. refreshToken:installation.refreshToken];
  213. }
  214. #pragma mark - URL Request
  215. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  216. HTTPMethod:(NSString *)HTTPMethod
  217. bodyDict:(NSDictionary *)bodyDict
  218. refreshToken:(nullable NSString *)refreshToken {
  219. return [self requestWithURL:requestURL
  220. HTTPMethod:HTTPMethod
  221. bodyDict:bodyDict
  222. refreshToken:refreshToken
  223. additionalHeaders:nil];
  224. }
  225. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  226. HTTPMethod:(NSString *)HTTPMethod
  227. bodyDict:(NSDictionary *)bodyDict
  228. refreshToken:(nullable NSString *)refreshToken
  229. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  230. additionalHeaders {
  231. return [FBLPromise
  232. onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  233. do:^id _Nullable {
  234. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  235. request.HTTPMethod = HTTPMethod;
  236. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  237. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  238. [request addValue:bundleIdentifier forHTTPHeaderField:kFIRInstallationsBundleId];
  239. [self setJSONHTTPBody:bodyDict forRequest:request];
  240. if (refreshToken) {
  241. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  242. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  243. }
  244. // Heartbeat Header.
  245. [request setValue:[self.heartbeatLogger headerValue]
  246. forHTTPHeaderField:kFIRInstallationsHeartbeatKey];
  247. [additionalHeaders
  248. enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull obj,
  249. BOOL *_Nonnull stop) {
  250. [request setValue:obj forHTTPHeaderField:key];
  251. }];
  252. return [request copy];
  253. }];
  254. }
  255. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)URLRequestPromise:(NSURLRequest *)request {
  256. return [[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  257. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeSendAPIRequest,
  258. @"Sending request: %@, body:%@, headers: %@.", request,
  259. [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
  260. request.allHTTPHeaderFields);
  261. [[self.URLSession
  262. dataTaskWithRequest:request
  263. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  264. NSError *_Nullable error) {
  265. if (error) {
  266. FIRLogDebug(kFIRLoggerInstallations,
  267. kFIRInstallationsMessageCodeAPIRequestNetworkError,
  268. @"Request failed: %@, error: %@.", request, error);
  269. reject(error);
  270. } else {
  271. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeAPIRequestResponse,
  272. @"Request response received: %@, error: %@, body: %@.", request, error,
  273. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  274. fulfill([[FIRInstallationsURLSessionResponse alloc]
  275. initWithResponse:(NSHTTPURLResponse *)response
  276. data:data]);
  277. }
  278. }] resume];
  279. }] then:^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  280. return [self validateHTTPResponseStatusCode:response];
  281. }];
  282. }
  283. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)validateHTTPResponseStatusCode:
  284. (FIRInstallationsURLSessionResponse *)response {
  285. NSInteger statusCode = response.HTTPResponse.statusCode;
  286. return [FBLPromise do:^id _Nullable {
  287. if (statusCode < 200 || statusCode >= 300) {
  288. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeUnexpectedAPIRequestResponse,
  289. @"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  290. [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]);
  291. return [FIRInstallationsErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  292. data:response.data];
  293. }
  294. return response;
  295. }];
  296. }
  297. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)sendURLRequest:(NSURLRequest *)request {
  298. return [FBLPromise attempts:1
  299. delay:1
  300. condition:^BOOL(NSInteger remainingAttempts, NSError *_Nonnull error) {
  301. return [FIRInstallationsErrorUtil isAPIError:error
  302. withHTTPCode:FIRInstallationsHTTPCodesServerInternalError];
  303. }
  304. retry:^id _Nullable {
  305. return [self URLRequestPromise:request];
  306. }];
  307. }
  308. - (NSString *)SDKVersion {
  309. return [NSString stringWithFormat:@"i:%@", FIRFirebaseVersion()];
  310. }
  311. #pragma mark - Validation
  312. - (FBLPromise<FIRInstallationsItem *> *)validateInstallation:(FIRInstallationsItem *)installation {
  313. FBLPromise<FIRInstallationsItem *> *result = [FBLPromise pendingPromise];
  314. NSError *validationError;
  315. if ([installation isValid:&validationError]) {
  316. [result fulfill:installation];
  317. } else {
  318. [result reject:validationError];
  319. }
  320. return result;
  321. }
  322. #pragma mark - JSON
  323. - (void)setJSONHTTPBody:(NSDictionary<NSString *, id> *)body
  324. forRequest:(NSMutableURLRequest *)request {
  325. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  326. NSError *error;
  327. NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  328. if (JSONData == nil) {
  329. // TODO: Log or return an error.
  330. }
  331. request.HTTPBody = JSONData;
  332. }
  333. @end