FIRInstallationsAPIService.m 14 KB

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