FIRInstallationsAPIService.m 15 KB

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