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. #import "FirebaseInstallations/Source/Library/Public/FirebaseInstallations/FIRInstallationsVersion.h"
  18. #if __has_include(<FBLPromises/FBLPromises.h>)
  19. #import <FBLPromises/FBLPromises.h>
  20. #else
  21. #import "FBLPromises.h"
  22. #endif
  23. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  24. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsErrorUtil.h"
  25. #import "FirebaseInstallations/Source/Library/Errors/FIRInstallationsHTTPError.h"
  26. #import "FirebaseInstallations/Source/Library/FIRInstallationsLogger.h"
  27. #import "FirebaseInstallations/Source/Library/InstallationsAPI/FIRInstallationsItem+RegisterInstallationAPI.h"
  28. NSString *const kFIRInstallationsAPIBaseURL = @"https://firebaseinstallations.googleapis.com";
  29. NSString *const kFIRInstallationsAPIKey = @"X-Goog-Api-Key";
  30. NSString *const kFIRInstallationsBundleId = @"X-Ios-Bundle-Identifier";
  31. NSString *const kFIRInstallationsIIDMigrationAuthHeader = @"x-goog-fis-ios-iid-migration-auth";
  32. NSString *const kFIRInstallationsHeartbeatKey = @"X-firebase-client-log-type";
  33. NSString *const kFIRInstallationsHeartbeatTag = @"fire-installations";
  34. NSString *const kFIRInstallationsUserAgentKey = @"X-firebase-client";
  35. NS_ASSUME_NONNULL_BEGIN
  36. @interface FIRInstallationsURLSessionResponse : NSObject
  37. @property(nonatomic) NSHTTPURLResponse *HTTPResponse;
  38. @property(nonatomic) NSData *data;
  39. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data;
  40. @end
  41. @implementation FIRInstallationsURLSessionResponse
  42. - (instancetype)initWithResponse:(NSHTTPURLResponse *)response data:(nullable NSData *)data {
  43. self = [super init];
  44. if (self) {
  45. _HTTPResponse = response;
  46. _data = data ?: [NSData data];
  47. }
  48. return self;
  49. }
  50. @end
  51. @interface FIRInstallationsAPIService ()
  52. @property(nonatomic, readonly) NSURLSession *URLSession;
  53. @property(nonatomic, readonly) NSString *APIKey;
  54. @property(nonatomic, readonly) NSString *projectID;
  55. @end
  56. NS_ASSUME_NONNULL_END
  57. @implementation FIRInstallationsAPIService
  58. - (instancetype)initWithAPIKey:(NSString *)APIKey projectID:(NSString *)projectID {
  59. NSURLSession *URLSession = [NSURLSession
  60. sessionWithConfiguration:[NSURLSessionConfiguration ephemeralSessionConfiguration]];
  61. return [self initWithURLSession:URLSession APIKey:APIKey projectID:projectID];
  62. }
  63. /// The initializer for tests.
  64. - (instancetype)initWithURLSession:(NSURLSession *)URLSession
  65. APIKey:(NSString *)APIKey
  66. projectID:(NSString *)projectID {
  67. self = [super init];
  68. if (self) {
  69. _URLSession = URLSession;
  70. _APIKey = [APIKey copy];
  71. _projectID = [projectID copy];
  72. }
  73. return self;
  74. }
  75. #pragma mark - Public
  76. - (FBLPromise<FIRInstallationsItem *> *)registerInstallation:(FIRInstallationsItem *)installation {
  77. return [self validateInstallation:installation]
  78. .then(^id _Nullable(FIRInstallationsItem *_Nullable validInstallation) {
  79. return [self registerRequestWithInstallation:validInstallation];
  80. })
  81. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  82. return [self sendURLRequest:request];
  83. })
  84. .then(^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  85. return [self registeredInstallationWithInstallation:installation serverResponse:response];
  86. });
  87. }
  88. - (FBLPromise<FIRInstallationsItem *> *)refreshAuthTokenForInstallation:
  89. (FIRInstallationsItem *)installation {
  90. return [self authTokenRequestWithInstallation:installation]
  91. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  92. return [self sendURLRequest:request];
  93. })
  94. .then(^FBLPromise<FIRInstallationsStoredAuthToken *> *(
  95. FIRInstallationsURLSessionResponse *response) {
  96. return [self authTokenWithServerResponse:response];
  97. })
  98. .then(^FIRInstallationsItem *(FIRInstallationsStoredAuthToken *authToken) {
  99. FIRInstallationsItem *updatedInstallation = [installation copy];
  100. updatedInstallation.authToken = authToken;
  101. return updatedInstallation;
  102. });
  103. }
  104. - (FBLPromise<FIRInstallationsItem *> *)deleteInstallation:(FIRInstallationsItem *)installation {
  105. return [self deleteInstallationRequestWithInstallation:installation]
  106. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  107. return [self sendURLRequest:request];
  108. })
  109. .then(^id _Nullable(FIRInstallationsURLSessionResponse *_Nullable value) {
  110. // Return the original installation on success.
  111. return installation;
  112. });
  113. }
  114. #pragma mark - Register Installation
  115. - (FBLPromise<NSURLRequest *> *)registerRequestWithInstallation:
  116. (FIRInstallationsItem *)installation {
  117. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/",
  118. kFIRInstallationsAPIBaseURL, self.projectID];
  119. NSURL *URL = [NSURL URLWithString:URLString];
  120. NSDictionary *bodyDict = @{
  121. // `firebaseInstallationID` is validated before but let's make sure it is not `nil` one more
  122. // time to prevent a crash.
  123. @"fid" : installation.firebaseInstallationID ?: @"",
  124. @"authVersion" : @"FIS_v2",
  125. @"appId" : installation.appID,
  126. @"sdkVersion" : [self SDKVersion]
  127. };
  128. NSDictionary *headers;
  129. if (installation.IIDDefaultToken) {
  130. headers = @{kFIRInstallationsIIDMigrationAuthHeader : installation.IIDDefaultToken};
  131. }
  132. return [self requestWithURL:URL
  133. HTTPMethod:@"POST"
  134. bodyDict:bodyDict
  135. refreshToken:nil
  136. additionalHeaders:headers];
  137. }
  138. - (FBLPromise<FIRInstallationsItem *> *)
  139. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  140. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  141. return [FBLPromise do:^id {
  142. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  143. @"Parsing server response for %@.", response.HTTPResponse.URL);
  144. NSError *error;
  145. FIRInstallationsItem *registeredInstallation =
  146. [installation registeredInstallationWithJSONData:response.data
  147. date:[NSDate date]
  148. error:&error];
  149. if (registeredInstallation == nil) {
  150. FIRLogDebug(kFIRLoggerInstallations,
  151. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  152. @"Failed to parse FIRInstallationsItem: %@.", error);
  153. return error;
  154. }
  155. FIRLogDebug(kFIRLoggerInstallations,
  156. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  157. @"FIRInstallationsItem parsed successfully.");
  158. return registeredInstallation;
  159. }];
  160. }
  161. #pragma mark - Auth token
  162. - (FBLPromise<NSURLRequest *> *)authTokenRequestWithInstallation:
  163. (FIRInstallationsItem *)installation {
  164. NSString *URLString =
  165. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  166. kFIRInstallationsAPIBaseURL, self.projectID,
  167. installation.firebaseInstallationID];
  168. NSURL *URL = [NSURL URLWithString:URLString];
  169. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  170. return [self requestWithURL:URL
  171. HTTPMethod:@"POST"
  172. bodyDict:bodyDict
  173. refreshToken:installation.refreshToken];
  174. }
  175. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  176. (FIRInstallationsURLSessionResponse *)response {
  177. return [FBLPromise do:^id {
  178. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  179. @"Parsing server response for %@.", response.HTTPResponse.URL);
  180. NSError *error;
  181. FIRInstallationsStoredAuthToken *token =
  182. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  183. date:[NSDate date]
  184. error:&error];
  185. if (token == nil) {
  186. FIRLogDebug(kFIRLoggerInstallations,
  187. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  188. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  189. return error;
  190. }
  191. FIRLogDebug(kFIRLoggerInstallations,
  192. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  193. @"FIRInstallationsStoredAuthToken parsed successfully.");
  194. return token;
  195. }];
  196. }
  197. #pragma mark - Delete Installation
  198. - (FBLPromise<NSURLRequest *> *)deleteInstallationRequestWithInstallation:
  199. (FIRInstallationsItem *)installation {
  200. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  201. kFIRInstallationsAPIBaseURL, self.projectID,
  202. installation.firebaseInstallationID];
  203. NSURL *URL = [NSURL URLWithString:URLString];
  204. return [self requestWithURL:URL
  205. HTTPMethod:@"DELETE"
  206. bodyDict:@{}
  207. refreshToken:installation.refreshToken];
  208. }
  209. #pragma mark - URL Request
  210. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  211. HTTPMethod:(NSString *)HTTPMethod
  212. bodyDict:(NSDictionary *)bodyDict
  213. refreshToken:(nullable NSString *)refreshToken {
  214. return [self requestWithURL:requestURL
  215. HTTPMethod:HTTPMethod
  216. bodyDict:bodyDict
  217. refreshToken:refreshToken
  218. additionalHeaders:nil];
  219. }
  220. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  221. HTTPMethod:(NSString *)HTTPMethod
  222. bodyDict:(NSDictionary *)bodyDict
  223. refreshToken:(nullable NSString *)refreshToken
  224. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  225. additionalHeaders {
  226. return [FBLPromise
  227. onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  228. do:^id _Nullable {
  229. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  230. request.HTTPMethod = HTTPMethod;
  231. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  232. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  233. [request addValue:bundleIdentifier forHTTPHeaderField:kFIRInstallationsBundleId];
  234. [self setJSONHTTPBody:bodyDict forRequest:request];
  235. if (refreshToken) {
  236. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  237. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  238. }
  239. // User agent Header.
  240. [request setValue:[FIRApp firebaseUserAgent]
  241. forHTTPHeaderField:kFIRInstallationsUserAgentKey];
  242. // Heartbeat Header.
  243. [request setValue:@([FIRHeartbeatInfo
  244. heartbeatCodeForTag:kFIRInstallationsHeartbeatTag])
  245. .stringValue
  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:%s", FIRInstallationsVersionStr];
  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