FIRMessagingTokenManager.m 30 KB

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