FIRMessagingTokenManager.m 31 KB

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