FIRInstallationsAPIService.m 13 KB

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