FIRMessagingTokenStore.m 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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/FIRMessagingTokenStore.h"
  17. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  20. #import "FirebaseMessaging/Sources/Token/FIRMessagingAuthKeychain.h"
  21. #import "FirebaseMessaging/Sources/Token/FIRMessagingTokenInfo.h"
  22. static NSString *const kFIRMessagingTokenKeychainId = @"com.google.iid-tokens";
  23. @interface FIRMessagingTokenStore ()
  24. @property(nonatomic, readwrite, strong) FIRMessagingAuthKeychain *keychain;
  25. @end
  26. @implementation FIRMessagingTokenStore
  27. - (instancetype)init {
  28. self = [super init];
  29. if (self) {
  30. _keychain = [[FIRMessagingAuthKeychain alloc] initWithIdentifier:kFIRMessagingTokenKeychainId];
  31. }
  32. return self;
  33. }
  34. #pragma mark - Get
  35. + (NSString *)serviceKeyForAuthorizedEntity:(NSString *)authorizedEntity scope:(NSString *)scope {
  36. return [NSString stringWithFormat:@"%@:%@", authorizedEntity, scope];
  37. }
  38. - (nullable FIRMessagingTokenInfo *)tokenInfoWithAuthorizedEntity:(NSString *)authorizedEntity
  39. scope:(NSString *)scope {
  40. // TODO(chliangGoogle): If we don't have the token plist we should delete all the tokens from
  41. // the keychain. This is because not having the plist signifies a backup and restore operation.
  42. // In case the keychain has any tokens these would now be stale and therefore should be
  43. // deleted.
  44. if (![authorizedEntity length] || ![scope length]) {
  45. return nil;
  46. }
  47. NSString *account = FIRMessagingAppIdentifier();
  48. NSString *service = [[self class] serviceKeyForAuthorizedEntity:authorizedEntity scope:scope];
  49. NSData *item = [self.keychain dataForService:service account:account];
  50. if (!item) {
  51. return nil;
  52. }
  53. // Token infos created from legacy storage don't have appVersion, firebaseAppID, or APNSInfo.
  54. FIRMessagingTokenInfo *tokenInfo = [[self class] tokenInfoFromKeychainItem:item];
  55. if ([tokenInfo needsMigration]) {
  56. [self
  57. saveTokenInfo:tokenInfo
  58. handler:^(NSError *error) {
  59. if (error) {
  60. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManager001,
  61. @"Failed to migrate token: %@ account: %@ service %@",
  62. tokenInfo, account, service);
  63. } else {
  64. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManager001,
  65. @"Successful token migration: %@ account: %@ service %@",
  66. tokenInfo, account, service);
  67. }
  68. }];
  69. }
  70. return tokenInfo;
  71. }
  72. - (NSArray<FIRMessagingTokenInfo *> *)cachedTokenInfos {
  73. NSString *account = FIRMessagingAppIdentifier();
  74. NSArray<NSData *> *items =
  75. [self.keychain itemsMatchingService:kFIRMessagingKeychainWildcardIdentifier account:account];
  76. NSMutableArray<FIRMessagingTokenInfo *> *tokenInfos =
  77. [NSMutableArray arrayWithCapacity:items.count];
  78. for (NSData *item in items) {
  79. FIRMessagingTokenInfo *tokenInfo = [[self class] tokenInfoFromKeychainItem:item];
  80. if (tokenInfo) {
  81. [tokenInfos addObject:tokenInfo];
  82. }
  83. }
  84. return tokenInfos;
  85. }
  86. + (nullable FIRMessagingTokenInfo *)tokenInfoFromKeychainItem:(NSData *)item {
  87. // Check if it is saved as an archived FIRMessagingTokenInfo, otherwise return nil.
  88. FIRMessagingTokenInfo *tokenInfo = nil;
  89. if (item) {
  90. @try {
  91. NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingFromData:item
  92. error:nil];
  93. unarchiver.requiresSecureCoding = NO;
  94. [unarchiver setClass:[FIRMessagingTokenInfo class] forClassName:@"FIRInstanceIDTokenInfo"];
  95. tokenInfo = [unarchiver decodeObjectForKey:NSKeyedArchiveRootObjectKey];
  96. [unarchiver finishDecoding];
  97. } @catch (NSException *exception) {
  98. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenStoreExceptionUnarchivingTokenInfo,
  99. @"Unable to parse token info from Keychain item; item was in an "
  100. @"invalid format");
  101. tokenInfo = nil;
  102. } @finally {
  103. }
  104. }
  105. return tokenInfo;
  106. }
  107. #pragma mark - Save
  108. // Token Infos will be saved under these Keychain keys:
  109. // Account: <Main App Bundle ID> (e.g. com.mycompany.myapp)
  110. // Service: <Sender ID>:<Scope> (e.g. 1234567890:*)
  111. - (void)saveTokenInfo:(FIRMessagingTokenInfo *)tokenInfo
  112. handler:(void (^)(NSError *))handler { // Keep the cachetime up-to-date.
  113. tokenInfo.cacheTime = [NSDate date];
  114. // Always write to the Keychain, so that the cacheTime is up-to-date.
  115. NSData *tokenInfoData;
  116. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  117. [NSKeyedArchiver setClassName:@"FIRInstanceIDTokenInfo" forClass:[FIRMessagingTokenInfo class]];
  118. #pragma clang diagnostic push
  119. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  120. tokenInfoData = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  121. #pragma clang diagnostic pop
  122. NSString *account = FIRMessagingAppIdentifier();
  123. NSString *service = [[self class] serviceKeyForAuthorizedEntity:tokenInfo.authorizedEntity
  124. scope:tokenInfo.scope];
  125. [self.keychain setData:tokenInfoData forService:service account:account handler:handler];
  126. }
  127. - (void)saveTokenInfoInCache:(FIRMessagingTokenInfo *)tokenInfo {
  128. tokenInfo.cacheTime = [NSDate date];
  129. // TODO(chliangGoogle): Use the new API and secureCoding protocol.
  130. // Always write to the Keychain, so that the cacheTime is up-to-date.
  131. NSData *tokenInfoData;
  132. [NSKeyedArchiver setClassName:@"FIRInstanceIDTokenInfo" forClass:[FIRMessagingTokenInfo class]];
  133. #pragma clang diagnostic push
  134. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  135. tokenInfoData = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  136. #pragma clang diagnostic pop
  137. NSString *account = FIRMessagingAppIdentifier();
  138. NSString *service = [[self class] serviceKeyForAuthorizedEntity:tokenInfo.authorizedEntity
  139. scope:tokenInfo.scope];
  140. [self.keychain setCacheData:tokenInfoData forService:service account:account];
  141. }
  142. #pragma mark - Delete
  143. - (void)removeTokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity
  144. scope:(nonnull NSString *)scope {
  145. if (![authorizedEntity length] || ![scope length]) {
  146. FIRMessagingLoggerError(kFIRMessagingMessageCodeStore012,
  147. @"Will not delete token with invalid entity: %@, scope: %@",
  148. authorizedEntity, scope);
  149. return;
  150. }
  151. NSString *account = FIRMessagingAppIdentifier();
  152. NSString *service = [[self class] serviceKeyForAuthorizedEntity:authorizedEntity scope:scope];
  153. [self.keychain removeItemsMatchingService:service account:account handler:nil];
  154. }
  155. - (void)removeAllTokensWithHandler:(void (^)(NSError *error))handler {
  156. NSString *account = FIRMessagingAppIdentifier();
  157. [self.keychain removeItemsMatchingService:kFIRMessagingKeychainWildcardIdentifier
  158. account:account
  159. handler:handler];
  160. }
  161. @end