FIRInstallationsAPIService.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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/Sources/Private/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-log-type";
  32. NSString *const kFIRInstallationsHeartbeatTag = @"fire-installations";
  33. NSString *const kFIRInstallationsUserAgentKey = @"X-firebase-client";
  34. NS_ASSUME_NONNULL_BEGIN
  35. @interface FIRInstallationsURLSessionResponse : NSObject
  36. @property(nonatomic) NSHTTPURLResponse *HTTPResponse;
  37. @property(nonatomic) NSData *data;
  38. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data;
  39. @end
  40. @implementation FIRInstallationsURLSessionResponse
  41. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data {
  42. self = [super init];
  43. if (self) {
  44. _HTTPResponse = response;
  45. _data = data ?: [NSData data];
  46. }
  47. return self;
  48. }
  49. @end
  50. @interface FIRInstallationsAPIService ()
  51. @property(nonatomic, readonly) NSURLSession *URLSession;
  52. @property(nonatomic, readonly) NSString *APIKey;
  53. @property(nonatomic, readonly) NSString *projectID;
  54. @end
  55. NS_ASSUME_NONNULL_END
  56. @implementation FIRInstallationsAPIService
  57. - (instancetype)initWithAPIKey:(NSString *)APIKey projectID:(NSString *)projectID {
  58. NSURLSession *URLSession = [NSURLSession
  59. sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
  60. return [self initWithURLSession:URLSession APIKey:APIKey projectID:projectID];
  61. }
  62. /// The initializer for tests.
  63. - (instancetype)initWithURLSession:(NSURLSession *)URLSession
  64. APIKey:(NSString *)APIKey
  65. projectID:(NSString *)projectID {
  66. self = [super init];
  67. if (self) {
  68. _URLSession = URLSession;
  69. _APIKey = [APIKey copy];
  70. _projectID = [projectID copy];
  71. }
  72. return self;
  73. }
  74. #pragma mark - Public
  75. - (FBLPromise<FIRInstallationsItem *> *)registerInstallation:(FIRInstallationsItem *)installation {
  76. return [self validateInstallation:installation]
  77. .then(^id _Nullable(FIRInstallationsItem *_Nullable validInstallation) {
  78. return [self registerRequestWithInstallation:validInstallation];
  79. })
  80. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  81. return [self sendURLRequest:request];
  82. })
  83. .then(^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  84. return [self registeredInstallationWithInstallation:installation serverResponse:response];
  85. });
  86. }
  87. - (FBLPromise<FIRInstallationsItem *> *)refreshAuthTokenForInstallation:
  88. (FIRInstallationsItem *)installation {
  89. return [self authTokenRequestWithInstallation:installation]
  90. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  91. return [self sendURLRequest:request];
  92. })
  93. .then(^FBLPromise<FIRInstallationsStoredAuthToken *> *(
  94. FIRInstallationsURLSessionResponse *response) {
  95. return [self authTokenWithServerResponse:response];
  96. })
  97. .then(^FIRInstallationsItem *(FIRInstallationsStoredAuthToken *authToken) {
  98. FIRInstallationsItem *updatedInstallation = [installation copy];
  99. updatedInstallation.authToken = authToken;
  100. return updatedInstallation;
  101. });
  102. }
  103. - (FBLPromise<FIRInstallationsItem *> *)deleteInstallation:(FIRInstallationsItem *)installation {
  104. return [self deleteInstallationRequestWithInstallation:installation]
  105. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  106. return [self sendURLRequest:request];
  107. })
  108. .then(^id _Nullable(FIRInstallationsURLSessionResponse *_Nullable value) {
  109. // Return the original installation on success.
  110. return installation;
  111. });
  112. }
  113. #pragma mark - Register Installation
  114. - (FBLPromise<NSURLRequest *> *)registerRequestWithInstallation:
  115. (FIRInstallationsItem *)installation {
  116. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/",
  117. kFIRInstallationsAPIBaseURL, self.projectID];
  118. NSURL *URL = [NSURL URLWithString:URLString];
  119. NSDictionary *bodyDict = @{
  120. // `firebaseInstallationID` is validated before but let's make sure it is not `nil` one more
  121. // time to prevent a crash.
  122. @"fid" : installation.firebaseInstallationID ?: @"",
  123. @"authVersion" : @"FIS_v2",
  124. @"appId" : installation.appID,
  125. @"sdkVersion" : [self SDKVersion]
  126. };
  127. NSDictionary *headers;
  128. if (installation.IIDDefaultToken) {
  129. headers = @{kFIRInstallationsIIDMigrationAuthHeader : installation.IIDDefaultToken};
  130. }
  131. return [self requestWithURL:URL
  132. HTTPMethod:@"POST"
  133. bodyDict:bodyDict
  134. refreshToken:nil
  135. additionalHeaders:headers];
  136. }
  137. - (FBLPromise<FIRInstallationsItem *> *)
  138. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  139. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  140. return [FBLPromise do:^id {
  141. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  142. @"Parsing server response for %@.", response.HTTPResponse.URL);
  143. NSError *error;
  144. FIRInstallationsItem *registeredInstallation =
  145. [installation registeredInstallationWithJSONData:response.data
  146. date:[NSDate date]
  147. error:&error];
  148. if (registeredInstallation == nil) {
  149. FIRLogDebug(kFIRLoggerInstallations,
  150. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  151. @"Failed to parse FIRInstallationsItem: %@.", error);
  152. return error;
  153. }
  154. FIRLogDebug(kFIRLoggerInstallations,
  155. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  156. @"FIRInstallationsItem parsed successfully.");
  157. return registeredInstallation;
  158. }];
  159. }
  160. #pragma mark - Auth token
  161. - (FBLPromise<NSURLRequest *> *)authTokenRequestWithInstallation:
  162. (FIRInstallationsItem *)installation {
  163. NSString *URLString =
  164. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  165. kFIRInstallationsAPIBaseURL, self.projectID,
  166. installation.firebaseInstallationID];
  167. NSURL *URL = [NSURL URLWithString:URLString];
  168. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  169. return [self requestWithURL:URL
  170. HTTPMethod:@"POST"
  171. bodyDict:bodyDict
  172. refreshToken:installation.refreshToken];
  173. }
  174. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  175. (FIRInstallationsURLSessionResponse *)response {
  176. return [FBLPromise do:^id {
  177. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  178. @"Parsing server response for %@.", response.HTTPResponse.URL);
  179. NSError *error;
  180. FIRInstallationsStoredAuthToken *token =
  181. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  182. date:[NSDate date]
  183. error:&error];
  184. if (token == nil) {
  185. FIRLogDebug(kFIRLoggerInstallations,
  186. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  187. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  188. return error;
  189. }
  190. FIRLogDebug(kFIRLoggerInstallations,
  191. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  192. @"FIRInstallationsStoredAuthToken parsed successfully.");
  193. return token;
  194. }];
  195. }
  196. #pragma mark - Delete Installation
  197. - (FBLPromise<NSURLRequest *> *)deleteInstallationRequestWithInstallation:
  198. (FIRInstallationsItem *)installation {
  199. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  200. kFIRInstallationsAPIBaseURL, self.projectID,
  201. installation.firebaseInstallationID];
  202. NSURL *URL = [NSURL URLWithString:URLString];
  203. return [self requestWithURL:URL
  204. HTTPMethod:@"DELETE"
  205. bodyDict:@{}
  206. refreshToken:installation.refreshToken];
  207. }
  208. #pragma mark - URL Request
  209. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  210. HTTPMethod:(NSString *)HTTPMethod
  211. bodyDict:(NSDictionary *)bodyDict
  212. refreshToken:(nullable NSString *)refreshToken {
  213. return [self requestWithURL:requestURL
  214. HTTPMethod:HTTPMethod
  215. bodyDict:bodyDict
  216. refreshToken:refreshToken
  217. additionalHeaders:nil];
  218. }
  219. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  220. HTTPMethod:(NSString *)HTTPMethod
  221. bodyDict:(NSDictionary *)bodyDict
  222. refreshToken:(nullable NSString *)refreshToken
  223. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  224. additionalHeaders {
  225. return [FBLPromise
  226. onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  227. do:^id _Nullable {
  228. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  229. request.HTTPMethod = HTTPMethod;
  230. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  231. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  232. [request addValue:bundleIdentifier forHTTPHeaderField:kFIRInstallationsBundleId];
  233. [self setJSONHTTPBody:bodyDict forRequest:request];
  234. if (refreshToken) {
  235. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  236. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  237. }
  238. // User agent Header.
  239. [request setValue:[FIRApp firebaseUserAgent]
  240. forHTTPHeaderField:kFIRInstallationsUserAgentKey];
  241. // Heartbeat Header.
  242. [request setValue:@([FIRHeartbeatInfo
  243. heartbeatCodeForTag:kFIRInstallationsHeartbeatTag])
  244. .stringValue
  245. forHTTPHeaderField:kFIRInstallationsHeartbeatKey];
  246. [additionalHeaders
  247. enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull obj,
  248. BOOL *_Nonnull stop) {
  249. [request setValue:obj forHTTPHeaderField:key];
  250. }];
  251. return [request copy];
  252. }];
  253. }
  254. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)URLRequestPromise:(NSURLRequest *)request {
  255. return [[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  256. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeSendAPIRequest,
  257. @"Sending request: %@, body:%@, headers: %@.", request,
  258. [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
  259. request.allHTTPHeaderFields);
  260. [[self.URLSession
  261. dataTaskWithRequest:request
  262. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  263. NSError *_Nullable error) {
  264. if (error) {
  265. FIRLogDebug(kFIRLoggerInstallations,
  266. kFIRInstallationsMessageCodeAPIRequestNetworkError,
  267. @"Request failed: %@, error: %@.", request, error);
  268. reject(error);
  269. } else {
  270. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeAPIRequestResponse,
  271. @"Request response received: %@, error: %@, body: %@.", request, error,
  272. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  273. fulfill([[FIRInstallationsURLSessionResponse alloc]
  274. initWithResponse:(NSHTTPURLResponse *)response
  275. data:data]);
  276. }
  277. }] resume];
  278. }] then:^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  279. return [self validateHTTPResponseStatusCode:response];
  280. }];
  281. }
  282. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)validateHTTPResponseStatusCode:
  283. (FIRInstallationsURLSessionResponse *)response {
  284. NSInteger statusCode = response.HTTPResponse.statusCode;
  285. return [FBLPromise do:^id _Nullable {
  286. if (statusCode < 200 || statusCode >= 300) {
  287. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeUnexpectedAPIRequestResponse,
  288. @"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  289. [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]);
  290. return [FIRInstallationsErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  291. data:response.data];
  292. }
  293. return response;
  294. }];
  295. }
  296. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)sendURLRequest:(NSURLRequest *)request {
  297. return [FBLPromise attempts:1
  298. delay:1
  299. condition:^BOOL(NSInteger remainingAttempts, NSError *_Nonnull error) {
  300. return [FIRInstallationsErrorUtil isAPIError:error
  301. withHTTPCode:FIRInstallationsHTTPCodesServerInternalError];
  302. }
  303. retry:^id _Nullable {
  304. return [self URLRequestPromise:request];
  305. }];
  306. }
  307. - (NSString *)SDKVersion {
  308. return [NSString stringWithFormat:@"i:%@", FIRFirebaseVersion()];
  309. }
  310. #pragma mark - Validation
  311. - (FBLPromise<FIRInstallationsItem *> *)validateInstallation:(FIRInstallationsItem *)installation {
  312. FBLPromise<FIRInstallationsItem *> *result = [FBLPromise pendingPromise];
  313. NSError *validationError;
  314. if ([installation isValid:&validationError]) {
  315. [result fulfill:installation];
  316. } else {
  317. [result reject:validationError];
  318. }
  319. return result;
  320. }
  321. #pragma mark - JSON
  322. - (void)setJSONHTTPBody:(NSDictionary<NSString *, id> *)body
  323. forRequest:(NSMutableURLRequest *)request {
  324. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  325. NSError *error;
  326. NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  327. if (JSONData == nil) {
  328. // TODO: Log or return an error.
  329. }
  330. request.HTTPBody = JSONData;
  331. }
  332. @end