FIRMessagingTokenManager.m 33 KB

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