FIRMessagingTokenStore.m 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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. // NOTE: Passing in nil to unarchiveObjectWithData will result in an iOS error logged
  90. // in the console on iOS 10 and below. Avoid by checking item.data's existence.
  91. if (item) {
  92. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  93. @try {
  94. #pragma clang diagnostic push
  95. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  96. [NSKeyedUnarchiver setClass:[FIRMessagingTokenInfo class]
  97. forClassName:@"FIRInstanceIDTokenInfo"];
  98. tokenInfo = [NSKeyedUnarchiver unarchiveObjectWithData:item];
  99. #pragma clang diagnostic pop
  100. } @catch (NSException *exception) {
  101. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenStoreExceptionUnarchivingTokenInfo,
  102. @"Unable to parse token info from Keychain item; item was in an "
  103. @"invalid format");
  104. tokenInfo = nil;
  105. } @finally {
  106. }
  107. }
  108. return tokenInfo;
  109. }
  110. #pragma mark - Save
  111. // Token Infos will be saved under these Keychain keys:
  112. // Account: <Main App Bundle ID> (e.g. com.mycompany.myapp)
  113. // Service: <Sender ID>:<Scope> (e.g. 1234567890:*)
  114. - (void)saveTokenInfo:(FIRMessagingTokenInfo *)tokenInfo
  115. handler:(void (^)(NSError *))handler { // Keep the cachetime up-to-date.
  116. tokenInfo.cacheTime = [NSDate date];
  117. // Always write to the Keychain, so that the cacheTime is up-to-date.
  118. NSData *tokenInfoData;
  119. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  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 setData:tokenInfoData forService:service account:account handler:handler];
  129. }
  130. - (void)saveTokenInfoInCache:(FIRMessagingTokenInfo *)tokenInfo {
  131. tokenInfo.cacheTime = [NSDate date];
  132. // TODO(chliangGoogle): Use the new API and secureCoding protocol.
  133. // Always write to the Keychain, so that the cacheTime is up-to-date.
  134. NSData *tokenInfoData;
  135. [NSKeyedArchiver setClassName:@"FIRInstanceIDTokenInfo" forClass:[FIRMessagingTokenInfo class]];
  136. #pragma clang diagnostic push
  137. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  138. tokenInfoData = [NSKeyedArchiver archivedDataWithRootObject:tokenInfo];
  139. #pragma clang diagnostic pop
  140. NSString *account = FIRMessagingAppIdentifier();
  141. NSString *service = [[self class] serviceKeyForAuthorizedEntity:tokenInfo.authorizedEntity
  142. scope:tokenInfo.scope];
  143. [self.keychain setCacheData:tokenInfoData forService:service account:account];
  144. }
  145. #pragma mark - Delete
  146. - (void)removeTokenWithAuthorizedEntity:(nonnull NSString *)authorizedEntity
  147. scope:(nonnull NSString *)scope {
  148. if (![authorizedEntity length] || ![scope length]) {
  149. FIRMessagingLoggerError(kFIRMessagingMessageCodeStore012,
  150. @"Will not delete token with invalid entity: %@, scope: %@",
  151. authorizedEntity, scope);
  152. return;
  153. }
  154. NSString *account = FIRMessagingAppIdentifier();
  155. NSString *service = [[self class] serviceKeyForAuthorizedEntity:authorizedEntity scope:scope];
  156. [self.keychain removeItemsMatchingService:service account:account handler:nil];
  157. }
  158. - (void)removeAllTokensWithHandler:(void (^)(NSError *error))handler {
  159. NSString *account = FIRMessagingAppIdentifier();
  160. [self.keychain removeItemsMatchingService:kFIRMessagingKeychainWildcardIdentifier
  161. account:account
  162. handler:handler];
  163. }
  164. @end