FIRInstallationsAPIService.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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 "FIRInstallationsStoredIIDCheckin.h"
  27. NSString *const kFIRInstallationsAPIBaseURL = @"https://firebaseinstallations.googleapis.com";
  28. NSString *const kFIRInstallationsAPIKey = @"X-Goog-Api-Key";
  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.IIDCheckin && installation.IIDCheckin.deviceID &&
  113. installation.IIDCheckin.secretToken) {
  114. NSString *IIDAuthHeaderValue =
  115. [NSString stringWithFormat:@"%@:%@", installation.IIDCheckin.deviceID,
  116. installation.IIDCheckin.secretToken];
  117. headers = @{kFIRInstallationsIIDMigrationAuthHeader : IIDAuthHeaderValue};
  118. }
  119. return [self requestWithURL:URL
  120. HTTPMethod:@"POST"
  121. bodyDict:bodyDict
  122. refreshToken:nil
  123. additionalHeaders:headers];
  124. }
  125. - (FBLPromise<FIRInstallationsItem *> *)
  126. registeredInstallationWithInstallation:(FIRInstallationsItem *)installation
  127. serverResponse:(FIRInstallationsURLSessionResponse *)response {
  128. return [FBLPromise do:^id {
  129. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  130. @"Parsing server response for %@.", response.HTTPResponse.URL);
  131. NSError *error;
  132. FIRInstallationsItem *registeredInstallation =
  133. [installation registeredInstallationWithJSONData:response.data
  134. date:[NSDate date]
  135. error:&error];
  136. if (registeredInstallation == nil) {
  137. FIRLogDebug(kFIRLoggerInstallations,
  138. kFIRInstallationsMessageCodeAPIResponseParsingInstallationFailed,
  139. @"Failed to parse FIRInstallationsItem: %@.", error);
  140. return error;
  141. }
  142. FIRLogDebug(kFIRLoggerInstallations,
  143. kFIRInstallationsMessageCodeAPIResponseParsingInstallationSucceed,
  144. @"FIRInstallationsItem parsed successfully.");
  145. return registeredInstallation;
  146. }];
  147. }
  148. #pragma mark - Auth token
  149. - (NSURLRequest *)authTokenRequestWithInstallation:(FIRInstallationsItem *)installation {
  150. NSString *URLString =
  151. [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/authTokens:generate",
  152. kFIRInstallationsAPIBaseURL, self.projectID,
  153. installation.firebaseInstallationID];
  154. NSURL *URL = [NSURL URLWithString:URLString];
  155. NSDictionary *bodyDict = @{@"installation" : @{@"sdkVersion" : [self SDKVersion]}};
  156. return [self requestWithURL:URL
  157. HTTPMethod:@"POST"
  158. bodyDict:bodyDict
  159. refreshToken:installation.refreshToken];
  160. }
  161. - (FBLPromise<FIRInstallationsStoredAuthToken *> *)authTokenWithServerResponse:
  162. (FIRInstallationsURLSessionResponse *)response {
  163. return [FBLPromise do:^id {
  164. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeParsingAPIResponse,
  165. @"Parsing server response for %@.", response.HTTPResponse.URL);
  166. NSError *error;
  167. FIRInstallationsStoredAuthToken *token =
  168. [FIRInstallationsItem authTokenWithGenerateTokenAPIJSONData:response.data
  169. date:[NSDate date]
  170. error:&error];
  171. if (token == nil) {
  172. FIRLogDebug(kFIRLoggerInstallations,
  173. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenFailed,
  174. @"Failed to parse FIRInstallationsStoredAuthToken: %@.", error);
  175. return error;
  176. }
  177. FIRLogDebug(kFIRLoggerInstallations,
  178. kFIRInstallationsMessageCodeAPIResponseParsingAuthTokenSucceed,
  179. @"FIRInstallationsStoredAuthToken parsed successfully.");
  180. return token;
  181. }];
  182. }
  183. #pragma mark - Delete Installation
  184. - (NSURLRequest *)deleteInstallationRequestWithInstallation:(FIRInstallationsItem *)installation {
  185. NSString *URLString = [NSString stringWithFormat:@"%@/v1/projects/%@/installations/%@/",
  186. kFIRInstallationsAPIBaseURL, self.projectID,
  187. installation.firebaseInstallationID];
  188. NSURL *URL = [NSURL URLWithString:URLString];
  189. return [self requestWithURL:URL
  190. HTTPMethod:@"DELETE"
  191. bodyDict:@{}
  192. refreshToken:installation.refreshToken];
  193. }
  194. #pragma mark - URL Request
  195. - (NSURLRequest *)requestWithURL:(NSURL *)requestURL
  196. HTTPMethod:(NSString *)HTTPMethod
  197. bodyDict:(NSDictionary *)bodyDict
  198. refreshToken:(nullable NSString *)refreshToken {
  199. return [self requestWithURL:requestURL
  200. HTTPMethod:HTTPMethod
  201. bodyDict:bodyDict
  202. refreshToken:refreshToken
  203. additionalHeaders:nil];
  204. }
  205. - (NSURLRequest *)requestWithURL:(NSURL *)requestURL
  206. HTTPMethod:(NSString *)HTTPMethod
  207. bodyDict:(NSDictionary *)bodyDict
  208. refreshToken:(nullable NSString *)refreshToken
  209. additionalHeaders:
  210. (nullable NSDictionary<NSString *, NSString *> *)additionalHeaders {
  211. __block NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:requestURL];
  212. request.HTTPMethod = HTTPMethod;
  213. [request addValue:self.APIKey forHTTPHeaderField:kFIRInstallationsAPIKey];
  214. [self setJSONHTTPBody:bodyDict forRequest:request];
  215. if (refreshToken) {
  216. NSString *authHeader = [NSString stringWithFormat:@"FIS_v2 %@", refreshToken];
  217. [request setValue:authHeader forHTTPHeaderField:@"Authorization"];
  218. }
  219. [additionalHeaders enumerateKeysAndObjectsUsingBlock:^(
  220. NSString *_Nonnull key, NSString *_Nonnull obj, BOOL *_Nonnull stop) {
  221. [request setValue:obj forHTTPHeaderField:key];
  222. }];
  223. return [request copy];
  224. }
  225. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)URLRequestPromise:(NSURLRequest *)request {
  226. return [[FBLPromise async:^(FBLPromiseFulfillBlock fulfill, FBLPromiseRejectBlock reject) {
  227. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeSendAPIRequest,
  228. @"Sending request: %@, body:%@, headers: %@.", request,
  229. [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding],
  230. request.allHTTPHeaderFields);
  231. [[self.URLSession
  232. dataTaskWithRequest:request
  233. completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response,
  234. NSError *_Nullable error) {
  235. if (error) {
  236. FIRLogDebug(kFIRLoggerInstallations,
  237. kFIRInstallationsMessageCodeAPIRequestNetworkError,
  238. @"Request failed: %@, error: %@.", request, error);
  239. reject(error);
  240. } else {
  241. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeAPIRequestResponse,
  242. @"Request response received: %@, error: %@, body: %@.", request, error,
  243. [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
  244. fulfill([[FIRInstallationsURLSessionResponse alloc]
  245. initWithResponse:(NSHTTPURLResponse *)response
  246. data:data]);
  247. }
  248. }] resume];
  249. }] then:^id _Nullable(FIRInstallationsURLSessionResponse *response) {
  250. return [self validateHTTPResponseStatusCode:response];
  251. }];
  252. }
  253. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)validateHTTPResponseStatusCode:
  254. (FIRInstallationsURLSessionResponse *)response {
  255. NSInteger statusCode = response.HTTPResponse.statusCode;
  256. return [FBLPromise do:^id _Nullable {
  257. if (statusCode < 200 || statusCode >= 300) {
  258. FIRLogDebug(kFIRLoggerInstallations, kFIRInstallationsMessageCodeUnexpectedAPIRequestResponse,
  259. @"Unexpected API response: %@, body: %@.", response.HTTPResponse,
  260. [[NSString alloc] initWithData:response.data encoding:NSUTF8StringEncoding]);
  261. return [FIRInstallationsErrorUtil APIErrorWithHTTPResponse:response.HTTPResponse
  262. data:response.data];
  263. }
  264. return response;
  265. }];
  266. }
  267. - (FBLPromise<FIRInstallationsURLSessionResponse *> *)sendURLRequest:(NSURLRequest *)request {
  268. return [FBLPromise attempts:1
  269. delay:1
  270. condition:^BOOL(NSInteger remainingAttempts, NSError *_Nonnull error) {
  271. return [FIRInstallationsErrorUtil isAPIError:error withHTTPCode:500];
  272. }
  273. retry:^id _Nullable {
  274. return [self URLRequestPromise:request];
  275. }];
  276. }
  277. - (NSString *)SDKVersion {
  278. return [NSString stringWithFormat:@"i:%s", FIRInstallationsVersionStr];
  279. }
  280. #pragma mark - JSON
  281. - (void)setJSONHTTPBody:(NSDictionary<NSString *, id> *)body
  282. forRequest:(NSMutableURLRequest *)request {
  283. [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
  284. NSError *error;
  285. NSData *JSONData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
  286. if (JSONData == nil) {
  287. // TODO: Log or return an error.
  288. }
  289. request.HTTPBody = JSONData;
  290. }
  291. @end