FIRMessagingTokenManager.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  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 "FirebaseMessaging/Sources/Token/FIRMessagingTokenManager.h"
  17. #import "FirebaseInstallations/Source/Library/Private/FirebaseInstallationsInternal.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingDefines.h"
  20. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  21. #import "FirebaseMessaging/Sources/NSError+FIRMessaging.h"
  22. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthKeychain.h"
  23. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthService.h"
  24. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinPreferences.h"
  25. #import "FirebaseMessaging/Sources/Token/FIRMessagingCheckinStore.h"
  26. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenDeleteOperation.h"
  27. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenFetchOperation.h"
  28. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenInfo.h"
  29. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenOperation.h"
  30. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenStore.h"
  31. @interface FIRMessagingTokenManager () {
  32. FIRMessagingTokenStore *_tokenStore;
  33. NSString *_defaultFCMToken;
  34. }
  35. @property(nonatomic, readwrite, strong) FIRMessagingCheckinStore *checkinStore;
  36. @property(nonatomic, readwrite, strong) FIRMessagingAuthService *authService;
  37. @property(nonatomic, readonly, strong) NSOperationQueue *tokenOperations;
  38. @property(nonatomic, readwrite, strong) FIRMessagingAPNSInfo *currentAPNSInfo;
  39. @property(nonatomic, readwrite) FIRInstallations *installations;
  40. @end
  41. @implementation FIRMessagingTokenManager
  42. - (instancetype)init {
  43. self = [super init];
  44. if (self) {
  45. _tokenStore = [[FIRMessagingTokenStore alloc] init];
  46. _authService = [[FIRMessagingAuthService alloc] init];
  47. [self resetCredentialsIfNeeded];
  48. [self configureTokenOperations];
  49. _installations = [FIRInstallations installations];
  50. }
  51. return self;
  52. }
  53. - (void)dealloc {
  54. [self stopAllTokenOperations];
  55. }
  56. - (NSString *)tokenAndRequestIfNotExist {
  57. if (!self.fcmSenderID.length) {
  58. return nil;
  59. }
  60. if (_defaultFCMToken.length) {
  61. return _defaultFCMToken;
  62. }
  63. FIRMessagingTokenInfo *cachedTokenInfo =
  64. [self cachedTokenInfoWithAuthorizedEntity:self.fcmSenderID
  65. scope:kFIRMessagingDefaultTokenScope];
  66. NSString *cachedToken = cachedTokenInfo.token;
  67. if (cachedToken) {
  68. return cachedToken;
  69. } else {
  70. [self tokenWithAuthorizedEntity:self.fcmSenderID
  71. scope:kFIRMessagingDefaultTokenScope
  72. options:[self tokenOptions]
  73. handler:^(NSString *_Nullable FCMToken, NSError *_Nullable error){
  74. }];
  75. return nil;
  76. }
  77. }
  78. - (NSString *)defaultFCMToken {
  79. return _defaultFCMToken;
  80. }
  81. - (void)postTokenRefreshNotificationWithDefaultFCMToken:(NSString *)defaultFCMToken {
  82. // Should always trigger the token refresh notification when the delegate method is called
  83. // No need to check if the token has changed, it's handled in the notification receiver.
  84. NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
  85. [center postNotificationName:kFIRMessagingRegistrationTokenRefreshNotification
  86. object:defaultFCMToken];
  87. }
  88. - (void)saveDefaultTokenInfoInKeychain:(NSString *)defaultFcmToken {
  89. if ([self hasTokenChangedFromOldToken:_defaultFCMToken toNewToken:defaultFcmToken]) {
  90. _defaultFCMToken = [defaultFcmToken copy];
  91. FIRMessagingTokenInfo *tokenInfo =
  92. [[FIRMessagingTokenInfo alloc] initWithAuthorizedEntity:_fcmSenderID
  93. scope:kFIRMessagingDefaultTokenScope
  94. token:defaultFcmToken
  95. appVersion:FIRMessagingCurrentAppVersion()
  96. firebaseAppID:_firebaseAppID];
  97. tokenInfo.APNSInfo =
  98. [[FIRMessagingAPNSInfo alloc] initWithTokenOptionsDictionary:[self tokenOptions]];
  99. [self->_tokenStore saveTokenInfoInCache:tokenInfo];
  100. }
  101. }
  102. - (BOOL)hasTokenChangedFromOldToken:(NSString *)oldToken toNewToken:(NSString *)newToken {
  103. return oldToken.length != newToken.length ||
  104. (oldToken.length && newToken.length && ![oldToken isEqualToString:newToken]);
  105. }
  106. - (NSDictionary *)tokenOptions {
  107. NSDictionary *instanceIDOptions = @{};
  108. NSData *apnsTokenData = self.currentAPNSInfo.deviceToken;
  109. if (apnsTokenData) {
  110. instanceIDOptions = @{
  111. kFIRMessagingTokenOptionsAPNSKey : apnsTokenData,
  112. kFIRMessagingTokenOptionsAPNSIsSandboxKey : @(self.currentAPNSInfo.isSandbox),
  113. };
  114. }
  115. return instanceIDOptions;
  116. }
  117. - (NSString *)deviceAuthID {
  118. return [_authService checkinPreferences].deviceID;
  119. }
  120. - (NSString *)secretToken {
  121. return [_authService checkinPreferences].secretToken;
  122. }
  123. - (NSString *)versionInfo {
  124. return [_authService checkinPreferences].versionInfo;
  125. }
  126. - (void)configureTokenOperations {
  127. _tokenOperations = [[NSOperationQueue alloc] init];
  128. _tokenOperations.name = @"com.google.iid-token-operations";
  129. // For now, restrict the operations to be serial, because in some cases (like if the
  130. // authorized entity and scope are the same), order matters.
  131. // If we have to deal with several different token requests simultaneously, it would be a good
  132. // idea to add some better intelligence around this (performing unrelated token operations
  133. // simultaneously, etc.).
  134. _tokenOperations.maxConcurrentOperationCount = 1;
  135. if ([_tokenOperations respondsToSelector:@selector(qualityOfService)]) {
  136. _tokenOperations.qualityOfService = NSOperationQualityOfServiceUtility;
  137. }
  138. }
  139. - (void)tokenWithAuthorizedEntity:(NSString *)authorizedEntity
  140. scope:(NSString *)scope
  141. options:(NSDictionary *)options
  142. handler:(FIRMessagingFCMTokenFetchCompletion)handler {
  143. if (!handler) {
  144. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID000, @"Invalid nil handler");
  145. return;
  146. }
  147. // Add internal options
  148. NSMutableDictionary *tokenOptions = [NSMutableDictionary dictionary];
  149. if (options.count) {
  150. [tokenOptions addEntriesFromDictionary:options];
  151. }
  152. if (tokenOptions[kFIRMessagingTokenOptionsAPNSKey] != nil &&
  153. tokenOptions[kFIRMessagingTokenOptionsAPNSIsSandboxKey] == nil) {
  154. // APNS key was given, but server type is missing. Supply the server type with automatic
  155. // checking. This can happen when the token is requested from FCM, which does not include a
  156. // server type during its request.
  157. tokenOptions[kFIRMessagingTokenOptionsAPNSIsSandboxKey] = @(FIRMessagingIsSandboxApp());
  158. }
  159. if (self.firebaseAppID) {
  160. tokenOptions[kFIRMessagingTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  161. }
  162. // comparing enums to ints directly throws a warning
  163. FIRMessagingErrorCode noError = INT_MAX;
  164. FIRMessagingErrorCode errorCode = noError;
  165. if (![authorizedEntity length]) {
  166. errorCode = kFIRMessagingErrorCodeMissingAuthorizedEntity;
  167. } else if (![scope length]) {
  168. errorCode = kFIRMessagingErrorCodeMissingScope;
  169. } else if (!self.installations) {
  170. errorCode = kFIRMessagingErrorCodeMissingFid;
  171. }
  172. FIRMessagingFCMTokenFetchCompletion newHandler = ^(NSString *token, NSError *error) {
  173. dispatch_async(dispatch_get_main_queue(), ^{
  174. handler(token, error);
  175. });
  176. };
  177. if (errorCode != noError) {
  178. newHandler(
  179. nil,
  180. [NSError messagingErrorWithCode:errorCode
  181. failureReason:@"Failed to send token request, missing critical info."]);
  182. return;
  183. }
  184. FIRMessaging_WEAKIFY(self);
  185. [_authService
  186. fetchCheckinInfoWithHandler:^(FIRMessagingCheckinPreferences *preferences, NSError *error) {
  187. FIRMessaging_STRONGIFY(self);
  188. if (error) {
  189. newHandler(nil, error);
  190. return;
  191. }
  192. FIRMessaging_WEAKIFY(self);
  193. [self->_installations installationIDWithCompletion:^(NSString *_Nullable identifier,
  194. NSError *_Nullable error) {
  195. FIRMessaging_STRONGIFY(self);
  196. if (error) {
  197. newHandler(nil, error);
  198. } else {
  199. FIRMessagingTokenInfo *cachedTokenInfo =
  200. [self cachedTokenInfoWithAuthorizedEntity:authorizedEntity scope:scope];
  201. if (cachedTokenInfo) {
  202. FIRMessagingAPNSInfo *optionsAPNSInfo =
  203. [[FIRMessagingAPNSInfo alloc] initWithTokenOptionsDictionary:tokenOptions];
  204. // Check if APNS Info is changed
  205. if ((!cachedTokenInfo.APNSInfo && !optionsAPNSInfo) ||
  206. [cachedTokenInfo.APNSInfo isEqualToAPNSInfo:optionsAPNSInfo]) {
  207. // check if token is fresh
  208. if ([cachedTokenInfo isFreshWithIID:identifier]) {
  209. newHandler(cachedTokenInfo.token, nil);
  210. return;
  211. }
  212. }
  213. }
  214. [self fetchNewTokenWithAuthorizedEntity:[authorizedEntity copy]
  215. scope:[scope copy]
  216. instanceID:identifier
  217. options:tokenOptions
  218. handler:newHandler];
  219. }
  220. }];
  221. }];
  222. }
  223. - (void)fetchNewTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  224. scope:(NSString *)scope
  225. instanceID:(NSString *)instanceID
  226. options:(NSDictionary *)options
  227. handler:(FIRMessagingFCMTokenFetchCompletion)handler {
  228. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManager000,
  229. @"Fetch new token for authorizedEntity: %@, scope: %@", authorizedEntity,
  230. scope);
  231. FIRMessagingTokenFetchOperation *operation =
  232. [self createFetchOperationWithAuthorizedEntity:authorizedEntity
  233. scope:scope
  234. options:options
  235. instanceID:instanceID];
  236. FIRMessaging_WEAKIFY(self);
  237. FIRMessagingTokenOperationCompletion completion =
  238. ^(FIRMessagingTokenOperationResult result, NSString *_Nullable token,
  239. NSError *_Nullable error) {
  240. FIRMessaging_STRONGIFY(self);
  241. if (error) {
  242. handler(nil, error);
  243. return;
  244. }
  245. if ([self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope]) {
  246. [self postTokenRefreshNotificationWithDefaultFCMToken:token];
  247. }
  248. NSString *firebaseAppID = options[kFIRMessagingTokenOptionsFirebaseAppIDKey];
  249. FIRMessagingTokenInfo *tokenInfo =
  250. [[FIRMessagingTokenInfo alloc] initWithAuthorizedEntity:authorizedEntity
  251. scope:scope
  252. token:token
  253. appVersion:FIRMessagingCurrentAppVersion()
  254. firebaseAppID:firebaseAppID];
  255. tokenInfo.APNSInfo = [[FIRMessagingAPNSInfo alloc] initWithTokenOptionsDictionary:options];
  256. [self->_tokenStore
  257. saveTokenInfo:tokenInfo
  258. handler:^(NSError *error) {
  259. if (!error) {
  260. // Do not send the token back in case the save was unsuccessful. Since with
  261. // the new asychronous fetch mechanism this can lead to infinite loops, for
  262. // example, we will return a valid token even though we weren't able to store
  263. // it in our cache. The first token will lead to a onTokenRefresh callback
  264. // wherein the user again calls `getToken` but since we weren't able to save
  265. // it we won't hit the cache but hit the server again leading to an infinite
  266. // loop.
  267. FIRMessagingLoggerDebug(
  268. kFIRMessagingMessageCodeTokenManager001,
  269. @"Token fetch successful, token: %@, authorizedEntity: %@, scope:%@",
  270. token, authorizedEntity, scope);
  271. if (handler) {
  272. handler(token, nil);
  273. }
  274. } else {
  275. if (handler) {
  276. handler(nil, error);
  277. }
  278. }
  279. }];
  280. };
  281. // Add completion handler, and ensure it's called on the main queue
  282. [operation addCompletionHandler:^(FIRMessagingTokenOperationResult result,
  283. NSString *_Nullable token, NSError *_Nullable error) {
  284. dispatch_async(dispatch_get_main_queue(), ^{
  285. completion(result, token, error);
  286. });
  287. }];
  288. [self.tokenOperations addOperation:operation];
  289. }
  290. - (FIRMessagingTokenInfo *)cachedTokenInfoWithAuthorizedEntity:(NSString *)authorizedEntity
  291. scope:(NSString *)scope {
  292. FIRMessagingTokenInfo *tokenInfo = [_tokenStore tokenInfoWithAuthorizedEntity:authorizedEntity
  293. scope:scope];
  294. return tokenInfo;
  295. }
  296. - (BOOL)isDefaultTokenWithAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope {
  297. if (_fcmSenderID.length != authorizedEntity.length) {
  298. return NO;
  299. }
  300. if (![_fcmSenderID isEqualToString:authorizedEntity]) {
  301. return NO;
  302. }
  303. return [scope isEqualToString:kFIRMessagingDefaultTokenScope];
  304. }
  305. - (void)deleteTokenWithAuthorizedEntity:(NSString *)authorizedEntity
  306. scope:(NSString *)scope
  307. instanceID:(NSString *)instanceID
  308. handler:(FIRMessagingDeleteFCMTokenCompletion)handler {
  309. if ([_tokenStore tokenInfoWithAuthorizedEntity:authorizedEntity scope:scope]) {
  310. [_tokenStore removeTokenWithAuthorizedEntity:authorizedEntity scope:scope];
  311. }
  312. // Does not matter if we cannot find it in the cache. Still make an effort to unregister
  313. // from the server.
  314. FIRMessagingCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  315. FIRMessagingTokenDeleteOperation *operation =
  316. [self createDeleteOperationWithAuthorizedEntity:authorizedEntity
  317. scope:scope
  318. checkinPreferences:checkinPreferences
  319. instanceID:instanceID
  320. action:FIRMessagingTokenActionDeleteToken];
  321. if (handler) {
  322. [operation addCompletionHandler:^(FIRMessagingTokenOperationResult result,
  323. NSString *_Nullable token, NSError *_Nullable error) {
  324. if ([self isDefaultTokenWithAuthorizedEntity:authorizedEntity scope:scope]) {
  325. [self postTokenRefreshNotificationWithDefaultFCMToken:nil];
  326. }
  327. dispatch_async(dispatch_get_main_queue(), ^{
  328. handler(error);
  329. });
  330. }];
  331. }
  332. [self.tokenOperations addOperation:operation];
  333. }
  334. - (void)deleteAllTokensWithHandler:(void (^)(NSError *))handler {
  335. FIRMessaging_WEAKIFY(self);
  336. [self.installations
  337. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  338. FIRMessaging_STRONGIFY(self);
  339. if (error) {
  340. if (handler) {
  341. dispatch_async(dispatch_get_main_queue(), ^{
  342. handler(error);
  343. });
  344. }
  345. return;
  346. }
  347. // delete all tokens
  348. FIRMessagingCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  349. if (!checkinPreferences) {
  350. // The checkin is already deleted. No need to trigger the token delete operation as client
  351. // no longer has the checkin information for server to delete.
  352. dispatch_async(dispatch_get_main_queue(), ^{
  353. handler(nil);
  354. });
  355. return;
  356. }
  357. FIRMessagingTokenDeleteOperation *operation = [self
  358. createDeleteOperationWithAuthorizedEntity:kFIRMessagingKeychainWildcardIdentifier
  359. scope:kFIRMessagingKeychainWildcardIdentifier
  360. checkinPreferences:checkinPreferences
  361. instanceID:identifier
  362. action:FIRMessagingTokenActionDeleteTokenAndIID];
  363. if (handler) {
  364. [operation addCompletionHandler:^(FIRMessagingTokenOperationResult result,
  365. NSString *_Nullable token, NSError *_Nullable error) {
  366. self->_defaultFCMToken = nil;
  367. dispatch_async(dispatch_get_main_queue(), ^{
  368. handler(error);
  369. });
  370. }];
  371. }
  372. [self.tokenOperations addOperation:operation];
  373. }];
  374. }
  375. - (void)deleteAllTokensLocallyWithHandler:(void (^)(NSError *error))handler {
  376. [_tokenStore removeAllTokensWithHandler:handler];
  377. }
  378. - (void)stopAllTokenOperations {
  379. [self.authService stopCheckinRequest];
  380. [self.tokenOperations cancelAllOperations];
  381. }
  382. - (void)deleteWithHandler:(void (^)(NSError *))handler {
  383. FIRMessaging_WEAKIFY(self);
  384. [self deleteAllTokensWithHandler:^(NSError *_Nullable error) {
  385. FIRMessaging_STRONGIFY(self);
  386. if (error) {
  387. handler(error);
  388. return;
  389. }
  390. [self deleteAllTokensLocallyWithHandler:^(NSError *localError) {
  391. [self postTokenRefreshNotificationWithDefaultFCMToken:nil];
  392. self->_defaultFCMToken = nil;
  393. if (localError) {
  394. handler(localError);
  395. return;
  396. }
  397. [self.authService resetCheckinWithHandler:^(NSError *_Nonnull authError) {
  398. handler(authError);
  399. }];
  400. }];
  401. }];
  402. }
  403. #pragma mark - CheckinStore
  404. /**
  405. * Reset the keychain preferences if the app had been deleted earlier and then reinstalled.
  406. * Keychain preferences are not cleared in the above scenario so explicitly clear them.
  407. *
  408. * In case of an iCloud backup and restore the Keychain preferences should already be empty
  409. * since the Keychain items are marked with `*BackupThisDeviceOnly`.
  410. */
  411. - (void)resetCredentialsIfNeeded {
  412. BOOL checkinPlistExists = [_authService hasCheckinPlist];
  413. // Checkin info existed in backup excluded plist. Should not be a fresh install.
  414. if (checkinPlistExists) {
  415. return;
  416. }
  417. // Keychain can still exist even if app is uninstalled.
  418. FIRMessagingCheckinPreferences *oldCheckinPreferences = _authService.checkinPreferences;
  419. if (!oldCheckinPreferences) {
  420. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeStore009,
  421. @"App reset detected but no valid checkin auth preferences found."
  422. @" Will not delete server token registrations.");
  423. return;
  424. }
  425. [_authService resetCheckinWithHandler:^(NSError *_Nonnull error) {
  426. if (!error) {
  427. FIRMessagingLoggerDebug(
  428. kFIRMessagingMessageCodeStore002,
  429. @"Removed cached checkin preferences from Keychain because this is a fresh install.");
  430. } else {
  431. FIRMessagingLoggerError(
  432. kFIRMessagingMessageCodeStore003,
  433. @"Couldn't remove cached checkin preferences for a fresh install. Error: %@", error);
  434. }
  435. if (oldCheckinPreferences.deviceID.length && oldCheckinPreferences.secretToken.length) {
  436. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeStore006,
  437. @"Resetting old checkin and deleting server token registrations.");
  438. // We don't really need to delete old FCM tokens created via IID auth tokens since
  439. // those tokens are already hashed by APNS token as the has so creating a new
  440. // token should automatically delete the old-token.
  441. [self didDeleteFCMScopedTokensForCheckin:oldCheckinPreferences];
  442. }
  443. }];
  444. }
  445. - (void)didDeleteFCMScopedTokensForCheckin:(FIRMessagingCheckinPreferences *)checkin {
  446. // Make a best effort try to delete the old client related state on the FCM server. This is
  447. // required to delete old pubusb registrations which weren't cleared when the app was deleted.
  448. //
  449. // This is only a one time effort. If this call fails the client would still receive duplicate
  450. // pubsub notifications if he is again subscribed to the same topic.
  451. //
  452. // The client state should be cleared on the server for the provided checkin preferences.
  453. FIRMessagingTokenDeleteOperation *operation =
  454. [self createDeleteOperationWithAuthorizedEntity:nil
  455. scope:nil
  456. checkinPreferences:checkin
  457. instanceID:nil
  458. action:FIRMessagingTokenActionDeleteToken];
  459. [operation addCompletionHandler:^(FIRMessagingTokenOperationResult result,
  460. NSString *_Nullable token, NSError *_Nullable error) {
  461. if (error) {
  462. FIRMessagingMessageCode code =
  463. kFIRMessagingMessageCodeTokenManagerErrorDeletingFCMTokensOnAppReset;
  464. FIRMessagingLoggerDebug(code, @"Failed to delete GCM server registrations on app reset.");
  465. } else {
  466. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManagerDeletedFCMTokensOnAppReset,
  467. @"Successfully deleted GCM server registrations on app reset");
  468. }
  469. }];
  470. [self.tokenOperations addOperation:operation];
  471. }
  472. #pragma mark - Unit Testing Stub Helpers
  473. // We really have this method so that we can more easily stub it out for unit testing
  474. - (FIRMessagingTokenFetchOperation *)
  475. createFetchOperationWithAuthorizedEntity:(NSString *)authorizedEntity
  476. scope:(NSString *)scope
  477. options:(NSDictionary<NSString *, NSString *> *)options
  478. instanceID:(NSString *)instanceID {
  479. FIRMessagingCheckinPreferences *checkinPreferences = self.authService.checkinPreferences;
  480. FIRMessagingTokenFetchOperation *operation =
  481. [[FIRMessagingTokenFetchOperation alloc] initWithAuthorizedEntity:authorizedEntity
  482. scope:scope
  483. options:options
  484. checkinPreferences:checkinPreferences
  485. instanceID:instanceID];
  486. return operation;
  487. }
  488. // We really have this method so that we can more easily stub it out for unit testing
  489. - (FIRMessagingTokenDeleteOperation *)
  490. createDeleteOperationWithAuthorizedEntity:(NSString *)authorizedEntity
  491. scope:(NSString *)scope
  492. checkinPreferences:(FIRMessagingCheckinPreferences *)checkinPreferences
  493. instanceID:(NSString *)instanceID
  494. action:(FIRMessagingTokenAction)action {
  495. FIRMessagingTokenDeleteOperation *operation =
  496. [[FIRMessagingTokenDeleteOperation alloc] initWithAuthorizedEntity:authorizedEntity
  497. scope:scope
  498. checkinPreferences:checkinPreferences
  499. instanceID:instanceID
  500. action:action];
  501. return operation;
  502. }
  503. #pragma mark - Invalidating Cached Tokens
  504. - (BOOL)checkTokenRefreshPolicyWithIID:(NSString *)IID {
  505. // We know at least one cached token exists.
  506. BOOL shouldFetchDefaultToken = NO;
  507. NSArray<FIRMessagingTokenInfo *> *tokenInfos = [_tokenStore cachedTokenInfos];
  508. NSMutableArray<FIRMessagingTokenInfo *> *tokenInfosToDelete =
  509. [NSMutableArray arrayWithCapacity:tokenInfos.count];
  510. for (FIRMessagingTokenInfo *tokenInfo in tokenInfos) {
  511. if ([tokenInfo isFreshWithIID:IID]) {
  512. // Token is fresh and in right format, do nothing
  513. continue;
  514. }
  515. if ([tokenInfo isDefaultToken]) {
  516. // Default token is expired, do not mark for deletion. Fetch directly from server to
  517. // replace the current one.
  518. shouldFetchDefaultToken = YES;
  519. } else {
  520. // Non-default token is expired, mark for deletion.
  521. [tokenInfosToDelete addObject:tokenInfo];
  522. }
  523. FIRMessagingLoggerDebug(
  524. kFIRMessagingMessageCodeTokenManagerInvalidateStaleToken,
  525. @"Invalidating cached token for %@ (%@) due to token is no longer fresh.",
  526. tokenInfo.authorizedEntity, tokenInfo.scope);
  527. }
  528. for (FIRMessagingTokenInfo *tokenInfoToDelete in tokenInfosToDelete) {
  529. [_tokenStore removeTokenWithAuthorizedEntity:tokenInfoToDelete.authorizedEntity
  530. scope:tokenInfoToDelete.scope];
  531. }
  532. return shouldFetchDefaultToken;
  533. }
  534. - (NSArray<FIRMessagingTokenInfo *> *)updateTokensToAPNSDeviceToken:(NSData *)deviceToken
  535. isSandbox:(BOOL)isSandbox {
  536. // Each cached IID token that is missing an APNSInfo, or has an APNSInfo associated should be
  537. // checked and invalidated if needed.
  538. FIRMessagingAPNSInfo *APNSInfo = [[FIRMessagingAPNSInfo alloc] initWithDeviceToken:deviceToken
  539. isSandbox:isSandbox];
  540. if ([self.currentAPNSInfo isEqualToAPNSInfo:APNSInfo]) {
  541. return @[];
  542. }
  543. self.currentAPNSInfo = APNSInfo;
  544. NSArray<FIRMessagingTokenInfo *> *tokenInfos = [_tokenStore cachedTokenInfos];
  545. NSMutableArray<FIRMessagingTokenInfo *> *tokenInfosToDelete =
  546. [NSMutableArray arrayWithCapacity:tokenInfos.count];
  547. for (FIRMessagingTokenInfo *cachedTokenInfo in tokenInfos) {
  548. // Check if the cached APNSInfo is nil, or if it is an old APNSInfo.
  549. if (!cachedTokenInfo.APNSInfo ||
  550. ![cachedTokenInfo.APNSInfo isEqualToAPNSInfo:self.currentAPNSInfo]) {
  551. // Mark for invalidation.
  552. [tokenInfosToDelete addObject:cachedTokenInfo];
  553. }
  554. }
  555. for (FIRMessagingTokenInfo *tokenInfoToDelete in tokenInfosToDelete) {
  556. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManagerAPNSChangedTokenInvalidated,
  557. @"Invalidating cached token for %@ (%@) due to APNs token change.",
  558. tokenInfoToDelete.authorizedEntity, tokenInfoToDelete.scope);
  559. [_tokenStore removeTokenWithAuthorizedEntity:tokenInfoToDelete.authorizedEntity
  560. scope:tokenInfoToDelete.scope];
  561. }
  562. return tokenInfosToDelete;
  563. }
  564. #pragma mark - APNS Token
  565. - (void)setAPNSToken:(NSData *)APNSToken withUserInfo:(NSDictionary *)userInfo {
  566. if (!APNSToken || ![APNSToken isKindOfClass:[NSData class]]) {
  567. if ([APNSToken class]) {
  568. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInternal002, @"Invalid APNS token type %@",
  569. NSStringFromClass([APNSToken class]));
  570. } else {
  571. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInternal002, @"Empty APNS token type");
  572. }
  573. return;
  574. }
  575. NSInteger type = [userInfo[kFIRMessagingAPNSTokenType] integerValue];
  576. // The APNS token is being added, or has changed (rare)
  577. if ([self.currentAPNSInfo.deviceToken isEqualToData:APNSToken]) {
  578. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeInstanceID011,
  579. @"Trying to reset APNS token to the same value. Will return");
  580. return;
  581. }
  582. // Use this token type for when we have to automatically fetch tokens in the future
  583. BOOL isSandboxApp = (type == FIRMessagingAPNSTokenTypeSandbox);
  584. if (type == FIRMessagingAPNSTokenTypeUnknown) {
  585. isSandboxApp = FIRMessagingIsSandboxApp();
  586. }
  587. // Pro-actively invalidate the default token, if the APNs change makes it
  588. // invalid. Previously, we invalidated just before fetching the token.
  589. NSArray<FIRMessagingTokenInfo *> *invalidatedTokens =
  590. [self updateTokensToAPNSDeviceToken:APNSToken isSandbox:isSandboxApp];
  591. self.currentAPNSInfo = [[FIRMessagingAPNSInfo alloc] initWithDeviceToken:[APNSToken copy]
  592. isSandbox:isSandboxApp];
  593. // Re-fetch any invalidated tokens automatically, this time with the current APNs token, so that
  594. // they are up-to-date.
  595. if (invalidatedTokens.count > 0) {
  596. FIRMessaging_WEAKIFY(self);
  597. [self.installations
  598. installationIDWithCompletion:^(NSString *_Nullable identifier, NSError *_Nullable error) {
  599. FIRMessaging_STRONGIFY(self);
  600. if (self == nil) {
  601. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID017,
  602. @"Instance ID shut down during token reset. Aborting");
  603. return;
  604. }
  605. if (self.currentAPNSInfo == nil) {
  606. FIRMessagingLoggerError(kFIRMessagingMessageCodeInstanceID018,
  607. @"apnsTokenData was set to nil during token reset. Aborting");
  608. return;
  609. }
  610. NSMutableDictionary *tokenOptions = [@{
  611. kFIRMessagingTokenOptionsAPNSKey : self.currentAPNSInfo.deviceToken,
  612. kFIRMessagingTokenOptionsAPNSIsSandboxKey : @(isSandboxApp)
  613. } mutableCopy];
  614. if (self.firebaseAppID) {
  615. tokenOptions[kFIRMessagingTokenOptionsFirebaseAppIDKey] = self.firebaseAppID;
  616. }
  617. for (FIRMessagingTokenInfo *tokenInfo in invalidatedTokens) {
  618. [self fetchNewTokenWithAuthorizedEntity:tokenInfo.authorizedEntity
  619. scope:tokenInfo.scope
  620. instanceID:identifier
  621. options:tokenOptions
  622. handler:^(NSString *_Nullable token,
  623. NSError *_Nullable error){
  624. }];
  625. }
  626. }];
  627. }
  628. }
  629. #pragma mark - checkin
  630. - (BOOL)hasValidCheckinInfo {
  631. return self.authService.checkinPreferences.hasValidCheckinInfo;
  632. }
  633. @end