FIRMessagingTokenManager.m 32 KB

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