mirror of
https://github.com/firebase/firebase-ios-sdk
synced 2026-11-09 22:36:01 +05:45
* 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 69eb00dfe2.
* 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 <TargetConditionals.h> 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>
216 lines
7.0 KiB
Objective-C
216 lines
7.0 KiB
Objective-C
/*
|
|
* 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/FIRAppCheckTokenRefresher.h"
|
|
|
|
#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;
|
|
|
|
@property(nonatomic, readonly) id<FIRAppCheckSettingsProtocol> settings;
|
|
|
|
@property(nonatomic, readonly) FIRTimerProvider timerProvider;
|
|
@property(atomic, nullable) id<FIRAppCheckTimerProtocol> timer;
|
|
@property(atomic) NSUInteger retryCount;
|
|
|
|
/// Initial refresh result to be used when `tokenRefreshHandler` has been sent.
|
|
@property(nonatomic, nullable) FIRAppCheckTokenRefreshResult *initialRefreshResult;
|
|
|
|
@end
|
|
|
|
@implementation FIRAppCheckTokenRefresher
|
|
|
|
@synthesize tokenRefreshHandler = _tokenRefreshHandler;
|
|
|
|
- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult
|
|
timerProvider:(FIRTimerProvider)timerProvider
|
|
settings:(id<FIRAppCheckSettingsProtocol>)settings {
|
|
self = [super init];
|
|
if (self) {
|
|
_refreshQueue =
|
|
dispatch_queue_create("com.firebase.FIRAppCheckTokenRefresher", DISPATCH_QUEUE_SERIAL);
|
|
_initialRefreshResult = refreshResult;
|
|
_timerProvider = timerProvider;
|
|
_settings = settings;
|
|
}
|
|
return self;
|
|
}
|
|
|
|
- (instancetype)initWithRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult
|
|
settings:(id<FIRAppCheckSettingsProtocol>)settings {
|
|
return [self initWithRefreshResult:refreshResult
|
|
timerProvider:[FIRAppCheckTimer timerProvider]
|
|
settings:settings];
|
|
}
|
|
|
|
- (void)dealloc {
|
|
[self cancelTimer];
|
|
}
|
|
|
|
- (void)setTokenRefreshHandler:(FIRAppCheckTokenRefreshBlock)tokenRefreshHandler {
|
|
@synchronized(self) {
|
|
_tokenRefreshHandler = tokenRefreshHandler;
|
|
|
|
// Check if handler is being set for the first time and if yes then schedule first refresh.
|
|
if (tokenRefreshHandler && self.initialRefreshResult) {
|
|
FIRAppCheckTokenRefreshResult *initialTokenRefreshResult = self.initialRefreshResult;
|
|
self.initialRefreshResult = nil;
|
|
[self scheduleWithTokenRefreshResult:initialTokenRefreshResult];
|
|
}
|
|
}
|
|
}
|
|
|
|
- (FIRAppCheckTokenRefreshBlock)tokenRefreshHandler {
|
|
@synchronized(self) {
|
|
return _tokenRefreshHandler;
|
|
}
|
|
}
|
|
|
|
- (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 {
|
|
if (self.tokenRefreshHandler == nil) {
|
|
return;
|
|
}
|
|
|
|
if (!self.settings.isTokenAutoRefreshEnabled) {
|
|
return;
|
|
}
|
|
|
|
__auto_type __weak weakSelf = self;
|
|
self.tokenRefreshHandler(^(FIRAppCheckTokenRefreshResult *refreshResult) {
|
|
__auto_type strongSelf = weakSelf;
|
|
[strongSelf updateWithRefreshResult:refreshResult];
|
|
});
|
|
}
|
|
|
|
- (void)scheduleWithTokenRefreshResult:(FIRAppCheckTokenRefreshResult *)refreshResult {
|
|
// Schedule the refresh only when allowed.
|
|
if (self.settings.isTokenAutoRefreshEnabled) {
|
|
NSDate *refreshDate = [self nextRefreshDateWithTokenRefreshResult:refreshResult];
|
|
[self scheduleRefreshAtDate:refreshDate];
|
|
}
|
|
}
|
|
|
|
- (void)scheduleRefreshAtDate:(NSDate *)refreshDate {
|
|
[self cancelTimer];
|
|
|
|
NSTimeInterval scheduleInSec = [refreshDate timeIntervalSinceNow];
|
|
|
|
__auto_type __weak weakSelf = self;
|
|
dispatch_block_t refreshHandler = ^{
|
|
__auto_type strongSelf = weakSelf;
|
|
[strongSelf refresh];
|
|
};
|
|
|
|
// Refresh straight away if the refresh time is too close.
|
|
if (scheduleInSec <= 0) {
|
|
dispatch_async(self.refreshQueue, refreshHandler);
|
|
return;
|
|
}
|
|
|
|
self.timer = self.timerProvider(refreshDate, self.refreshQueue, refreshHandler);
|
|
}
|
|
|
|
- (void)cancelTimer {
|
|
[self.timer invalidate];
|
|
}
|
|
|
|
- (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.
|
|
return 0;
|
|
}
|
|
|
|
NSTimeInterval exponentialInterval =
|
|
kInitialBackoffTimeInterval * pow(2, retryCount - 1) + [self randomMilliseconds];
|
|
return MIN(exponentialInterval, kMaximumBackoffTimeInterval);
|
|
}
|
|
|
|
+ (NSTimeInterval)randomMilliseconds {
|
|
int32_t random_millis = ABS(arc4random() % 1000);
|
|
return (double)random_millis * 0.001;
|
|
}
|
|
|
|
@end
|
|
|
|
NS_ASSUME_NONNULL_END
|