FIRMessagingTokenInfo.m 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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/FIRMessagingTokenInfo.h"
  17. #import "FirebaseMessaging/Sources/FIRMessagingConstants.h"
  18. #import "FirebaseMessaging/Sources/FIRMessagingLogger.h"
  19. #import "FirebaseMessaging/Sources/FIRMessagingUtilities.h"
  20. /**
  21. * @enum Token Info Dictionary Key Constants
  22. * @discussion The keys that are checked when a token info is
  23. * created from a dictionary. The same keys are used
  24. * when decoding/encoding an archive.
  25. */
  26. /// Specifies a dictonary key whose value represents the authorized entity, or
  27. /// Sender ID for the token.
  28. static NSString *const kFIRInstanceIDAuthorizedEntityKey = @"authorized_entity";
  29. /// Specifies a dictionary key whose value represents the scope of the token,
  30. /// typically "*".
  31. static NSString *const kFIRInstanceIDScopeKey = @"scope";
  32. /// Specifies a dictionary key which represents the token value itself.
  33. static NSString *const kFIRInstanceIDTokenKey = @"token";
  34. /// Specifies a dictionary key which represents the app version associated
  35. /// with the token.
  36. static NSString *const kFIRInstanceIDAppVersionKey = @"app_version";
  37. /// Specifies a dictionary key which represents the GMP App ID associated with
  38. /// the token.
  39. static NSString *const kFIRInstanceIDFirebaseAppIDKey = @"firebase_app_id";
  40. /// Specifies a dictionary key representing an archive for a
  41. /// `FIRInstanceIDAPNSInfo` object.
  42. static NSString *const kFIRInstanceIDAPNSInfoKey = @"apns_info";
  43. /// Specifies a dictionary key representing the "last cached" time for the token.
  44. static NSString *const kFIRInstanceIDCacheTimeKey = @"cache_time";
  45. /// Default interval that token stays fresh.
  46. static const NSTimeInterval kDefaultFetchTokenInterval = 7 * 24 * 60 * 60; // 7 days.
  47. @implementation FIRMessagingTokenInfo
  48. - (instancetype)initWithAuthorizedEntity:(NSString *)authorizedEntity
  49. scope:(NSString *)scope
  50. token:(NSString *)token
  51. appVersion:(NSString *)appVersion
  52. firebaseAppID:(NSString *)firebaseAppID {
  53. self = [super init];
  54. if (self) {
  55. _authorizedEntity = [authorizedEntity copy];
  56. _scope = [scope copy];
  57. _token = [token copy];
  58. _appVersion = [appVersion copy];
  59. _firebaseAppID = [firebaseAppID copy];
  60. }
  61. return self;
  62. }
  63. - (BOOL)isFreshWithIID:(NSString *)IID {
  64. // Last fetch token cache time could be null if token is from legacy storage format. Then token is
  65. // considered not fresh and should be refreshed and overwrite with the latest storage format.
  66. if (!IID) {
  67. return NO;
  68. }
  69. if (!_cacheTime) {
  70. return NO;
  71. }
  72. // Check if it's consistent with IID
  73. if (![self.token hasPrefix:IID]) {
  74. return NO;
  75. }
  76. if ([self hasDenylistedScope]) {
  77. return NO;
  78. }
  79. // Check if app has just been updated to a new version.
  80. NSString *currentAppVersion = FIRMessagingCurrentAppVersion();
  81. if (!_appVersion || ![_appVersion isEqualToString:currentAppVersion]) {
  82. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenManager004,
  83. @"Invalidating cached token for %@ (%@) due to app version change.",
  84. _authorizedEntity, _scope);
  85. return NO;
  86. }
  87. // Check if GMP App ID has changed
  88. NSString *currentFirebaseAppID = FIRMessagingFirebaseAppID();
  89. if (!_firebaseAppID || ![_firebaseAppID isEqualToString:currentFirebaseAppID]) {
  90. FIRMessagingLoggerDebug(
  91. kFIRMessagingMessageCodeTokenInfoFirebaseAppIDChanged,
  92. @"Invalidating cached token due to Firebase App IID change from %@ to %@", _firebaseAppID,
  93. currentFirebaseAppID);
  94. return NO;
  95. }
  96. // Check whether locale has changed, if yes, token needs to be updated with server for locale
  97. // information.
  98. if (FIRMessagingHasLocaleChanged()) {
  99. FIRMessagingLoggerDebug(kFIRMessagingMessageCodeTokenInfoLocaleChanged,
  100. @"Invalidating cached token due to locale change");
  101. return NO;
  102. }
  103. // Locale is not changed, check whether token has been fetched within 7 days.
  104. NSTimeInterval lastFetchTokenTimestamp = [_cacheTime timeIntervalSince1970];
  105. NSTimeInterval currentTimestamp = FIRMessagingCurrentTimestampInSeconds();
  106. NSTimeInterval timeSinceLastFetchToken = currentTimestamp - lastFetchTokenTimestamp;
  107. return (timeSinceLastFetchToken < kDefaultFetchTokenInterval);
  108. }
  109. - (BOOL)hasDenylistedScope {
  110. /// The token with fiam scope is set by old FIAM SDK(s) which will remain in keychain for ever. So
  111. /// we need to remove these tokens to deny its usage.
  112. if ([self.scope isEqualToString:kFIRMessagingFIAMTokenScope]) {
  113. return YES;
  114. }
  115. return NO;
  116. }
  117. - (BOOL)isDefaultToken {
  118. return [self.scope isEqualToString:kFIRMessagingDefaultTokenScope];
  119. }
  120. #pragma mark - NSCoding
  121. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
  122. // These value cannot be nil
  123. id authorizedEntity = [aDecoder decodeObjectForKey:kFIRInstanceIDAuthorizedEntityKey];
  124. if (![authorizedEntity isKindOfClass:[NSString class]]) {
  125. return nil;
  126. }
  127. id scope = [aDecoder decodeObjectForKey:kFIRInstanceIDScopeKey];
  128. if (![scope isKindOfClass:[NSString class]]) {
  129. return nil;
  130. }
  131. id token = [aDecoder decodeObjectForKey:kFIRInstanceIDTokenKey];
  132. if (![token isKindOfClass:[NSString class]]) {
  133. return nil;
  134. }
  135. // These values are nullable, so only fail the decode if the type does not match
  136. id appVersion = [aDecoder decodeObjectForKey:kFIRInstanceIDAppVersionKey];
  137. if (appVersion && ![appVersion isKindOfClass:[NSString class]]) {
  138. return nil;
  139. }
  140. id firebaseAppID = [aDecoder decodeObjectForKey:kFIRInstanceIDFirebaseAppIDKey];
  141. if (firebaseAppID && ![firebaseAppID isKindOfClass:[NSString class]]) {
  142. return nil;
  143. }
  144. id rawAPNSInfo = [aDecoder decodeObjectForKey:kFIRInstanceIDAPNSInfoKey];
  145. if (rawAPNSInfo && ![rawAPNSInfo isKindOfClass:[NSData class]]) {
  146. return nil;
  147. }
  148. FIRMessagingAPNSInfo *APNSInfo = nil;
  149. if (rawAPNSInfo) {
  150. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  151. @try {
  152. [NSKeyedUnarchiver setClass:[FIRMessagingAPNSInfo class]
  153. forClassName:@"FIRInstanceIDAPNSInfo"];
  154. #pragma clang diagnostic push
  155. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  156. APNSInfo = [NSKeyedUnarchiver unarchiveObjectWithData:rawAPNSInfo];
  157. #pragma clang diagnostic pop
  158. } @catch (NSException *exception) {
  159. FIRMessagingLoggerInfo(kFIRMessagingMessageCodeTokenInfoBadAPNSInfo,
  160. @"Could not parse raw APNS Info while parsing archived token info.");
  161. APNSInfo = nil;
  162. } @finally {
  163. }
  164. }
  165. id cacheTime = [aDecoder decodeObjectForKey:kFIRInstanceIDCacheTimeKey];
  166. if (cacheTime && ![cacheTime isKindOfClass:[NSDate class]]) {
  167. return nil;
  168. }
  169. self = [super init];
  170. if (self) {
  171. _authorizedEntity = [authorizedEntity copy];
  172. _scope = [scope copy];
  173. _token = [token copy];
  174. _appVersion = [appVersion copy];
  175. _firebaseAppID = [firebaseAppID copy];
  176. _APNSInfo = [APNSInfo copy];
  177. _cacheTime = cacheTime;
  178. }
  179. return self;
  180. }
  181. - (void)encodeWithCoder:(NSCoder *)aCoder {
  182. [aCoder encodeObject:self.authorizedEntity forKey:kFIRInstanceIDAuthorizedEntityKey];
  183. [aCoder encodeObject:self.scope forKey:kFIRInstanceIDScopeKey];
  184. [aCoder encodeObject:self.token forKey:kFIRInstanceIDTokenKey];
  185. [aCoder encodeObject:self.appVersion forKey:kFIRInstanceIDAppVersionKey];
  186. [aCoder encodeObject:self.firebaseAppID forKey:kFIRInstanceIDFirebaseAppIDKey];
  187. NSData *rawAPNSInfo;
  188. if (self.APNSInfo) {
  189. // TODO(chliangGoogle: Use the new API and secureCoding protocol.
  190. [NSKeyedArchiver setClassName:@"FIRInstanceIDAPNSInfo" forClass:[FIRMessagingAPNSInfo class]];
  191. #pragma clang diagnostic push
  192. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  193. rawAPNSInfo = [NSKeyedArchiver archivedDataWithRootObject:self.APNSInfo];
  194. #pragma clang diagnostic pop
  195. [aCoder encodeObject:rawAPNSInfo forKey:kFIRInstanceIDAPNSInfoKey];
  196. }
  197. [aCoder encodeObject:self.cacheTime forKey:kFIRInstanceIDCacheTimeKey];
  198. }
  199. @end