FIRMessagingTokenManager.m 33 KB

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