FIRAppCheckTokenRefresher.m 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. /*
  2. * Copyright 2021 Google LLC
  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 "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h"
  17. #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h"
  18. #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTimer.h"
  19. #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h"
  20. NS_ASSUME_NONNULL_BEGIN
  21. static const NSTimeInterval kInitialBackoffTimeInterval = 30;
  22. static const NSTimeInterval kMaximumBackoffTimeInterval = 16 * 60;
  23. static const NSTimeInterval kMinimumAutoRefreshTimeInterval = 60; // 1 min.
  24. /// How much time in advance to auto-refresh token before it's expiration. E.g. 0.5 means that the
  25. /// token will be refreshed half way through it's intended time to live.
  26. static const double kAutoRefreshFraction = 0.5;
  27. @interface FIRAppCheckTokenRefresher ()
  28. @property(nonatomic, readonly) dispatch_queue_t refreshQueue;
  29. @property(nonatomic, readonly) id<FIRAppCheckSettingsProtocol> settings;
  30. @property(nonatomic, readonly) FIRTimerProvider timerProvider;
  31. @property(atomic, nullable) id<FIRAppCheckTimerProtocol> timer;
  32. @property(atomic) NSUInteger retryCount;
  33. /// Initial refresh result to be used when `tokenRefreshHandler` has been sent.
  34. @property(nonatomic, nullable) FIRAppCheckTokenRefreshResult *initialRefreshResult;
  35. @end
  36. @implementation FIRAppCheckTokenRefresher
  37. @synthesize tokenRefreshHandler = _tokenRefreshHandler;
  38. - (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult
  39. timerProvider:(FIRTimerProvider)timerProvider
  40. settings:(id<FIRAppCheckSettingsProtocol>)settings {
  41. self = [super init];
  42. if (self) {
  43. _refreshQueue =
  44. dispatch_queue_create("com.firebase.FIRAppCheckTokenRefresher", DISPATCH_QUEUE_SERIAL);
  45. _initialRefreshResult = refreshResult;
  46. _timerProvider = timerProvider;
  47. _settings = settings;
  48. }
  49. return self;
  50. }
  51. - (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult
  52. settings:(id<FIRAppCheckSettingsProtocol>)settings {
  53. return [self initWithRefreshResult:refreshResult
  54. timerProvider:[FIRAppCheckTimer timerProvider]
  55. settings:settings];
  56. }
  57. - (void)dealloc {
  58. [self cancelTimer];
  59. }
  60. - (void)setTokenRefreshHandler:(FIRAppCheckTokenRefreshBlock)tokenRefreshHandler {
  61. @synchronized(self) {
  62. _tokenRefreshHandler = tokenRefreshHandler;
  63. // Check if handler is being set for the first time and if yes then schedule first refresh.
  64. if (tokenRefreshHandler && self.initialRefreshResult) {
  65. FIRAppCheckTokenRefreshResult *initialTokenRefreshResult = self.initialRefreshResult;
  66. self.initialRefreshResult = nil;
  67. [self scheduleWithTokenRefreshResult:initialTokenRefreshResult];
  68. }
  69. }
  70. }
  71. - (FIRAppCheckTokenRefreshBlock)tokenRefreshHandler {
  72. @synchronized(self) {
  73. return _tokenRefreshHandler;
  74. }
  75. }
  76. - (void)updateWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult {
  77. switch (refreshResult.status) {
  78. case FIRAppCheckTokenRefreshStatusNever:
  79. case FIRAppCheckTokenRefreshStatusSuccess:
  80. self.retryCount = 0;
  81. break;
  82. case FIRAppCheckTokenRefreshStatusFailure:
  83. self.retryCount += 1;
  84. break;
  85. }
  86. [self scheduleWithTokenRefreshResult:refreshResult];
  87. }
  88. - (void)refresh {
  89. if (self.tokenRefreshHandler == nil) {
  90. return;
  91. }
  92. if (!self.settings.isTokenAutoRefreshEnabled) {
  93. return;
  94. }
  95. __auto_type __weak weakSelf = self;
  96. self.tokenRefreshHandler(^(FIRAppCheckTokenRefreshResult *refreshResult) {
  97. __auto_type strongSelf = weakSelf;
  98. [strongSelf updateWithRefreshResult:refreshResult];
  99. });
  100. }
  101. - (void)scheduleWithTokenRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult {
  102. // Schedule the refresh only when allowed.
  103. if (self.settings.isTokenAutoRefreshEnabled) {
  104. NSDate *refreshDate = [self nextRefreshDateWithTokenRefreshResult:refreshResult];
  105. [self scheduleRefreshAtDate:refreshDate];
  106. }
  107. }
  108. - (void)scheduleRefreshAtDate:(NSDate *)refreshDate {
  109. [self cancelTimer];
  110. NSTimeInterval scheduleInSec = [refreshDate timeIntervalSinceNow];
  111. __auto_type __weak weakSelf = self;
  112. dispatch_block_t refreshHandler = ^{
  113. __auto_type strongSelf = weakSelf;
  114. [strongSelf refresh];
  115. };
  116. // Refresh straight away if the refresh time is too close.
  117. if (scheduleInSec <= 0) {
  118. dispatch_async(self.refreshQueue, refreshHandler);
  119. return;
  120. }
  121. self.timer = self.timerProvider(refreshDate, self.refreshQueue, refreshHandler);
  122. }
  123. - (void)cancelTimer {
  124. [self.timer invalidate];
  125. }
  126. - (NSDate *)nextRefreshDateWithTokenRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult {
  127. switch (refreshResult.status) {
  128. case FIRAppCheckTokenRefreshStatusSuccess: {
  129. NSTimeInterval timeToLive = [refreshResult.tokenExpirationDate
  130. timeIntervalSinceDate:refreshResult.tokenReceivedAtDate];
  131. timeToLive = MAX(timeToLive, 0);
  132. // Refresh in 50% of TTL + 5 min.
  133. NSTimeInterval targetRefreshSinceReceivedDate = timeToLive * kAutoRefreshFraction + 5 * 60;
  134. NSDate *targetRefreshDate = [refreshResult.tokenReceivedAtDate
  135. dateByAddingTimeInterval:targetRefreshSinceReceivedDate];
  136. // Don't schedule later than expiration date.
  137. NSDate *refreshDate = [targetRefreshDate earlierDate:refreshResult.tokenExpirationDate];
  138. // Don't schedule a refresh earlier than in 1 min from now.
  139. if ([refreshDate timeIntervalSinceNow] < kMinimumAutoRefreshTimeInterval) {
  140. refreshDate = [NSDate dateWithTimeIntervalSinceNow:kMinimumAutoRefreshTimeInterval];
  141. }
  142. return refreshDate;
  143. } break;
  144. case FIRAppCheckTokenRefreshStatusFailure: {
  145. // Repeat refresh attempt later.
  146. NSTimeInterval backoffTime = [[self class] backoffTimeForRetryCount:self.retryCount];
  147. return [NSDate dateWithTimeIntervalSinceNow:backoffTime];
  148. } break;
  149. case FIRAppCheckTokenRefreshStatusNever:
  150. // Refresh ASAP.
  151. return [NSDate date];
  152. break;
  153. }
  154. }
  155. #pragma mark - Backoff
  156. + (NSTimeInterval)backoffTimeForRetryCount:(NSInteger)retryCount {
  157. if (retryCount == 0) {
  158. // No backoff for the first attempt.
  159. return 0;
  160. }
  161. NSTimeInterval exponentialInterval =
  162. kInitialBackoffTimeInterval * pow(2, retryCount - 1) + [self randomMilliseconds];
  163. return MIN(exponentialInterval, kMaximumBackoffTimeInterval);
  164. }
  165. + (NSTimeInterval)randomMilliseconds {
  166. int32_t random_millis = ABS(arc4random() % 1000);
  167. return (double)random_millis * 0.001;
  168. }
  169. @end
  170. NS_ASSUME_NONNULL_END