From 2ec4dbdae4087787dba18b719dd53949944a2423 Mon Sep 17 00:00:00 2001 From: Maksym Malyhin Date: Fri, 11 Jun 2021 17:35:37 -0400 Subject: [PATCH] App Check: optimize auto-refresh (#8232) * App Attest provider: attestation sequence (#7971) * App Attest provider: attestation sequence (#761) * App Attest draft WIP * FIRAppAttestProvider initializers * ./scripts/style.sh * FIRAppAttestProvider implementation draft * Basic FIRAppAttestProviderTests and fixes * style * testGetTokenWhenAppAttestIsNotSupported * More FIRAppAttestProviderTests * Cleanup * Remove unused file * Availability annotations on DCAppAttestService category. * Guard FIRAppAttestProvider with #if TARGET_OS_IOS * Formatting * Fix SPM * app_check.yaml: Add diagnostics SPM builds * fix yaml * Fix Firebase-Package scheme bad merge * Fix typo * FIRAppAttestProvider: hide default init * FIRAppAttestKeyIDStorage: methods placeholders * Comments * Fix updated block definition * Implement app attest key ID storage (#8014) * Implement FIRAppAttestKeyIDStorage * Add FIRAppAttestKeyIDStorageTests * Review [Draft] * Style * Docs updates * Docs updates 2 * Review [Draft] 2 * Improve tests * Improve test readability * Improve test readability 2 * App Check App Attest workflow updates: initial handshake (#8032) * Handshake adjustments (WIP) * Introduce FIRAppAttestProviderState * WIP: calculate attestation state * WIP: calculate attestation state 2 * formatting * Comments and moving code around * Fix init in tests * Fix state calculation flow * Cleanup state calculation and fix tests. * Cleanup and fixes. * Comments * formatting * Fix import * Typo fixes and additional comments * FIRAppAttestInitialHandshakeResponse API * Cleanup state calculation using FBLPromiseAwait * Cleanup * style * FIRAppAttestArtifactStorage implementation and tests (#8041) * Update comments * FIRAppAttestArtifactStorage implementation and tests * Fix init * API docs * Clean up storage in tests * Comments * Disable Keychain dependent tests for SPM * Implement App Attest `getRandomChallenge` (#8033) * Initial implementation * Parse response body for challenge and stub test cases * Review [Draft] * Avoid encoding challenge again * Add tests * Revert "Avoid encoding challenge again" and add TODO This reverts commit 69eb00dfe2b5bc25a03f2e971bfc7ae6531bbeee. * Document tests; Add test * Tests: Add URL validation check * Review * Define Exchange AppAttest Assertion for FAC token API (#8058) * App Check App Attest: attestation request (#8059) * App Attest provider API integration WIP * update tests * Draft attestation response parsing * Attestation request draft * style * AppAttest Attestation API tests draft * Error cases tests * style * Cleanup and API docs * Merge fix * Fix OCMock imports * Fix nullability modifier * Formatting * comments * App Check App Attest initial handshake adjustments (#8067) * calculatre sha256 of random challenge for attestation * Test app adjustments * cleanup * use trailing closures in the test app * Implement API for ExchangeAppAttestAssertionRequest endpoint (#8065) * Implement assertion exchange * Tweak existing tests * Add tests * Rename JSON to better match gRPC message * Add HTTPBody helper * Review * Review 2 * Review 3 * App Check App Attest assertion flow (#8083) * App Attest assertion workflow draft * send request * assertion flow tests * style * App Check: store App Attest artifact per key ID (#8097) * Update artifact storage API and tests * Artifact storage implementation update * Save artifact for a key ID * Style * typos * App Check: prevent concurrent token requests (#8117) * App Attest multiple get token method invocation tests * Ensure a single App Attest handshake sequence at the time * FIRAppCheckTests: get token request merging tests * FIRAppCheck: Ensure a single get token operation at the time * formatting * Test new request after merged requests * Release finished operation promise * Style * Typos * typo * Request merging tests for error cases * formatting * Changelog * App Check App Attest: handle attestation rejection (#8170) * Remove/update outdated TODOs * [WIP] Attestation rejection handling draft * style * retry tests draft * reset key ID before retry * Reset attestation * test error and fixes * style * More details in the name * Some debug logging * style * Use specific codes for log messages * style * Add FIRAppAttestProvider.h the umbrella header * Add receivedAtDate property to the FAC token * Update tests to check receivedAtDate field where important * [WIP] Use FIRAppCheckTokenRefreshResult instead in the refresher API * [WIP] Fix refgresher usage * Update tests with new API, keep old logic * Update tests with new logic * WIP * WIP * Initial refresh tests and fixes. * Add #import where needed. * Formatting * Cleanup and test updates * style * Comments * Cleanup and comments * Fix catalyst * Changelog * Changelog version fix * Typo * Cleanup * Typo * Imports order Co-authored-by: Nick Cooke <36927374+ncooke3@users.noreply.github.com> --- FirebaseAppCheck/CHANGELOG.md | 3 +- .../DCAppAttestService+FIRAppAttestService.h | 2 + .../DCAppAttestService+FIRAppAttestService.m | 2 +- .../APIService/FIRAppCheckToken+APIResponse.m | 3 +- FirebaseAppCheck/Sources/Core/FIRAppCheck.m | 22 +- .../Sources/Core/FIRAppCheckToken+Internal.h | 39 +++ .../Sources/Core/FIRAppCheckToken.m | 15 +- .../FIRAppCheckStoredToken+FIRAppCheckToken.m | 7 +- .../Core/Storage/FIRAppCheckStoredToken.h | 12 +- .../Core/Storage/FIRAppCheckStoredToken.m | 9 +- .../FIRAppCheckTokenRefreshResult.h | 63 +++++ .../FIRAppCheckTokenRefreshResult.m | 64 +++++ .../TokenRefresh/FIRAppCheckTokenRefresher.h | 28 +-- .../TokenRefresh/FIRAppCheckTokenRefresher.m | 124 ++++++---- .../FirebaseAppCheck/FIRAppCheckToken.h | 6 +- .../FIRAppAttestAPIServiceTests.m | 6 +- .../Unit/Core/FIRAppCheckIntegrationTests.m | 4 +- .../Tests/Unit/Core/FIRAppCheckStorageTests.m | 9 +- .../Unit/Core/FIRAppCheckStoredTokenTests.m | 9 +- .../Tests/Unit/Core/FIRAppCheckTests.m | 31 +-- .../Core/FIRAppCheckTokenRefresherTests.m | 234 +++++++++++++----- .../FIRAppCheckDebugProviderTests.m | 6 +- .../FIRDeviceCheckProviderTests.m | 6 +- 23 files changed, 524 insertions(+), 180 deletions(-) create mode 100644 FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h create mode 100644 FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h create mode 100644 FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.m diff --git a/FirebaseAppCheck/CHANGELOG.md b/FirebaseAppCheck/CHANGELOG.md index f63a3726530..612465303b3 100644 --- a/FirebaseAppCheck/CHANGELOG.md +++ b/FirebaseAppCheck/CHANGELOG.md @@ -1,4 +1,5 @@ -# 8.1.0 -- M97 +# 8.2.0 -- M98 - [added] Apple's App Attest attestation provider support. (#8133) +- [changed] Token auto-refresh optimizations. (#8232) # v8.0.0 -- M95 - [added] Firebase abuse reduction support SDK. (#7928, #7937, #7948) \ No newline at end of file diff --git a/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.h b/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.h index 98fdbdc31b7..4bc269ff163 100644 --- a/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.h +++ b/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.h @@ -14,6 +14,8 @@ * limitations under the License. */ +#import + // Currently DCAppAttestService is available on iOS only. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST // Catalyst should be possible with Xcode 12.5+ diff --git a/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.m b/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.m index 412221d4b2b..f47848724c9 100644 --- a/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.m +++ b/FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.m @@ -17,7 +17,7 @@ #import "FirebaseAppCheck/Sources/AppAttestProvider/DCAppAttestService+FIRAppAttestService.h" // Currently DCAppAttestService is available on iOS only. -#if TARGET_OS_IOS +#if TARGET_OS_IOS && !TARGET_OS_MACCATALYST // Catalyst should be possible with Xcode 12.5+ @implementation DCAppAttestService (FIRAppAttestService) diff --git a/FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.m b/FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.m index 3fc188144f5..2f063db7555 100644 --- a/FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.m +++ b/FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.m @@ -15,6 +15,7 @@ */ #import "FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #if __has_include() #import @@ -81,7 +82,7 @@ - (nullable instancetype)initWithResponseDict:(NSDictionary *)re NSDate *expirationDate = [requestDate dateByAddingTimeInterval:secondsToLive]; - return [self initWithToken:token expirationDate:expirationDate]; + return [self initWithToken:token expirationDate:expirationDate receivedAtDate:requestDate]; } @end diff --git a/FirebaseAppCheck/Sources/Core/FIRAppCheck.m b/FirebaseAppCheck/Sources/Core/FIRAppCheck.m index 99580e2047d..4e73929f5a3 100644 --- a/FirebaseAppCheck/Sources/Core/FIRAppCheck.m +++ b/FirebaseAppCheck/Sources/Core/FIRAppCheck.m @@ -24,13 +24,14 @@ #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProvider.h" #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProviderFactory.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" #import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h" #import "FirebaseAppCheck/Sources/Core/FIRAppCheckLogger.h" #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #import "FirebaseAppCheck/Sources/Core/FIRAppCheckTokenResult.h" #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStorage.h" +#import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h" #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h" #import "FirebaseAppCheck/Sources/Interop/FIRAppCheckInterop.h" @@ -124,10 +125,10 @@ - (nullable instancetype)initWithApp:(FIRApp *)app { [[FIRAppCheckSettings alloc] initWithApp:app userDefault:[NSUserDefaults standardUserDefaults] mainBundle:[NSBundle mainBundle]]; + FIRAppCheckTokenRefreshResult *refreshResult = + [[FIRAppCheckTokenRefreshResult alloc] initWithStatusNever]; FIRAppCheckTokenRefresher *tokenRefresher = - [[FIRAppCheckTokenRefresher alloc] initWithTokenExpirationDate:[NSDate date] - tokenExpirationThreshold:kTokenExpirationThreshold - settings:settings]; + [[FIRAppCheckTokenRefresher alloc] initWithRefreshResult:refreshResult settings:settings]; FIRAppCheckStorage *storage = [[FIRAppCheckStorage alloc] initWithAppName:app.name appID:app.options.googleAppID @@ -306,7 +307,10 @@ - (nonnull NSString *)notificationTokenKey { // TODO: Make sure the self.tokenRefresher is updated only once. Currently the timer will be // updated twice in the case when the refresh triggered by self.tokenRefresher, but it // should be fine for now as it is a relatively cheap operation. - [self.tokenRefresher updateTokenExpirationDate:token.expirationDate]; + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:token.expirationDate + receivedAtDate:token.receivedAtDate]; + [self.tokenRefresher updateWithRefreshResult:refreshResult]; [self postTokenUpdateNotificationWithToken:token]; return token; }); @@ -317,11 +321,15 @@ - (nonnull NSString *)notificationTokenKey { - (void)periodicTokenRefreshWithCompletion:(FIRAppCheckTokenRefreshCompletion)completion { [self retrieveOrRefreshTokenForcingRefresh:NO] .then(^id _Nullable(FIRAppCheckToken *_Nullable token) { - completion(YES, token.expirationDate); + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:token.expirationDate + receivedAtDate:token.receivedAtDate]; + completion(refreshResult); return nil; }) .catch(^(NSError *error) { - completion(NO, nil); + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] initWithStatusFailure]; + completion(refreshResult); }); } diff --git a/FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h b/FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h new file mode 100644 index 00000000000..48c55d2b6fc --- /dev/null +++ b/FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h @@ -0,0 +1,39 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAppCheckToken () + +/// A date when the Firebase App Check token was received in the device's local time. +@property(nonatomic) NSDate *receivedAtDate; + +/// The designated initializer. +/// @param token A Firebase App Check token. +/// @param expirationDate A Firebase App Check token expiration date in the device local time. +/// @param receivedAtDate A date when the Firebase App Check token was received in the device's +/// local time. +- (instancetype)initWithToken:(NSString *)token + expirationDate:(NSDate *)expirationDate + receivedAtDate:(NSDate *)receivedAtDate NS_DESIGNATED_INITIALIZER; + +@end + +NS_ASSUME_NONNULL_END diff --git a/FirebaseAppCheck/Sources/Core/FIRAppCheckToken.m b/FirebaseAppCheck/Sources/Core/FIRAppCheckToken.m index 20d9a830561..35af5adde09 100644 --- a/FirebaseAppCheck/Sources/Core/FIRAppCheckToken.m +++ b/FirebaseAppCheck/Sources/Core/FIRAppCheckToken.m @@ -14,17 +14,28 @@ * limitations under the License. */ -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" + +NS_ASSUME_NONNULL_BEGIN @implementation FIRAppCheckToken -- (instancetype)initWithToken:(NSString *)token expirationDate:(NSDate *)expirationDate { +- (instancetype)initWithToken:(NSString *)token + expirationDate:(NSDate *)expirationDate + receivedAtDate:(NSDate *)receivedAtDate { self = [super init]; if (self) { _token = [token copy]; _expirationDate = expirationDate; + _receivedAtDate = receivedAtDate; } return self; } +- (instancetype)initWithToken:(NSString *)token expirationDate:(NSDate *)expirationDate { + return [self initWithToken:token expirationDate:expirationDate receivedAtDate:[NSDate date]]; +} + @end + +NS_ASSUME_NONNULL_END diff --git a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.m b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.m index 4fd25df2132..9135854709e 100644 --- a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.m +++ b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.m @@ -16,17 +16,20 @@ #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" @implementation FIRAppCheckStoredToken (FIRAppCheckToken) - (void)updateWithToken:(FIRAppCheckToken *)token { self.token = token.token; self.expirationDate = token.expirationDate; + self.receivedAtDate = token.receivedAtDate; } - (FIRAppCheckToken *)appCheckToken { - return [[FIRAppCheckToken alloc] initWithToken:self.token expirationDate:self.expirationDate]; + return [[FIRAppCheckToken alloc] initWithToken:self.token + expirationDate:self.expirationDate + receivedAtDate:self.receivedAtDate]; } @end diff --git a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.h b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.h index c2c4e2a900d..63f46764009 100644 --- a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.h +++ b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.h @@ -22,10 +22,14 @@ NS_ASSUME_NONNULL_BEGIN @interface FIRAppCheckStoredToken : NSObject -/// FAA token. -@property(nonatomic, copy) NSString *token; -/// FAA token expiration date in the device local time. -@property(nonatomic, strong) NSDate *expirationDate; +/// The Firebase App Check token. +@property(nonatomic, copy, nullable) NSString *token; + +/// The Firebase App Check token expiration date in the device local time. +@property(nonatomic, strong, nullable) NSDate *expirationDate; + +/// The date when the Firebase App Check token was received in the device's local time. +@property(nonatomic, strong, nullable) NSDate *receivedAtDate; /// The version of local storage. @property(nonatomic, readonly) NSInteger storageVersion; diff --git a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.m b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.m index e7cf78ac7c0..217f2c77da3 100644 --- a/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.m +++ b/FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.m @@ -18,9 +18,10 @@ static NSString *const kTokenKey = @"token"; static NSString *const kExpirationDateKey = @"expirationDate"; +static NSString *const kReceivedAtDateKey = @"receivedAtDate"; static NSString *const kStorageVersionKey = @"storageVersion"; -static const NSInteger kStorageVersion = 1; +static const NSInteger kStorageVersion = 2; NS_ASSUME_NONNULL_BEGIN @@ -37,19 +38,21 @@ + (BOOL)supportsSecureCoding { - (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.token forKey:kTokenKey]; [coder encodeObject:self.expirationDate forKey:kExpirationDateKey]; + [coder encodeObject:self.receivedAtDate forKey:kReceivedAtDateKey]; [coder encodeInteger:self.storageVersion forKey:kStorageVersionKey]; } - (nullable instancetype)initWithCoder:(NSCoder *)coder { self = [super init]; if (self) { - NSInteger storageVersion = [coder decodeIntegerForKey:kStorageVersionKey]; - if (storageVersion > kStorageVersion) { + NSInteger decodedStorageVersion = [coder decodeIntegerForKey:kStorageVersionKey]; + if (decodedStorageVersion > kStorageVersion) { // TODO: Log a message. } _token = [coder decodeObjectOfClass:[NSString class] forKey:kTokenKey]; _expirationDate = [coder decodeObjectOfClass:[NSDate class] forKey:kExpirationDateKey]; + _receivedAtDate = [coder decodeObjectOfClass:[NSDate class] forKey:kReceivedAtDateKey]; } return self; } diff --git a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h new file mode 100644 index 00000000000..8d899efa61f --- /dev/null +++ b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h @@ -0,0 +1,63 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import + +NS_ASSUME_NONNULL_BEGIN + +/// Represents possible results of a Firebase App Check token refresh attempt that matter for +/// `FIRAppCheckTokenRefresher`. +typedef NS_ENUM(NSInteger, FIRAppCheckTokenRefreshStatus) { + // The token has not been refreshed. + FIRAppCheckTokenRefreshStatusNever, + + // The token was successfully refreshed. + FIRAppCheckTokenRefreshStatusSuccess, + + // The token refresh failed. + FIRAppCheckTokenRefreshStatusFailure +}; + +/// An object to pass the possible results of a Firebase App Check token refresh attempt and +/// supplementary data. +@interface FIRAppCheckTokenRefreshResult : NSObject + +/// Status of the refresh. +@property(nonatomic, readonly) FIRAppCheckTokenRefreshStatus status; + +/// A date when the new Firebase App Check token is expiring. +@property(nonatomic, readonly, nullable) NSDate *tokenExpirationDate; + +/// A date when the new Firebase App Check token was received from the server. +@property(nonatomic, readonly, nullable) NSDate *tokenReceivedAtDate; + +- (instancetype)init NS_UNAVAILABLE; + +/// Initializes the instance with `FIRAppCheckTokenRefreshStatusNever`. +- (instancetype)initWithStatusNever; + +/// Initializes the instance with `FIRAppCheckTokenRefreshStatusFailure`. +- (instancetype)initWithStatusFailure; + +/// Initializes the instance with `FIRAppCheckTokenRefreshStatusSuccess`. +/// @param tokenExpirationDate See `tokenExpirationDate` property. +/// @param tokenReceivedAtDate See `tokenReceivedAtDate` property. +- (instancetype)initWithStatusSuccessAndExpirationDate:(NSDate *)tokenExpirationDate + receivedAtDate:(NSDate *)tokenReceivedAtDate; + +@end + +NS_ASSUME_NONNULL_END diff --git a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.m b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.m new file mode 100644 index 00000000000..edaf242dd47 --- /dev/null +++ b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.m @@ -0,0 +1,64 @@ +/* + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h" + +NS_ASSUME_NONNULL_BEGIN + +@interface FIRAppCheckTokenRefreshResult () + +- (instancetype)initWithStatus:(FIRAppCheckTokenRefreshStatus)status + expirationDate:(nullable NSDate *)tokenExpirationDate + receivedAtDate:(nullable NSDate *)tokenReceivedAtDate NS_DESIGNATED_INITIALIZER; + +@end + +@implementation FIRAppCheckTokenRefreshResult + +- (instancetype)initWithStatus:(FIRAppCheckTokenRefreshStatus)status + expirationDate:(nullable NSDate *)tokenExpirationDate + receivedAtDate:(nullable NSDate *)tokenReceivedAtDate { + self = [super init]; + if (self) { + _status = status; + _tokenExpirationDate = tokenExpirationDate; + _tokenReceivedAtDate = tokenReceivedAtDate; + } + return self; +} + +- (instancetype)initWithStatusNever { + return [self initWithStatus:FIRAppCheckTokenRefreshStatusNever + expirationDate:nil + receivedAtDate:nil]; +} + +- (instancetype)initWithStatusFailure { + return [self initWithStatus:FIRAppCheckTokenRefreshStatusFailure + expirationDate:nil + receivedAtDate:nil]; +} + +- (instancetype)initWithStatusSuccessAndExpirationDate:(NSDate *)tokenExpirationDate + receivedAtDate:(NSDate *)tokenReceivedAtDate { + return [self initWithStatus:FIRAppCheckTokenRefreshStatusSuccess + expirationDate:tokenExpirationDate + receivedAtDate:tokenReceivedAtDate]; +} + +@end + +NS_ASSUME_NONNULL_END diff --git a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h index 5aee56c828d..26bdca9acfc 100644 --- a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h +++ b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h @@ -19,15 +19,14 @@ #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTimer.h" @protocol FIRAppCheckSettingsProtocol; +@class FIRAppCheckTokenRefreshResult; NS_ASSUME_NONNULL_BEGIN /** The block to be called on the token refresh completion. - * @param success If refresh was successful. - * @param tokenExpirationDate The date when the token will expire. + * @param refreshResult The refresh result. */ -typedef void (^FIRAppCheckTokenRefreshCompletion)(BOOL success, - NSDate *_Nullable tokenExpirationDate); +typedef void (^FIRAppCheckTokenRefreshCompletion)(FIRAppCheckTokenRefreshResult *refreshResult); /** The block that will be called by `FIRAppCheckTokenRefresher` to trigger the token refresh. * @param completion The block that the client must call when the token refresh was completed. @@ -42,8 +41,8 @@ typedef void (^FIRAppCheckTokenRefreshBlock)(FIRAppCheckTokenRefreshCompletion c /// Updates the next refresh date based on the new token expiration date. This method should be /// called when the token update was initiated not by the refresher. -/// @param tokenExpirationDate A new token expiration date. -- (void)updateTokenExpirationDate:(NSDate *)tokenExpirationDate; +/// @param refreshResult A result of a refresh attempt. +- (void)updateWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult; @end @@ -54,21 +53,16 @@ typedef void (^FIRAppCheckTokenRefreshBlock)(FIRAppCheckTokenRefreshCompletion c - (instancetype)init NS_UNAVAILABLE; /// The designated initializer. -/// @param tokenExpirationDate The initial token expiration date when known. Pass current date or -/// date in the past to trigger refresh once `tokenRefreshHandler` is set. -/// @param tokenExpirationThreshold The token refresh will be triggered `tokenExpirationThreshold` -/// seconds before the actual token expiration time. +/// @param refreshResult A previous token refresh attempt result. /// @param settings An object that handles Firebase app check settings. -- (instancetype)initWithTokenExpirationDate:(NSDate *)tokenExpirationDate - tokenExpirationThreshold:(NSTimeInterval)tokenExpirationThreshold - timerProvider:(FIRTimerProvider)timerProvider - settings:(id)settings +- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult + timerProvider:(FIRTimerProvider)timerProvider + settings:(id)settings NS_DESIGNATED_INITIALIZER; /// A convenience initializer with a timer provider returning an instance of `FIRAppCheckTimer`. -- (instancetype)initWithTokenExpirationDate:(NSDate *)tokenExpirationDate - tokenExpirationThreshold:(NSTimeInterval)tokenExpirationThreshold - settings:(id)settings; +- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult + settings:(id)settings; @end diff --git a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.m b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.m index 07d7bd9a5d9..be52ace97e5 100644 --- a/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.m +++ b/FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.m @@ -18,12 +18,19 @@ #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h" #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTimer.h" +#import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h" NS_ASSUME_NONNULL_BEGIN static const NSTimeInterval kInitialBackoffTimeInterval = 30; static const NSTimeInterval kMaximumBackoffTimeInterval = 16 * 60; +static const NSTimeInterval kMinimumAutoRefreshTimeInterval = 60; // 1 min. + +/// How much time in advance to auto-refresh token before it's expiration. E.g. 0.5 means that the +/// token will be refreshed half way through it's intended time to live. +static const double kAutoRefreshFraction = 0.5; + @interface FIRAppCheckTokenRefresher () @property(nonatomic, readonly) dispatch_queue_t refreshQueue; @@ -34,8 +41,8 @@ @interface FIRAppCheckTokenRefresher () @property(atomic, nullable) id timer; @property(atomic) NSUInteger retryCount; -@property(nonatomic, nullable) NSDate *initialTokenExpirationDate; -@property(nonatomic, readonly) NSTimeInterval tokenExpirationThreshold; +/// Initial refresh result to be used when `tokenRefreshHandler` has been sent. +@property(nonatomic, nullable) FIRAppCheckTokenRefreshResult *initialRefreshResult; @end @@ -43,29 +50,25 @@ @implementation FIRAppCheckTokenRefresher @synthesize tokenRefreshHandler = _tokenRefreshHandler; -- (instancetype)initWithTokenExpirationDate:(NSDate *)tokenExpirationDate - tokenExpirationThreshold:(NSTimeInterval)tokenExpirationThreshold - timerProvider:(FIRTimerProvider)timerProvider - settings:(id)settings { +- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult + timerProvider:(FIRTimerProvider)timerProvider + settings:(id)settings { self = [super init]; if (self) { _refreshQueue = dispatch_queue_create("com.firebase.FIRAppCheckTokenRefresher", DISPATCH_QUEUE_SERIAL); - _tokenExpirationThreshold = tokenExpirationThreshold; - _initialTokenExpirationDate = tokenExpirationDate; + _initialRefreshResult = refreshResult; _timerProvider = timerProvider; _settings = settings; } return self; } -- (instancetype)initWithTokenExpirationDate:(NSDate *)tokenExpirationDate - tokenExpirationThreshold:(NSTimeInterval)tokenExpirationThreshold - settings:(id)settings { - return [self initWithTokenExpirationDate:tokenExpirationDate - tokenExpirationThreshold:tokenExpirationThreshold - timerProvider:[FIRAppCheckTimer timerProvider] - settings:settings]; +- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult + settings:(id)settings { + return [self initWithRefreshResult:refreshResult + timerProvider:[FIRAppCheckTimer timerProvider] + settings:settings]; } - (void)dealloc { @@ -77,11 +80,10 @@ - (void)setTokenRefreshHandler:(FIRAppCheckTokenRefreshBlock)tokenRefreshHandler _tokenRefreshHandler = tokenRefreshHandler; // Check if handler is being set for the first time and if yes then schedule first refresh. - if (tokenRefreshHandler && self.initialTokenExpirationDate && - self.settings.isTokenAutoRefreshEnabled) { - NSDate *initialTokenExpirationDate = self.initialTokenExpirationDate; - self.initialTokenExpirationDate = nil; - [self scheduleWithTokenExpirationDate:initialTokenExpirationDate]; + if (tokenRefreshHandler && self.initialRefreshResult) { + FIRAppCheckTokenRefreshResult *initialTokenRefreshResult = self.initialRefreshResult; + self.initialRefreshResult = nil; + [self scheduleWithTokenRefreshResult:initialTokenRefreshResult]; } } } @@ -92,10 +94,19 @@ - (FIRAppCheckTokenRefreshBlock)tokenRefreshHandler { } } -- (void)updateTokenExpirationDate:(NSDate *)tokenExpirationDate { - if (self.settings.isTokenAutoRefreshEnabled) { - [self scheduleWithTokenExpirationDate:tokenExpirationDate]; +- (void)updateWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult { + switch (refreshResult.status) { + case FIRAppCheckTokenRefreshStatusNever: + case FIRAppCheckTokenRefreshStatusSuccess: + self.retryCount = 0; + break; + + case FIRAppCheckTokenRefreshStatusFailure: + self.retryCount += 1; + break; } + + [self scheduleWithTokenRefreshResult:refreshResult]; } - (void)refresh { @@ -108,25 +119,18 @@ - (void)refresh { } __auto_type __weak weakSelf = self; - self.tokenRefreshHandler(^(BOOL success, NSDate *_Nullable tokenExpirationDate) { + self.tokenRefreshHandler(^(FIRAppCheckTokenRefreshResult *refreshResult) { __auto_type strongSelf = weakSelf; - [strongSelf tokenRefreshedWithSuccess:success tokenExpirationDate:tokenExpirationDate]; + [strongSelf updateWithRefreshResult:refreshResult]; }); } -- (void)tokenRefreshedWithSuccess:(BOOL)success tokenExpirationDate:(NSDate *)tokenExpirationDate { - if (success) { - self.retryCount = 0; - } else { - self.retryCount += 1; +- (void)scheduleWithTokenRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult { + // Schedule the refresh only when allowed. + if (self.settings.isTokenAutoRefreshEnabled) { + NSDate *refreshDate = [self nextRefreshDateWithTokenRefreshResult:refreshResult]; + [self scheduleRefreshAtDate:refreshDate]; } - - [self scheduleWithTokenExpirationDate:tokenExpirationDate ?: [NSDate date]]; -} - -- (void)scheduleWithTokenExpirationDate:(NSDate *)tokenExpirationDate { - NSDate *refreshDate = [self nextRefreshDateWithTokenExpirationDate:tokenExpirationDate]; - [self scheduleRefreshAtDate:refreshDate]; } - (void)scheduleRefreshAtDate:(NSDate *)refreshDate { @@ -153,21 +157,43 @@ - (void)cancelTimer { [self.timer invalidate]; } -#pragma mark - Backoff - -- (NSDate *)nextRefreshDateWithTokenExpirationDate:(NSDate *)tokenExpirationDate { - NSDate *targetRefreshDate = - [tokenExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; - NSTimeInterval scheduleIn = [targetRefreshDate timeIntervalSinceNow]; - - NSTimeInterval backoffTime = [[self class] backoffTimeForRetryCount:self.retryCount]; - if (scheduleIn >= backoffTime) { - return targetRefreshDate; - } else { - return [NSDate dateWithTimeIntervalSinceNow:backoffTime]; +- (NSDate *)nextRefreshDateWithTokenRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult { + switch (refreshResult.status) { + case FIRAppCheckTokenRefreshStatusSuccess: { + NSTimeInterval timeToLive = [refreshResult.tokenExpirationDate + timeIntervalSinceDate:refreshResult.tokenReceivedAtDate]; + timeToLive = MAX(timeToLive, 0); + + // Refresh in 50% of TTL + 5 min. + NSTimeInterval targetRefreshSinceReceivedDate = timeToLive * kAutoRefreshFraction + 5 * 60; + NSDate *targetRefreshDate = [refreshResult.tokenReceivedAtDate + dateByAddingTimeInterval:targetRefreshSinceReceivedDate]; + + // Don't schedule later than expiration date. + NSDate *refreshDate = [targetRefreshDate earlierDate:refreshResult.tokenExpirationDate]; + + // Don't schedule a refresh earlier than in 1 min from now. + if ([refreshDate timeIntervalSinceNow] < kMinimumAutoRefreshTimeInterval) { + refreshDate = [NSDate dateWithTimeIntervalSinceNow:kMinimumAutoRefreshTimeInterval]; + } + return refreshDate; + } break; + + case FIRAppCheckTokenRefreshStatusFailure: { + // Repeat refresh attempt later. + NSTimeInterval backoffTime = [[self class] backoffTimeForRetryCount:self.retryCount]; + return [NSDate dateWithTimeIntervalSinceNow:backoffTime]; + } break; + + case FIRAppCheckTokenRefreshStatusNever: + // Refresh ASAP. + return [NSDate date]; + break; } } +#pragma mark - Backoff + + (NSTimeInterval)backoffTimeForRetryCount:(NSInteger)retryCount { if (retryCount == 0) { // No backoff for the first attempt. diff --git a/FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h b/FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h index bc74856f1aa..368b900ae06 100644 --- a/FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h +++ b/FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h @@ -24,16 +24,16 @@ NS_SWIFT_NAME(AppCheckToken) /// A Firebase App Check token. @property(nonatomic, readonly) NSString *token; + /// The App Check token's expiration date in the device's local time. @property(nonatomic, readonly) NSDate *expirationDate; - (instancetype)init NS_UNAVAILABLE; -/// The designated initializer. +/// The default initializer. /// @param token A Firebase App Check token. /// @param expirationDate A Firebase App Check token expiration date in the device local time. -- (instancetype)initWithToken:(NSString *)token - expirationDate:(NSDate *)expirationDate NS_DESIGNATED_INITIALIZER; +- (instancetype)initWithToken:(NSString *)token expirationDate:(NSDate *)expirationDate; @end diff --git a/FirebaseAppCheck/Tests/Unit/AppAttestProvider/FIRAppAttestAPIServiceTests.m b/FirebaseAppCheck/Tests/Unit/AppAttestProvider/FIRAppAttestAPIServiceTests.m index e610665de58..d0a7ec36750 100644 --- a/FirebaseAppCheck/Tests/Unit/AppAttestProvider/FIRAppAttestAPIServiceTests.m +++ b/FirebaseAppCheck/Tests/Unit/AppAttestProvider/FIRAppAttestAPIServiceTests.m @@ -26,7 +26,7 @@ #import "FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckAPIService.h" #import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h" #import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckHTTPError.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #import "FirebaseAppCheck/Tests/Unit/Utils/FIRFixtureLoader.h" #import "SharedTestUtilities/Date/FIRDateTestUtils.h" @@ -224,7 +224,8 @@ - (void)testGetAppCheckTokenSuccess { error:nil]; // 2.2. Return token from parsed response. FIRAppCheckToken *expectedToken = [[FIRAppCheckToken alloc] initWithToken:@"app_check_token" - expirationDate:[NSDate date]]; + expirationDate:[NSDate date] + receivedAtDate:[NSDate date]]; [self expectTokenWithAPIReponse:validAPIResponse toReturnToken:expectedToken]; // 3. Send request. @@ -240,6 +241,7 @@ - (void)testGetAppCheckTokenSuccess { XCTAssertEqualObjects(promise.value, expectedToken); XCTAssertEqualObjects(promise.value.token, expectedToken.token); XCTAssertEqualObjects(promise.value.expirationDate, expectedToken.expirationDate); + XCTAssertEqualObjects(promise.value.receivedAtDate, expectedToken.receivedAtDate); OCMVerifyAll(self.mockAPIService); } diff --git a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckIntegrationTests.m b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckIntegrationTests.m index 4e43b2e9b45..183296a7bf3 100644 --- a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckIntegrationTests.m +++ b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckIntegrationTests.m @@ -204,9 +204,7 @@ - (void)usageExample { - (void)disableTokenRefresher { self.mockTokenRefresher = OCMClassMock([FIRAppCheckTokenRefresher class]); OCMStub([self.mockTokenRefresher alloc]).andReturn(self.mockTokenRefresher); - OCMStub([self.mockTokenRefresher initWithTokenExpirationDate:[OCMArg any] - tokenExpirationThreshold:5 * 60 - settings:[OCMArg any]]) + OCMStub([self.mockTokenRefresher initWithRefreshResult:[OCMArg any] settings:[OCMArg any]]) .andReturn(self.mockTokenRefresher); } diff --git a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStorageTests.m b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStorageTests.m index b8c61f567cd..13b5eecf859 100644 --- a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStorageTests.m +++ b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStorageTests.m @@ -21,7 +21,7 @@ #import #import "FBLPromise+Testing.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" @interface FIRAppCheckStorageTests : XCTestCase @property(nonatomic) NSString *appName; @@ -49,7 +49,8 @@ - (void)tearDown { - (void)testSetAndGetToken { FIRAppCheckToken *tokenToStore = [[FIRAppCheckToken alloc] initWithToken:@"token" - expirationDate:[NSDate distantPast]]; + expirationDate:[NSDate distantPast] + receivedAtDate:[NSDate date]]; FBLPromise *setPromise = [self.storage setToken:tokenToStore]; XCTAssert(FBLWaitForPromisesWithTimeout(0.5)); @@ -60,6 +61,7 @@ - (void)testSetAndGetToken { XCTAssert(FBLWaitForPromisesWithTimeout(0.5)); XCTAssertEqualObjects(getPromise.value.token, tokenToStore.token); XCTAssertEqualObjects(getPromise.value.expirationDate, tokenToStore.expirationDate); + XCTAssertEqualObjects(getPromise.value.receivedAtDate, tokenToStore.receivedAtDate); XCTAssertNil(getPromise.error); } @@ -78,7 +80,8 @@ - (void)testRemoveToken { - (void)testSetTokenPerApp { // 1. Set token with a storage. FIRAppCheckToken *tokenToStore = [[FIRAppCheckToken alloc] initWithToken:@"token" - expirationDate:[NSDate distantPast]]; + expirationDate:[NSDate distantPast] + receivedAtDate:[NSDate date]]; FBLPromise *setPromise = [self.storage setToken:tokenToStore]; XCTAssert(FBLWaitForPromisesWithTimeout(0.5)); diff --git a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStoredTokenTests.m b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStoredTokenTests.m index 15233f50758..8281527904f 100644 --- a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStoredTokenTests.m +++ b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckStoredTokenTests.m @@ -16,9 +16,9 @@ #import +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken+FIRAppCheckToken.h" #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStoredToken.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" #import @@ -32,6 +32,7 @@ - (void)testSecureCoding { FIRAppCheckStoredToken *tokenToArchive = [[FIRAppCheckStoredToken alloc] init]; tokenToArchive.token = @"some_token"; tokenToArchive.expirationDate = [NSDate date]; + tokenToArchive.receivedAtDate = [tokenToArchive.expirationDate dateByAddingTimeInterval:-10]; NSError *error; NSData *archivedToken = [GULSecureCoding archivedDataWithRootObject:tokenToArchive error:&error]; @@ -46,21 +47,25 @@ - (void)testSecureCoding { XCTAssertNil(error); XCTAssertEqualObjects(unarchivedToken.token, tokenToArchive.token); XCTAssertEqualObjects(unarchivedToken.expirationDate, tokenToArchive.expirationDate); + XCTAssertEqualObjects(unarchivedToken.receivedAtDate, tokenToArchive.receivedAtDate); XCTAssertEqual(unarchivedToken.storageVersion, tokenToArchive.storageVersion); } - (void)testConvertingToAndFromFIRAppCheckToken { FIRAppCheckToken *originalToken = [[FIRAppCheckToken alloc] initWithToken:@"___" - expirationDate:[NSDate date]]; + expirationDate:[NSDate date] + receivedAtDate:[NSDate date]]; FIRAppCheckStoredToken *storedToken = [[FIRAppCheckStoredToken alloc] init]; [storedToken updateWithToken:originalToken]; XCTAssertEqualObjects(originalToken.token, storedToken.token); XCTAssertEqualObjects(originalToken.expirationDate, storedToken.expirationDate); + XCTAssertEqualObjects(originalToken.receivedAtDate, storedToken.receivedAtDate); FIRAppCheckToken *recoveredToken = [storedToken appCheckToken]; XCTAssertEqualObjects(recoveredToken.token, storedToken.token); XCTAssertEqualObjects(recoveredToken.expirationDate, storedToken.expirationDate); + XCTAssertEqualObjects(recoveredToken.receivedAtDate, storedToken.receivedAtDate); } @end diff --git a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTests.m b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTests.m index 0fc0c7a5578..0977eda286b 100644 --- a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTests.m +++ b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTests.m @@ -31,6 +31,7 @@ #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h" #import "FirebaseAppCheck/Sources/Core/FIRAppCheckTokenResult.h" #import "FirebaseAppCheck/Sources/Core/Storage/FIRAppCheckStorage.h" +#import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h" #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h" #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h" @@ -114,20 +115,21 @@ - (void)testInitWithApp { id mockTokenRefresher = OCMClassMock([FIRAppCheckTokenRefresher class]); OCMExpect([mockTokenRefresher alloc]).andReturn(mockTokenRefresher); - id refresherDateValidator = [OCMArg checkWithBlock:^BOOL(NSDate *tokenExpirationDate) { - NSTimeInterval accuracy = 1; - XCTAssertLessThanOrEqual(ABS([tokenExpirationDate timeIntervalSinceNow]), accuracy); - return YES; - }]; + id refresherDateValidator = + [OCMArg checkWithBlock:^BOOL(FIRAppCheckTokenRefreshResult *refreshResult) { + XCTAssertEqual(refreshResult.status, FIRAppCheckTokenRefreshStatusNever); + XCTAssertEqual(refreshResult.tokenExpirationDate, nil); + XCTAssertEqual(refreshResult.tokenReceivedAtDate, nil); + return YES; + }]; id settingsValidator = [OCMArg checkWithBlock:^BOOL(id obj) { XCTAssert([obj isKindOfClass:[FIRAppCheckSettings class]]); return YES; }]; - OCMExpect([mockTokenRefresher initWithTokenExpirationDate:refresherDateValidator - tokenExpirationThreshold:5 * 60 - settings:settingsValidator]) + OCMExpect([mockTokenRefresher initWithRefreshResult:refresherDateValidator + settings:settingsValidator]) .andReturn(mockTokenRefresher); OCMExpect([mockTokenRefresher setTokenRefreshHandler:[OCMArg any]]); @@ -381,10 +383,10 @@ - (void)testTokenRefreshTriggeredAndRefreshSuccess { } XCTestExpectation *completionExpectation = [self expectationWithDescription:@"completion"]; - self.tokenRefreshHandler(^(BOOL success, NSDate *_Nullable tokenExpirationDate) { + self.tokenRefreshHandler(^(FIRAppCheckTokenRefreshResult *refreshResult) { [completionExpectation fulfill]; - XCTAssertEqual(tokenExpirationDate, expirationDate); - XCTAssertTrue(success); + XCTAssertEqualObjects(refreshResult.tokenExpirationDate, expirationDate); + XCTAssertEqual(refreshResult.status, FIRAppCheckTokenRefreshStatusSuccess); }); [self waitForExpectations:@[ notificationExpectation, completionExpectation ] timeout:0.5]; @@ -415,10 +417,11 @@ - (void)testTokenRefreshTriggeredAndRefreshError { } XCTestExpectation *completionExpectation = [self expectationWithDescription:@"completion"]; - self.tokenRefreshHandler(^(BOOL success, NSDate *_Nullable tokenExpirationDate) { + self.tokenRefreshHandler(^(FIRAppCheckTokenRefreshResult *refreshResult) { [completionExpectation fulfill]; - XCTAssertNil(tokenExpirationDate); - XCTAssertFalse(success); + XCTAssertEqual(refreshResult.status, FIRAppCheckTokenRefreshStatusFailure); + XCTAssertNil(refreshResult.tokenExpirationDate); + XCTAssertNil(refreshResult.tokenReceivedAtDate); }); [self waitForExpectations:@[ notificationExpectation, completionExpectation ] timeout:0.5]; diff --git a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTokenRefresherTests.m b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTokenRefresherTests.m index 747aba25da0..2ffa18441d3 100644 --- a/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTokenRefresherTests.m +++ b/FirebaseAppCheck/Tests/Unit/Core/FIRAppCheckTokenRefresherTests.m @@ -19,8 +19,10 @@ #import #import "FirebaseAppCheck/Sources/Core/FIRAppCheckSettings.h" +#import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefreshResult.h" #import "FirebaseAppCheck/Sources/Core/TokenRefresh/FIRAppCheckTokenRefresher.h" #import "FirebaseAppCheck/Tests/Unit/Utils/FIRFakeTimer.h" +#import "SharedTestUtilities/Date/FIRDateTestUtils.h" @interface FIRAppCheckTokenRefresherTests : XCTestCase @@ -28,8 +30,7 @@ @interface FIRAppCheckTokenRefresherTests : XCTestCase @property(nonatomic) OCMockObject *mockSettings; -@property(nonatomic) NSDate *initialTokenExpirationDate; -@property(nonatomic) NSTimeInterval tokenExpirationThreshold; +@property(nonatomic) FIRAppCheckTokenRefreshResult *initialTokenRefreshResult; @end @@ -38,8 +39,11 @@ @implementation FIRAppCheckTokenRefresherTests - (void)setUp { self.mockSettings = OCMProtocolMock(@protocol(FIRAppCheckSettingsProtocol)); self.fakeTimer = [[FIRFakeTimer alloc] init]; - self.initialTokenExpirationDate = [NSDate dateWithTimeIntervalSinceNow:1000]; - self.tokenExpirationThreshold = 1 * 60; + + NSDate *receivedAtDate = [NSDate date]; + self.initialTokenRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:[receivedAtDate dateByAddingTimeInterval:1000] + receivedAtDate:receivedAtDate]; } - (void)tearDown { @@ -51,48 +55,86 @@ - (void)tearDown { #pragma mark - Auto refresh is allowed - (void)testInitialRefreshWhenAutoRefreshAllowed { + __auto_type weakSelf = self; + + self.initialTokenRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] initWithStatusNever]; FIRAppCheckTokenRefresher *refresher = [self createRefresher]; - // 1. Expect checking if auto-refresh allowed before scheduling initial refresh. + // 1. Expect checking if auto-refresh allowed before scheduling the initial refresh. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; - // 2. Expect timer to be scheduled. - NSDate *expectedTimerFireDate = - [self.initialTokenExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; - XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; - - __auto_type weakSelf = self; + // 2. Don't expect the timer to be scheduled for the first refresh as the refresh should be + // triggered straight away. + XCTestExpectation *initialTimerCreatedExpectation = + [self expectationWithDescription:@"initial refresh timer created"]; + initialTimerCreatedExpectation.inverted = YES; self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { weakSelf.fakeTimer.createHandler = nil; - XCTAssertEqualObjects(fireDate, expectedTimerFireDate); - [timerCreateExpectation fulfill]; + [initialTimerCreatedExpectation fulfill]; }; - // 3. Expect refresh handler to be called. - NSDate *refreshedTokenExpirationDate = [expectedTimerFireDate dateByAddingTimeInterval:60 * 60]; + // 3. Expect checking if auto-refresh allowed before triggering the initial refresh. + [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; + + // 4. Expect initial refresh handler to be called. + __block FIRAppCheckTokenRefreshCompletion initialRefreshCompletion; XCTestExpectation *initialRefreshExpectation = [self expectationWithDescription:@"initial refresh"]; - XCTestExpectation *noEarlyRefreshExpectation = - [self expectationWithDescription:@"no early refresh"]; - noEarlyRefreshExpectation.inverted = YES; refresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) { + // Save completion to be called later. + initialRefreshCompletion = completion; + [initialRefreshExpectation fulfill]; - [noEarlyRefreshExpectation fulfill]; + }; - // Call completion. - completion(YES, refreshedTokenExpirationDate); + NSDate *initialTokenExpirationDate = [NSDate dateWithTimeIntervalSinceNow:60 * 60]; + NSDate *initialTokenReceivedDate = [NSDate date]; + __auto_type initialRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:initialTokenExpirationDate + receivedAtDate:initialTokenReceivedDate]; + + [self waitForExpectations:@[ initialTimerCreatedExpectation, initialRefreshExpectation ] + timeout:1]; + + // 5. Expect checking if auto-refresh allowed before scheduling next refresh. + [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; + + // 6. Expect a next refresh timer to be scheduled on initial refresh completion. + NSDate *expectedRefreshDate = + [self expectedRefreshDateWithReceivedDate:initialTokenReceivedDate + expirationDate:initialTokenExpirationDate]; + XCTestExpectation *nextTimerCreateExpectation = + [self expectationWithDescription:@"next refresh create timer"]; + self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { + weakSelf.fakeTimer.createHandler = nil; + XCTAssertEqualObjects(fireDate, expectedRefreshDate); + [nextTimerCreateExpectation fulfill]; }; - // 4. Check if the handler is not fired before the timer. - [self waitForExpectations:@[ timerCreateExpectation, noEarlyRefreshExpectation ] timeout:1]; + // 7. Call initial refresh completion and wait for next refresh timer to be scheduled. + initialRefreshCompletion(initialRefreshResult); + [self waitForExpectations:@[ nextTimerCreateExpectation ] timeout:0.5]; - // 5. Expect checking if auto-refresh allowed before refreshing. + // 8. Expect checking if auto-refresh allowed before triggering the next refresh. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; - // 6. Fire the timer and wait for completion. + // 9. Expect refresh handler to be called for the next refresh. + __auto_type nextRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:[expectedRefreshDate dateByAddingTimeInterval:60 * 60] + receivedAtDate:expectedRefreshDate]; + XCTestExpectation *nextRefreshExpectation = [self expectationWithDescription:@"next refresh"]; + refresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) { + [nextRefreshExpectation fulfill]; + + // Call completion. + completion(nextRefreshResult); + }; + + // 10. Fire the timer. [self fireTimer]; - [self waitForExpectations:@[ initialRefreshExpectation ] timeout:0.5]; + // 11. Wait for the next refresh handler to be called. + [self waitForExpectations:@[ nextRefreshExpectation ] timeout:1]; OCMVerifyAll(self.mockSettings); } @@ -135,12 +177,18 @@ - (void)testNextRefreshOnRefreshSuccess { FIRAppCheckTokenRefresher *refresher = [self createRefresher]; NSDate *refreshedTokenExpirationDate = - [self.initialTokenExpirationDate dateByAddingTimeInterval:60 * 60]; + [self.initialTokenRefreshResult.tokenExpirationDate dateByAddingTimeInterval:60 * 60]; + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:refreshedTokenExpirationDate + receivedAtDate:self.initialTokenRefreshResult.tokenExpirationDate]; // 1. Expect checking if auto-refresh allowed before scheduling initial refresh. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; - // 2. Expect refresh handler. + // 2. Expect checking if auto-refresh allowed before calling the refresh handler. + [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; + + // 3. Expect refresh handler. XCTestExpectation *initialRefreshExpectation = [self expectationWithDescription:@"initial refresh"]; refresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) { @@ -149,23 +197,24 @@ - (void)testNextRefreshOnRefreshSuccess { // Call completion in a while. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - completion(YES, refreshedTokenExpirationDate); + completion(refreshResult); }); }; - // 3. Expect for new timer to be created. + // 4. Expect for new timer to be created. NSDate *expectedFireDate = - [refreshedTokenExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; + [self expectedRefreshDateWithReceivedDate:refreshResult.tokenReceivedAtDate + expirationDate:refreshResult.tokenExpirationDate]; XCTestExpectation *createTimerExpectation = [self expectationWithDescription:@"create timer"]; self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { [createTimerExpectation fulfill]; XCTAssertEqualObjects(fireDate, expectedFireDate); }; - // 4. Expect checking if auto-refresh allowed before refreshing. + // 5. Expect checking if auto-refresh allowed before refreshing. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; - // 5. Fire initial timer and wait for expectations. + // 6. Fire initial timer and wait for expectations. [self fireTimer]; [self waitForExpectations:@[ initialRefreshExpectation, createTimerExpectation ] @@ -186,7 +235,10 @@ - (void)testBackoff { [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; for (NSInteger i = 0; i < 10; i++) { - // 2. Expect refresh handler. + // 2. Expect checking if auto-refresh allowed before calling the refresh handler. + [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; + + // 3. Expect refresh handler. XCTestExpectation *initialRefreshExpectation = [self expectationWithDescription:@"initial refresh"]; refresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) { @@ -195,11 +247,13 @@ - (void)testBackoff { // Call completion in a while. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ - completion(NO, nil); + __auto_type refreshFailure = + [[FIRAppCheckTokenRefreshResult alloc] initWithStatusFailure]; + completion(refreshFailure); }); }; - // 3. Expect for new timer to be created. + // 4. Expect for new timer to be created. // No backoff initially, 1st backoff 30sec, double backoff on each next attempt until 16min. expectedBackoffTime = expectedBackoffTime == 0 ? 30 : expectedBackoffTime * 2; expectedBackoffTime = MIN(expectedBackoffTime, maximumBackoffTime); @@ -214,10 +268,10 @@ - (void)testBackoff { XCTAssertLessThan(ABS([expectedFireDate timeIntervalSinceDate:fireDate]), 2); }; - // 4. Expect checking if auto-refresh allowed before refreshing. + // 5. Expect checking if auto-refresh allowed before refreshing. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; - // 5. Fire initial timer and wait for expectations. + // 6. Fire initial timer and wait for expectations. [self fireTimer]; [self waitForExpectations:@[ initialRefreshExpectation, createTimerExpectation ] @@ -237,20 +291,19 @@ - (void)testNoInitialRefreshWhenAutoRefreshIsNotAllowed { [[[self.mockSettings expect] andReturnValue:@(NO)] isTokenAutoRefreshEnabled]; // 2. Don't expect timer to be scheduled. - NSDate *expectedTimerFireDate = - [self.initialTokenExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; timerCreateExpectation.inverted = YES; __auto_type weakSelf = self; self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { weakSelf.fakeTimer.createHandler = nil; - XCTAssertEqualObjects(fireDate, expectedTimerFireDate); [timerCreateExpectation fulfill]; }; // 3. Don't expect refresh handler to be called. - NSDate *refreshedTokenExpirationDate = [expectedTimerFireDate dateByAddingTimeInterval:60 * 60]; + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:[NSDate dateWithTimeIntervalSinceNow:60 * 60] + receivedAtDate:[NSDate date]]; XCTestExpectation *refreshExpectation = [self expectationWithDescription:@"refresh"]; refreshExpectation.inverted = YES; @@ -258,7 +311,7 @@ - (void)testNoInitialRefreshWhenAutoRefreshIsNotAllowed { [refreshExpectation fulfill]; // Call completion. - completion(YES, refreshedTokenExpirationDate); + completion(refreshResult); }; // 4. Check if the handler is not fired before the timer. @@ -275,7 +328,8 @@ - (void)testNoRefreshWhenAutoRefreshWasDisabledAfterInit { // 2. Expect timer to be scheduled. NSDate *expectedTimerFireDate = - [self.initialTokenExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; + [self expectedRefreshDateWithReceivedDate:self.initialTokenRefreshResult.tokenReceivedAtDate + expirationDate:self.initialTokenRefreshResult.tokenExpirationDate]; XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; __auto_type weakSelf = self; @@ -286,14 +340,17 @@ - (void)testNoRefreshWhenAutoRefreshWasDisabledAfterInit { }; // 3. Expect refresh handler to be called. - NSDate *refreshedTokenExpirationDate = [expectedTimerFireDate dateByAddingTimeInterval:60 * 60]; + __auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:[expectedTimerFireDate + dateByAddingTimeInterval:60 * 60] + receivedAtDate:expectedTimerFireDate]; XCTestExpectation *noRefreshExpectation = [self expectationWithDescription:@"initial refresh"]; noRefreshExpectation.inverted = YES; refresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) { [noRefreshExpectation fulfill]; // Call completion. - completion(YES, refreshedTokenExpirationDate); + completion(refreshResult); }; // 4. Check if the handler is not fired before the timer. @@ -312,17 +369,22 @@ - (void)testNoRefreshWhenAutoRefreshWasDisabledAfterInit { #pragma mark - Update token expiration -- (void)testUpdateTokenExpirationDateWhenAutoRefreshIsAllowed { +- (void)testUpdateWithRefreshResultWhenAutoRefreshIsAllowed { FIRAppCheckTokenRefresher *refresher = [self createRefresher]; - NSDate *newExpirationDate = [self.initialTokenExpirationDate dateByAddingTimeInterval:10 * 60]; + NSDate *newExpirationDate = + [self.initialTokenRefreshResult.tokenExpirationDate dateByAddingTimeInterval:10 * 60]; + __auto_type newRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:newExpirationDate + receivedAtDate:self.initialTokenRefreshResult.tokenExpirationDate]; - // 1. Expect checking if auto-refresh allowed before scheduling initial refresh. + // 1. Expect checking if auto-refresh allowed before scheduling refresh. [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; // 2. Expect timer to be scheduled. NSDate *expectedTimerFireDate = - [newExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; + [self expectedRefreshDateWithReceivedDate:newRefreshResult.tokenReceivedAtDate + expirationDate:newRefreshResult.tokenExpirationDate]; XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; __auto_type weakSelf = self; @@ -333,7 +395,7 @@ - (void)testUpdateTokenExpirationDateWhenAutoRefreshIsAllowed { }; // 3. Update token expiration date. - [refresher updateTokenExpirationDate:newExpirationDate]; + [refresher updateWithRefreshResult:newRefreshResult]; // 4. Wait for timer to be created. [self waitForExpectations:@[ timerCreateExpectation ] timeout:1]; @@ -341,29 +403,62 @@ - (void)testUpdateTokenExpirationDateWhenAutoRefreshIsAllowed { OCMVerifyAll(self.mockSettings); } -- (void)testUpdateTokenExpirationDateWhenAutoRefreshIsNotAllowed { +- (void)testUpdateWithRefreshResultWhenAutoRefreshIsNotAllowed { FIRAppCheckTokenRefresher *refresher = [self createRefresher]; - NSDate *newExpirationDate = [self.initialTokenExpirationDate dateByAddingTimeInterval:10 * 60]; + __auto_type newRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:[NSDate dateWithTimeIntervalSinceNow:60 * 60] + receivedAtDate:self.initialTokenRefreshResult.tokenExpirationDate]; // 1. Expect checking if auto-refresh allowed before scheduling initial refresh. [[[self.mockSettings expect] andReturnValue:@(NO)] isTokenAutoRefreshEnabled]; // 2. Don't expect timer to be scheduled. - NSDate *expectedTimerFireDate = - [newExpirationDate dateByAddingTimeInterval:-self.tokenExpirationThreshold]; XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; timerCreateExpectation.inverted = YES; __auto_type weakSelf = self; self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { weakSelf.fakeTimer.createHandler = nil; - XCTAssertEqualObjects(fireDate, expectedTimerFireDate); [timerCreateExpectation fulfill]; }; // 3. Update token expiration date. - [refresher updateTokenExpirationDate:newExpirationDate]; + [refresher updateWithRefreshResult:newRefreshResult]; + + // 4. Wait for timer to be created. + [self waitForExpectations:@[ timerCreateExpectation ] timeout:1]; + + OCMVerifyAll(self.mockSettings); +} + +- (void)testUpdateWithRefreshResult_WhenTokenExpiresLessThanIn1Minute { + FIRAppCheckTokenRefresher *refresher = [self createRefresher]; + + NSDate *newExpirationDate = [NSDate dateWithTimeIntervalSinceNow:0.5 * 60]; + __auto_type newRefreshResult = [[FIRAppCheckTokenRefreshResult alloc] + initWithStatusSuccessAndExpirationDate:newExpirationDate + receivedAtDate:[NSDate date]]; + + // 1. Expect checking if auto-refresh allowed before scheduling refresh. + [[[self.mockSettings expect] andReturnValue:@(YES)] isTokenAutoRefreshEnabled]; + + // 2. Expect timer to be scheduled in at least 1 minute. + XCTestExpectation *timerCreateExpectation = [self expectationWithDescription:@"create timer"]; + + __auto_type weakSelf = self; + self.fakeTimer.createHandler = ^(NSDate *_Nonnull fireDate) { + weakSelf.fakeTimer.createHandler = nil; + + // 1 minute is the minimal interval between successful refreshes. + XCTAssert([FIRDateTestUtils isDate:fireDate + approximatelyEqualCurrentPlusTimeInterval:60 + precision:1]); + [timerCreateExpectation fulfill]; + }; + + // 3. Update token expiration date. + [refresher updateWithRefreshResult:newRefreshResult]; // 4. Wait for timer to be created. [self waitForExpectations:@[ timerCreateExpectation ] timeout:1]; @@ -382,11 +477,26 @@ - (void)fireTimer { } - (FIRAppCheckTokenRefresher *)createRefresher { - return [[FIRAppCheckTokenRefresher alloc] - initWithTokenExpirationDate:self.initialTokenExpirationDate - tokenExpirationThreshold:self.tokenExpirationThreshold - timerProvider:[self.fakeTimer fakeTimerProvider] - settings:self.mockSettings]; + return [[FIRAppCheckTokenRefresher alloc] initWithRefreshResult:self.initialTokenRefreshResult + timerProvider:[self.fakeTimer fakeTimerProvider] + settings:self.mockSettings]; +} + +- (NSDate *)expectedRefreshDateWithReceivedDate:(NSDate *)receivedDate + expirationDate:(NSDate *)expirationDate { + NSTimeInterval timeToLive = [expirationDate timeIntervalSinceDate:receivedDate]; + XCTAssertGreaterThanOrEqual(timeToLive, 0); + + NSTimeInterval timeToRefresh = timeToLive / 2 + 5 * 60; // 50% of TTL + 5 min + + NSTimeInterval minimalAutoRefreshInterval = 60; // 1 min + timeToRefresh = MAX(timeToRefresh, minimalAutoRefreshInterval); + + NSDate *refreshDate = [receivedDate dateByAddingTimeInterval:timeToRefresh]; + + NSDate *now = [NSDate date]; + + return [refreshDate laterDate:now]; } @end diff --git a/FirebaseAppCheck/Tests/Unit/DebugProvider/FIRAppCheckDebugProviderTests.m b/FirebaseAppCheck/Tests/Unit/DebugProvider/FIRAppCheckDebugProviderTests.m index 5b80c100db7..a7f185178d0 100644 --- a/FirebaseAppCheck/Tests/Unit/DebugProvider/FIRAppCheckDebugProviderTests.m +++ b/FirebaseAppCheck/Tests/Unit/DebugProvider/FIRAppCheckDebugProviderTests.m @@ -19,9 +19,9 @@ #import #import "FBLPromise+Testing.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #import "FirebaseAppCheck/Sources/DebugProvider/API/FIRAppCheckDebugProviderAPIService.h" #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckDebugProvider.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h" @@ -130,7 +130,8 @@ - (void)testGetTokenSuccess { // 1. Stub API service. NSString *expectedDebugToken = [self.provider currentDebugToken]; FIRAppCheckToken *validToken = [[FIRAppCheckToken alloc] initWithToken:@"valid_token" - expirationDate:[NSDate date]]; + expirationDate:[NSDate date] + receivedAtDate:[NSDate date]]; OCMExpect([self.fakeAPIService appCheckTokenWithDebugToken:expectedDebugToken]) .andReturn([FBLPromise resolvedWith:validToken]); @@ -139,6 +140,7 @@ - (void)testGetTokenSuccess { XCTAssertNil(error); XCTAssertEqualObjects(token.token, validToken.token); XCTAssertEqualObjects(token.expirationDate, validToken.expirationDate); + XCTAssertEqualObjects(token.receivedAtDate, validToken.receivedAtDate); }]; // 3. Verify fakes. diff --git a/FirebaseAppCheck/Tests/Unit/DeviceCheckProvider/FIRDeviceCheckProviderTests.m b/FirebaseAppCheck/Tests/Unit/DeviceCheckProvider/FIRDeviceCheckProviderTests.m index b2776e6f380..6e54d463a36 100644 --- a/FirebaseAppCheck/Tests/Unit/DeviceCheckProvider/FIRDeviceCheckProviderTests.m +++ b/FirebaseAppCheck/Tests/Unit/DeviceCheckProvider/FIRDeviceCheckProviderTests.m @@ -19,9 +19,9 @@ #import #import "FBLPromise+Testing.h" +#import "FirebaseAppCheck/Sources/Core/FIRAppCheckToken+Internal.h" #import "FirebaseAppCheck/Sources/DeviceCheckProvider/API/FIRDeviceCheckAPIService.h" #import "FirebaseAppCheck/Sources/DeviceCheckProvider/FIRDeviceCheckTokenGenerator.h" -#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckToken.h" #import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRDeviceCheckProvider.h" #import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h" @@ -90,7 +90,8 @@ - (void)testGetTokenSuccess { // 2. Expect FAA token to be requested. FIRAppCheckToken *validToken = [[FIRAppCheckToken alloc] initWithToken:@"valid_token" - expirationDate:[NSDate distantFuture]]; + expirationDate:[NSDate distantFuture] + receivedAtDate:[NSDate date]]; OCMExpect([self.fakeAPIService appCheckTokenWithDeviceToken:deviceToken]) .andReturn([FBLPromise resolvedWith:validToken]); @@ -102,6 +103,7 @@ - (void)testGetTokenSuccess { [completionExpectation fulfill]; XCTAssertEqualObjects(token.token, validToken.token); XCTAssertEqualObjects(token.expirationDate, validToken.expirationDate); + XCTAssertEqualObjects(token.receivedAtDate, validToken.receivedAtDate); XCTAssertNil(error); }]; pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy