FIRMessagingTokenStore.m 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. return tokenInfo;
  56. }
  57. - (NSArray<FIRMessagingTokenInfo *> *)cachedTokenInfos {
  58. NSString *account = FIRMessagingAppIdentifier();
  59. NSArray<NSData *> *items =
  60. [self.keychain itemsMatchingService:kFIRMessagingKeychainWildcardIdentifier account:account];
  61. NSMutableArray<FIRMessagingTokenInfo *> *tokenInfos =
  62. [NSMutableArray arrayWithCapacity:items.count];
  63. for (NSData *item in items) {
  64. FIRMessagingTokenInfo *tokenInfo = [[self class] tokenInfoFromKeychainItem:item];
  65. if (tokenInfo) {
  66. [tokenInfos addObject:tokenInfo];
  67. }
  68. }
  69. return tokenInfos;
  70. }
  71. + (nullable FIRMessagingTokenInfo *)tokenInfoFromKeychainItem:(NSData *)item {
  72. // Check if it is saved as an archived FIRMessagingTokenInfo, otherwise return nil.
  73. FIRMessagingTokenInfo *tokenInfo = nil;
  74. // NOTE: Passing in nil to unarchiveObjectWithData will result in an iOS error logged
  75. // in the console on iOS 10 and below. Avoid by checking item.data's existence.
  76. if (item) {
  77. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  78. @try {
  79. #pragma clang diagnostic push
  80. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  81. [NSKeyedUnarchiver setClass:[FIRMessagingTokenInfo class]
  82. forClassName:@"FIRInstanceIDTokenInfo"];
  83. tokenInfo = [NSKeyedUnarchiver unarchiveObjectWithData:item];
  84. #pragma clang diagnostic pop
  85. } @catch (NSException *exception) {
  86. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenStoreExceptionUnarchivingTokenInfo,
  87. @"Unable to parse token info from Keychain item; item was in an "
  88. @"invalid format");
  89. tokenInfo = nil;
  90. } @finally {
  91. }
  92. }
  93. return tokenInfo;
  94. }
  95. #pragma mark - Save
  96. // Token Infos will be saved under these Keychain keys:
  97. // Account: <Main App Bundle ID> (e.g. com.mycompany.myapp)
  98. // Service: <Sender ID>:<Scope> (e.g. 1234567890:*)
  99. - (void)saveTokenInfo:(FIRMessagingTokenInfo *)tokenInfo
  100. handler:(void (^)(NSError *))handler { // Keep the cachetime up-to-date.
  101. tokenInfo.cacheTime = [NSDate date];
  102. // Always write to the Keychain, so that the cacheTime is up-to-date.
  103. NSData *tokenInfoData;
  104. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  105. [NSKeyedArchiver setClassName:@"FIRInstanceIDTokenInfo" forClass:[FIRMessagingTokenInfo class]];
  106. #pragma clang diagnostic push
  107. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  108. tokenInfoData = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  109. #pragma clang diagnostic pop
  110. NSString *account = FIRMessagingAppIdentifier();
  111. NSString *service = [[self class] serviceKeyForAuthorizedEntity:tokenInfo.authorizedEntity
  112. scope:tokenInfo.scope];
  113. [self.keychain setData:tokenInfoData forService:service account:account handler:handler];
  114. }
  115. - (void)saveTokenInfoInCache:(FIRMessagingTokenInfo *)tokenInfo {
  116. tokenInfo.cacheTime = [NSDate date];
  117. // TODO(chliangGoogle): Use the new API and secureCoding protocol.
  118. // Always write to the Keychain, so that the cacheTime is up-to-date.
  119. NSData *tokenInfoData;
  120. [NSKeyedArchiver setClassName:@"FIRInstanceIDTokenInfo" forClass:[FIRMessagingTokenInfo class]];
  121. #pragma clang diagnostic push
  122. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  123. tokenInfoData = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  124. #pragma clang diagnostic pop
  125. NSString *account = FIRMessagingAppIdentifier();
  126. NSString *service = [[self class] serviceKeyForAuthorizedEntity:tokenInfo.authorizedEntity
  127. scope:tokenInfo.scope];
  128. [self.keychain setCacheData:tokenInfoData forService:service account:account];
  129. }
  130. #pragma mark - Delete
  131. - (void)removeTokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity
  132. scope:(nonnull NSString *)scope {
  133. if (![authorizedEntity length] || ![scope length]) {
  134. FIRMessagingLoggerError(kFIRMessagingMessageCodeStore012,
  135. @"Will not delete token with invalid entity: %@, scope: %@",
  136. authorizedEntity, scope);
  137. return;
  138. }
  139. NSString *account = FIRMessagingAppIdentifier();
  140. NSString *service = [[self class] serviceKeyForAuthorizedEntity:authorizedEntity scope:scope];
  141. [self.keychain removeItemsMatchingService:service account:account handler:nil];
  142. }
  143. - (void)removeAllTokensWithHandler:(void (^)(NSError *error))handler {
  144. NSString *account = FIRMessagingAppIdentifier();
  145. [self.keychain removeItemsMatchingService:kFIRMessagingKeychainWildcardIdentifier
  146. account:account
  147. handler:handler];
  148. }
  149. @end