FIRInstanceIDTokenManager.m 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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 "FIRInstanceIDTokenManager.h"
  17. #import "FIRInstanceIDAuthKeyChain.h"
  18. #import "FIRInstanceIDAuthService.h"
  19. #import "FIRInstanceIDCheckinPreferences.h"
  20. #import "FIRInstanceIDConstants.h"
  21. #import "FIRInstanceIDDefines.h"
  22. #import "FIRInstanceIDLogger.h"
  23. #import "FIRInstanceIDStore.h"
  24. #import "FIRInstanceIDTokenDeleteOperation.h"
  25. #import "FIRInstanceIDTokenFetchOperation.h"
  26. #import "FIRInstanceIDTokenInfo.h"
  27. #import "FIRInstanceIDTokenOperation.h"
  28. #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
  29. #import "NSError+FIRInstanceID.h"
  30. @interface FIRInstanceIDTokenManager () <FIRInstanceIDStoreDelegate>
  31. @property(nonatomic, readwrite, strong) FIRInstanceIDStore *instanceIDStore;
  32. @property(nonatomic, readwrite, strong) FIRInstanceIDAuthService *authService;
  33. @property(nonatomic, readonly, strong) NSOperationQueue *tokenOperations;
  34. @property(nonatomic, readwrite, strong) FIRInstanceIDAPNSInfo *currentAPNSInfo;
  35. @end
  36. @implementation FIRInstanceIDTokenManager
  37. - (instancetype)init {
  38. self = [super init];
  39. if (self) {
  40. _instanceIDStore = [[FIRInstanceIDStore alloc] initWithDelegate:self];
  41. _authService = [[FIRInstanceIDAuthService alloc] initWithStore:_instanceIDStore];
  42. [self configureTokenOperations];
  43. }
  44. return self;
  45. }
  46. - (void)dealloc {
  47. [self stopAllTokenOperations];
  48. }
  49. - (void)configureTokenOperations {
  50. _tokenOperations = [[NSOperationQueue alloc] init];
  51. _tokenOperations.name = @"com.google.iid-token-operations";
  52. // For now, restrict the operations to be serial, because in some cases (like if the
  53. // authorized entity and scope are the same), order matters.
  54. // If we have to deal with several different token requests simultaneously, it would be a good
  55. // idea to add some better intelligence around this (performing unrelated token operations
  56. // simultaneously, etc.).
  57. _tokenOperations.maxConcurrentOperationCount = 1;
  58. if ([_tokenOperations respondsToSelector:@selector(qualityOfService)]) {
  59. _tokenOperations.qualityOfService = NSOperationQualityOfServiceUtility;
  60. }
  61. }
  62. - (void)fetchNewTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  63. scope:(NSString *)scope
  64. instanceID:(NSString *)instanceID
  65. options:(NSDictionary *)options
  66. handler:(FIRInstanceIDTokenHandler)handler {
  67. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenManager000,
  68. @"Fetch new token for authorizedEntity: %@, scope: %@", authorizedEntity,
  69. scope);
  70. FIRInstanceIDTokenFetchOperation *operation =
  71. [self createFetchOperationWithAuthorizedEntity:authorizedEntity
  72. scope:scope
  73. options:options
  74. instanceID:instanceID];
  75. FIRInstanceID_WEAKIFY(self);
  76. FIRInstanceIDTokenOperationCompletion completion =
  77. ^(FIRInstanceIDTokenOperationResult result, NSString *_Nullable token,
  78. NSError *_Nullable error) {
  79. FIRInstanceID_STRONGIFY(self);
  80. if (error) {
  81. handler(nil, error);
  82. return;
  83. }
  84. NSString *firebaseAppID = options[kFIRInstanceIDTokenOptionsFirebaseAppIDKey];
  85. FIRInstanceIDTokenInfo *tokenInfo = [[FIRInstanceIDTokenInfo alloc]
  86. initWithAuthorizedEntity:authorizedEntity
  87. scope:scope
  88. token:token
  89. appVersion:FIRInstanceIDCurrentAppVersion()
  90. firebaseAppID:firebaseAppID];
  91. tokenInfo.APNSInfo = [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:options];
  92. [self.instanceIDStore
  93. saveTokenInfo:tokenInfo
  94. handler:^(NSError *error) {
  95. if (!error) {
  96. // Do not send the token back in case the save was unsuccessful. Since with
  97. // the new asychronous fetch mechanism this can lead to infinite loops, for
  98. // example, we will return a valid token even though we weren't able to store
  99. // it in our cache. The first token will lead to a onTokenRefresh callback
  100. // wherein the user again calls `getToken` but since we weren't able to save
  101. // it we won't hit the cache but hit the server again leading to an infinite
  102. // loop.
  103. FIRInstanceIDLoggerDebug(
  104. kFIRInstanceIDMessageCodeTokenManager001,
  105. @"Token fetch successful, token: %@, authorizedEntity: %@, scope:%@",
  106. token, authorizedEntity, scope);
  107. if (handler) {
  108. handler(token, nil);
  109. }
  110. } else {
  111. if (handler) {
  112. handler(nil, error);
  113. }
  114. }
  115. }];
  116. };
  117. // Add completion handler, and ensure it's called on the main queue
  118. [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
  119. NSString *_Nullable token, NSError *_Nullable error) {
  120. dispatch_async(dispatch_get_main_queue(), ^{
  121. completion(result, token, error);
  122. });
  123. }];
  124. [self.tokenOperations addOperation:operation];
  125. }
  126. - (FIRInstanceIDTokenInfo *)cachedTokenInfoWithAuthorizedEntity:(NSString *)authorizedEntity
  127. scope:(NSString *)scope {
  128. return [self.instanceIDStore tokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  129. }
  130. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  131. scope:(NSString *)scope
  132. instanceID:(NSString *)instanceID
  133. handler:(FIRInstanceIDDeleteTokenHandler)handler {
  134. if ([self.instanceIDStore tokenInfoWithAuthorizedEntity:authorizedEntity scope:scope]) {
  135. [self.instanceIDStore removeCachedTokenWithAuthorizedEntity:authorizedEntity scope:scope];
  136. }
  137. // Does not matter if we cannot find it in the cache. Still make an effort to unregister
  138. // from the server.
  139. FIRInstanceIDCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  140. FIRInstanceIDTokenDeleteOperation *operation =
  141. [self createDeleteOperationWithAuthorizedEntity:authorizedEntity
  142. scope:scope
  143. checkinPreferences:checkinPreferences
  144. instanceID:instanceID
  145. action:FIRInstanceIDTokenActionDeleteToken];
  146. if (handler) {
  147. [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
  148. NSString *_Nullable token, NSError *_Nullable error) {
  149. dispatch_async(dispatch_get_main_queue(), ^{
  150. handler(error);
  151. });
  152. }];
  153. }
  154. [self.tokenOperations addOperation:operation];
  155. }
  156. - (void)deleteAllTokensWithInstanceID:(NSString *)instanceID
  157. handler:(FIRInstanceIDDeleteHandler)handler {
  158. // delete all tokens
  159. FIRInstanceIDCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  160. if (!checkinPreferences) {
  161. // The checkin is already deleted. No need to trigger the token delete operation as client no
  162. // longer has the checkin information for server to delete.
  163. dispatch_async(dispatch_get_main_queue(), ^{
  164. handler(nil);
  165. });
  166. return;
  167. }
  168. FIRInstanceIDTokenDeleteOperation *operation =
  169. [self createDeleteOperationWithAuthorizedEntity:kFIRInstanceIDKeychainWildcardIdentifier
  170. scope:kFIRInstanceIDKeychainWildcardIdentifier
  171. checkinPreferences:checkinPreferences
  172. instanceID:instanceID
  173. action:FIRInstanceIDTokenActionDeleteTokenAndIID];
  174. if (handler) {
  175. [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
  176. NSString *_Nullable token, NSError *_Nullable error) {
  177. dispatch_async(dispatch_get_main_queue(), ^{
  178. handler(error);
  179. });
  180. }];
  181. }
  182. [self.tokenOperations addOperation:operation];
  183. }
  184. - (void)deleteAllTokensLocallyWithHandler:(void (^)(NSError *error))handler {
  185. [self.instanceIDStore removeAllCachedTokensWithHandler:handler];
  186. }
  187. - (void)stopAllTokenOperations {
  188. [self.authService stopCheckinRequest];
  189. [self.tokenOperations cancelAllOperations];
  190. }
  191. #pragma mark - FIRInstanceIDStoreDelegate
  192. - (void)store:(FIRInstanceIDStore *)store
  193. didDeleteFCMScopedTokensForCheckin:(FIRInstanceIDCheckinPreferences *)checkin {
  194. // Make a best effort try to delete the old client related state on the FCM server. This is
  195. // required to delete old pubusb registrations which weren't cleared when the app was deleted.
  196. //
  197. // This is only a one time effort. If this call fails the client would still receive duplicate
  198. // pubsub notifications if he is again subscribed to the same topic.
  199. //
  200. // The client state should be cleared on the server for the provided checkin preferences.
  201. FIRInstanceIDTokenDeleteOperation *operation =
  202. [self createDeleteOperationWithAuthorizedEntity:nil
  203. scope:nil
  204. checkinPreferences:checkin
  205. instanceID:nil
  206. action:FIRInstanceIDTokenActionDeleteToken];
  207. [operation addCompletionHandler:^(FIRInstanceIDTokenOperationResult result,
  208. NSString *_Nullable token, NSError *_Nullable error) {
  209. if (error) {
  210. FIRInstanceIDMessageCode code =
  211. kFIRInstanceIDMessageCodeTokenManagerErrorDeletingFCMTokensOnAppReset;
  212. FIRInstanceIDLoggerDebug(code, @"Failed to delete GCM server registrations on app reset.");
  213. } else {
  214. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenManagerDeletedFCMTokensOnAppReset,
  215. @"Successfully deleted GCM server registrations on app reset");
  216. }
  217. }];
  218. [self.tokenOperations addOperation:operation];
  219. }
  220. #pragma mark - Unit Testing Stub Helpers
  221. // We really have this method so that we can more easily stub it out for unit testing
  222. - (FIRInstanceIDTokenFetchOperation *)
  223. createFetchOperationWithAuthorizedEntity:(NSString *)authorizedEntity
  224. scope:(NSString *)scope
  225. options:(NSDictionary<NSString *, NSString *> *)options
  226. instanceID:(NSString *)instanceID {
  227. FIRInstanceIDCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  228. FIRInstanceIDTokenFetchOperation *operation =
  229. [[FIRInstanceIDTokenFetchOperation alloc] initWithAuthorizedEntity:authorizedEntity
  230. scope:scope
  231. options:options
  232. checkinPreferences:checkinPreferences
  233. instanceID:instanceID];
  234. return operation;
  235. }
  236. // We really have this method so that we can more easily stub it out for unit testing
  237. - (FIRInstanceIDTokenDeleteOperation *)
  238. createDeleteOperationWithAuthorizedEntity:(NSString *)authorizedEntity
  239. scope:(NSString *)scope
  240. checkinPreferences:(FIRInstanceIDCheckinPreferences *)checkinPreferences
  241. instanceID:(NSString *)instanceID
  242. action:(FIRInstanceIDTokenAction)action {
  243. FIRInstanceIDTokenDeleteOperation *operation =
  244. [[FIRInstanceIDTokenDeleteOperation alloc] initWithAuthorizedEntity:authorizedEntity
  245. scope:scope
  246. checkinPreferences:checkinPreferences
  247. instanceID:instanceID
  248. action:action];
  249. return operation;
  250. }
  251. #pragma mark - Invalidating Cached Tokens
  252. - (BOOL)checkTokenRefreshPolicyWithIID:(NSString *)IID {
  253. // We know at least one cached token exists.
  254. BOOL shouldFetchDefaultToken = NO;
  255. NSArray<FIRInstanceIDTokenInfo *> *tokenInfos = [self.instanceIDStore cachedTokenInfos];
  256. NSMutableArray<FIRInstanceIDTokenInfo *> *tokenInfosToDelete =
  257. [NSMutableArray arrayWithCapacity:tokenInfos.count];
  258. for (FIRInstanceIDTokenInfo *tokenInfo in tokenInfos) {
  259. if ([tokenInfo isFreshWithIID:IID]) {
  260. // Token is fresh and in right format, do nothing
  261. continue;
  262. }
  263. if ([tokenInfo isDefaultToken]) {
  264. // Default token is expired, do not mark for deletion. Fetch directly from server to
  265. // replace the current one.
  266. shouldFetchDefaultToken = YES;
  267. } else {
  268. // Non-default token is expired, mark for deletion.
  269. [tokenInfosToDelete addObject:tokenInfo];
  270. }
  271. FIRInstanceIDLoggerDebug(
  272. kFIRInstanceIDMessageCodeTokenManagerInvalidateStaleToken,
  273. @"Invalidating cached token for %@ (%@) due to token is no longer fresh.",
  274. tokenInfo.authorizedEntity, tokenInfo.scope);
  275. }
  276. for (FIRInstanceIDTokenInfo *tokenInfoToDelete in tokenInfosToDelete) {
  277. [self.instanceIDStore removeCachedTokenWithAuthorizedEntity:tokenInfoToDelete.authorizedEntity
  278. scope:tokenInfoToDelete.scope];
  279. }
  280. return shouldFetchDefaultToken;
  281. }
  282. - (NSArray<FIRInstanceIDTokenInfo *> *)updateTokensToAPNSDeviceToken:(NSData *)deviceToken
  283. isSandbox:(BOOL)isSandbox {
  284. // Each cached IID token that is missing an APNSInfo, or has an APNSInfo associated should be
  285. // checked and invalidated if needed.
  286. FIRInstanceIDAPNSInfo *APNSInfo = [[FIRInstanceIDAPNSInfo alloc] initWithDeviceToken:deviceToken
  287. isSandbox:isSandbox];
  288. if ([self.currentAPNSInfo isEqualToAPNSInfo:APNSInfo]) {
  289. return @[];
  290. }
  291. self.currentAPNSInfo = APNSInfo;
  292. NSArray<FIRInstanceIDTokenInfo *> *tokenInfos = [self.instanceIDStore cachedTokenInfos];
  293. NSMutableArray<FIRInstanceIDTokenInfo *> *tokenInfosToDelete =
  294. [NSMutableArray arrayWithCapacity:tokenInfos.count];
  295. for (FIRInstanceIDTokenInfo *cachedTokenInfo in tokenInfos) {
  296. // Check if the cached APNSInfo is nil, or if it is an old APNSInfo.
  297. if (!cachedTokenInfo.APNSInfo ||
  298. ![cachedTokenInfo.APNSInfo isEqualToAPNSInfo:self.currentAPNSInfo]) {
  299. // Mark for invalidation.
  300. [tokenInfosToDelete addObject:cachedTokenInfo];
  301. }
  302. }
  303. for (FIRInstanceIDTokenInfo *tokenInfoToDelete in tokenInfosToDelete) {
  304. FIRInstanceIDLoggerDebug(kFIRInstanceIDMessageCodeTokenManagerAPNSChangedTokenInvalidated,
  305. @"Invalidating cached token for %@ (%@) due to APNs token change.",
  306. tokenInfoToDelete.authorizedEntity, tokenInfoToDelete.scope);
  307. [self.instanceIDStore removeCachedTokenWithAuthorizedEntity:tokenInfoToDelete.authorizedEntity
  308. scope:tokenInfoToDelete.scope];
  309. }
  310. return tokenInfosToDelete;
  311. }
  312. - (void)saveDefaultToken:(NSString *)defaultToken withOptions:(NSDictionary *)tokenOptions {
  313. FIROptions *options = FIRApp.defaultApp.options;
  314. FIRInstanceIDTokenInfo *tokenInfo =
  315. [[FIRInstanceIDTokenInfo alloc] initWithAuthorizedEntity:options.GCMSenderID
  316. scope:@"*"
  317. token:defaultToken
  318. appVersion:FIRInstanceIDCurrentAppVersion()
  319. firebaseAppID:options.googleAppID];
  320. tokenInfo.APNSInfo = [[FIRInstanceIDAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  321. [self.instanceIDStore saveTokenInfoInCacheOnly:tokenInfo];
  322. }
  323. @end