FIRInstallationsAPIService.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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 registerRequestWithInstallation:installation]
  78. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  79. return [self sendURLRequest:request];
  80. })
  81. .then(^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  82. return [self registeredInstallationWithInstallation:installation serverResponse:response];
  83. });
  84. }
  85. - (FBLPromise<FIRInstallationsItem *> *)refreshAuthTokenForInstallation:
  86. (FIRInstallationsItem *)installation {
  87. return [self authTokenRequestWithInstallation:installation]
  88. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  89. return [self sendURLRequest:request];
  90. })
  91. .then(^FBLPromise<FIRInstallationsStoredAuthToken *> *(
  92. FIRInstallationsURLSessionResponse *response) {
  93. return [self authTokenWithServerResponse:response];
  94. })
  95. .then(^FIRInstallationsItem *(FIRInstallationsStoredAuthToken *authToken) {
  96. FIRInstallationsItem *updatedInstallation = [installation copy];
  97. updatedInstallation.authToken = authToken;
  98. return updatedInstallation;
  99. });
  100. }
  101. - (FBLPromise<FIRInstallationsItem *> *)deleteInstallation:(FIRInstallationsItem *)installation {
  102. return [self deleteInstallationRequestWithInstallation:installation]
  103. .then(^id _Nullable(NSURLRequest *_Nullable request) {
  104. return [self sendURLRequest:request];
  105. })
  106. .then(^id _Nullable(FIRInstallationsURLSessionResponse *_Nullable value) {
  107. // Return the original installation on success.
  108. return installation;
  109. });
  110. }
  111. #pragma mark - Register Installation
  112. - (FBLPromise<NSURLRequest *> *)registerRequestWithInstallation:
  113. (FIRInstallationsItem *)installation {
  114. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/",
  115. kFIRInstallationsAPIBaseURL, self.projectID];
  116. NSURL *URL = [NSURL URLWithString:URLString];
  117. NSDictionary *bodyDict = @{
  118. @"fid" : installation.firebaseInstallationID,
  119. @"authVersion" : @"FIS_v2",
  120. @"appId" : installation.appID,
  121. @"sdkVersion" : [self SDKVersion]
  122. };
  123. NSDictionary *headers;
  124. if (installation.IIDDefaultToken) {
  125. headers = @{kFIRInstallationsIIDMigrationAuthHeader : installation.IIDDefaultToken};
  126. }
  127. return [self requestWithURL:URL
  128. HTTPMethod:@"POST"
  129. bodyDict:bodyDict
  130. refreshToken:nil
  131. additionalHeaders:headers];
  132. }
  133. - (FBLPromise<FIRInstallationsItem *> *)
  134. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  135. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  136. return [FBLPromise do:^id {
  137. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  138. @"Parsing server response for %@.", response.HTTPResponse.URL);
  139. NSError *error;
  140. FIRInstallationsItem *registeredInstallation =
  141. [installation registeredInstallationWithJSONData:response.data
  142. date:[NSDate date]
  143. error:&error];
  144. if (registeredInstallation == nil) {
  145. FIRLogDebug(kFIRLoggerInstallations,
  146. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  147. @"Failed to parse FIRInstallationsItem: %@.", error);
  148. return error;
  149. }
  150. FIRLogDebug(kFIRLoggerInstallations,
  151. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  152. @"FIRInstallationsItem parsed successfully.");
  153. return registeredInstallation;
  154. }];
  155. }
  156. #pragma mark - Auth token
  157. - (FBLPromise<NSURLRequest *> *)authTokenRequestWithInstallation:
  158. (FIRInstallationsItem *)installation {
  159. NSString *URLString =
  160. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  161. kFIRInstallationsAPIBaseURL, self.projectID,
  162. installation.firebaseInstallationID];
  163. NSURL *URL = [NSURL URLWithString:URLString];
  164. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  165. return [self requestWithURL:URL
  166. HTTPMethod:@"POST"
  167. bodyDict:bodyDict
  168. refreshToken:installation.refreshToken];
  169. }
  170. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  171. (FIRInstallationsURLSessionResponse *)response {
  172. return [FBLPromise do:^id {
  173. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  174. @"Parsing server response for %@.", response.HTTPResponse.URL);
  175. NSError *error;
  176. FIRInstallationsStoredAuthToken *token =
  177. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  178. date:[NSDate date]
  179. error:&error];
  180. if (token == nil) {
  181. FIRLogDebug(kFIRLoggerInstallations,
  182. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  183. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  184. return error;
  185. }
  186. FIRLogDebug(kFIRLoggerInstallations,
  187. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  188. @"FIRInstallationsStoredAuthToken parsed successfully.");
  189. return token;
  190. }];
  191. }
  192. #pragma mark - Delete Installation
  193. - (FBLPromise<NSURLRequest *> *)deleteInstallationRequestWithInstallation:
  194. (FIRInstallationsItem *)installation {
  195. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  196. kFIRInstallationsAPIBaseURL, self.projectID,
  197. installation.firebaseInstallationID];
  198. NSURL *URL = [NSURL URLWithString:URLString];
  199. return [self requestWithURL:URL
  200. HTTPMethod:@"DELETE"
  201. bodyDict:@{}
  202. refreshToken:installation.refreshToken];
  203. }
  204. #pragma mark - URL Request
  205. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  206. HTTPMethod:(NSString *)HTTPMethod
  207. bodyDict:(NSDictionary *)bodyDict
  208. refreshToken:(nullable NSString *)refreshToken {
  209. return [self requestWithURL:requestURL
  210. HTTPMethod:HTTPMethod
  211. bodyDict:bodyDict
  212. refreshToken:refreshToken
  213. additionalHeaders:nil];
  214. }
  215. - (FBLPromise<NSURLRequest *> *)requestWithURL:(NSURL *)requestURL
  216. HTTPMethod:(NSString *)HTTPMethod
  217. bodyDict:(NSDictionary *)bodyDict
  218. refreshToken:(nullable NSString *)refreshToken
  219. additionalHeaders:(nullable NSDictionary<NSString *, NSString *> *)
  220. additionalHeaders {
  221. return [FBLPromise
  222. onQueue:dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)
  223. do:^id _Nullable {
  224. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  225. request.HTTPMethod = HTTPMethod;
  226. NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
  227. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  228. [request addValue:bundleIdentifier forHTTPHeaderField:kFIRInstallationsBundleId];
  229. [self setJSONHTTPBody:bodyDict forRequest:request];
  230. if (refreshToken) {
  231. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  232. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  233. }
  234. // User agent Header.
  235. [request setValue:[FIRApp firebaseUserAgent]
  236. forHTTPHeaderField:kFIRInstallationsUserAgentKey];
  237. // Heartbeat Header.
  238. [request setValue:@([FIRHeartbeatInfo
  239. heartbeatCodeForTag:kFIRInstallationsHeartbeatTag])
  240. .stringValue
  241. forHTTPHeaderField:kFIRInstallationsHeartbeatKey];
  242. [additionalHeaders
  243. enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull key, NSString *_Nonnull obj,
  244. BOOL *_Nonnull stop) {
  245. [request setValue:obj forHTTPHeaderField:key];
  246. }];
  247. return [request copy];
  248. }];
  249. }
  250. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)URLRequestPromise:(NSURLRequest *)request {
  251. return [[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  252. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeSendAPIRequest,
  253. @"Sending request: %@, body:%@, headers: %@.", request,
  254. [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
  255. request.allHTTPHeaderFields);
  256. [[self.URLSession
  257. dataTaskWithRequest:request
  258. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  259. NSError *_Nullable error) {
  260. if (error) {
  261. FIRLogDebug(kFIRLoggerInstallations,
  262. kFIRInstallationsMessageCodeAPIRequestNetworkError,
  263. @"Request failed: %@, error: %@.", request, error);
  264. reject(error);
  265. } else {
  266. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeAPIRequestResponse,
  267. @"Request response received: %@, error: %@, body: %@.", request, error,
  268. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  269. fulfill([[FIRInstallationsURLSessionResponse alloc]
  270. initWithResponse:(NSHTTPURLResponse *)response
  271. data:data]);
  272. }
  273. }] resume];
  274. }] then:^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  275. return [self validateHTTPResponseStatusCode:response];
  276. }];
  277. }
  278. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)validateHTTPResponseStatusCode:
  279. (FIRInstallationsURLSessionResponse *)response {
  280. NSInteger statusCode = response.HTTPResponse.statusCode;
  281. return [FBLPromise do:^id _Nullable {
  282. if (statusCode < 200 || statusCode >= 300) {
  283. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeUnexpectedAPIRequestResponse,
  284. @"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  285. [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]);
  286. return [FIRInstallationsErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  287. data:response.data];
  288. }
  289. return response;
  290. }];
  291. }
  292. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)sendURLRequest:(NSURLRequest *)request {
  293. return [FBLPromise attempts:1
  294. delay:1
  295. condition:^BOOL(NSInteger remainingAttempts, NSError *_Nonnull error) {
  296. return [FIRInstallationsErrorUtil isAPIError:error
  297. withHTTPCode:FIRInstallationsHTTPCodesServerInternalError];
  298. }
  299. retry:^id _Nullable {
  300. return [self URLRequestPromise:request];
  301. }];
  302. }
  303. - (NSString *)SDKVersion {
  304. return [NSString stringWithFormat:@"i:%s", FIRInstallationsVersionStr];
  305. }
  306. #pragma mark - JSON
  307. - (void)setJSONHTTPBody:(NSDictionary<NSString *, id> *)body
  308. forRequest:(NSMutableURLRequest *)request {
  309. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  310. NSError *error;
  311. NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  312. if (JSONData == nil) {
  313. // TODO: Log or return an error.
  314. }
  315. request.HTTPBody = JSONData;
  316. }
  317. @end