mirror of
https://github.com/firebase/firebase-ios-sdk
synced 2026-11-11 22:55:59 +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>
350 lines
14 KiB
Objective-C
350 lines
14 KiB
Objective-C
/*
|
|
* Copyright 2020 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/Public/FirebaseAppCheck/FIRAppCheck.h"
|
|
|
|
#if __has_include(<FBLPromises/FBLPromises.h>)
|
|
#import <FBLPromises/FBLPromises.h>
|
|
#else
|
|
#import "FBLPromises.h"
|
|
#endif
|
|
|
|
#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProvider.h"
|
|
#import "FirebaseAppCheck/Sources/Public/FirebaseAppCheck/FIRAppCheckProviderFactory.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"
|
|
#import "FirebaseAppCheck/Sources/Interop/FIRAppCheckTokenResultInterop.h"
|
|
|
|
#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
|
|
|
|
NS_ASSUME_NONNULL_BEGIN
|
|
|
|
/// A notification with the specified name is sent to the default notification center
|
|
/// (`NotificationCenter.default`) each time a Firebase app check token is refreshed.
|
|
/// The user info dictionary contains `kFIRAppCheckTokenNotificationKey` and
|
|
/// `kFIRAppCheckAppNameNotificationKey` keys.
|
|
const NSNotificationName FIRAppCheckAppCheckTokenDidChangeNotification =
|
|
@"FIRAppCheckAppCheckTokenDidChangeNotification";
|
|
|
|
/// `userInfo` key for the `AppCheckToken` in `appCheckTokenRefreshNotification`.
|
|
NSString *const kFIRAppCheckTokenNotificationKey = @"FIRAppCheckTokenNotificationKey";
|
|
|
|
/// `userInfo` key for the `FirebaseApp.name` in `appCheckTokenRefreshNotification`.
|
|
NSString *const kFIRAppCheckAppNameNotificationKey = @"FIRAppCheckAppNameNotificationKey";
|
|
|
|
static id<FIRAppCheckProviderFactory> _providerFactory;
|
|
|
|
static const NSTimeInterval kTokenExpirationThreshold = 5 * 60; // 5 min.
|
|
|
|
static NSString *const kDummyFACTokenValue = @"eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ==";
|
|
|
|
@interface FIRAppCheck () <FIRLibrary, FIRAppCheckInterop>
|
|
@property(class, nullable) id<FIRAppCheckProviderFactory> providerFactory;
|
|
|
|
@property(nonatomic, readonly) NSString *appName;
|
|
@property(nonatomic, readonly) id<FIRAppCheckProvider> appCheckProvider;
|
|
@property(nonatomic, readonly) id<FIRAppCheckStorageProtocol> storage;
|
|
@property(nonatomic, readonly) NSNotificationCenter *notificationCenter;
|
|
@property(nonatomic, readonly) id<FIRAppCheckSettingsProtocol> settings;
|
|
|
|
@property(nonatomic, readonly, nullable) id<FIRAppCheckTokenRefresherProtocol> tokenRefresher;
|
|
|
|
@property(nonatomic, nullable) FBLPromise<FIRAppCheckToken *> *ongoingRetrieveOrRefreshTokenPromise;
|
|
|
|
@end
|
|
|
|
@implementation FIRAppCheck
|
|
|
|
#pragma mark - FIRComponents
|
|
|
|
+ (void)load {
|
|
[FIRApp registerInternalLibrary:(Class<FIRLibrary>)self withName:@"fire-app-check"];
|
|
}
|
|
|
|
+ (NSArray<FIRComponent *> *)componentsToRegister {
|
|
FIRComponentCreationBlock creationBlock =
|
|
^id _Nullable(FIRComponentContainer *container, BOOL *isCacheable) {
|
|
*isCacheable = YES;
|
|
return [[FIRAppCheck alloc] initWithApp:container.app];
|
|
};
|
|
|
|
// Use eager instantiation timing to give a chance for FAC token to be requested before it is
|
|
// actually needed to avoid extra delaying dependent requests.
|
|
FIRComponent *appCheckProvider =
|
|
[FIRComponent componentWithProtocol:@protocol(FIRAppCheckInterop)
|
|
instantiationTiming:FIRInstantiationTimingAlwaysEager
|
|
dependencies:@[]
|
|
creationBlock:creationBlock];
|
|
return @[ appCheckProvider ];
|
|
}
|
|
|
|
- (nullable instancetype)initWithApp:(FIRApp *)app {
|
|
id<FIRAppCheckProviderFactory> providerFactory = [FIRAppCheck providerFactory];
|
|
|
|
if (providerFactory == nil) {
|
|
FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderFactoryIsMissing,
|
|
@"Cannot instantiate `FIRAppCheck` for app: %@ without a provider factory. "
|
|
@"Please register a provider factory using "
|
|
@"`AppCheck.setAppCheckProviderFactory(_ ,forAppName:)` method.",
|
|
app.name);
|
|
return nil;
|
|
}
|
|
|
|
id<FIRAppCheckProvider> appCheckProvider = [providerFactory createProviderWithApp:app];
|
|
if (appCheckProvider == nil) {
|
|
FIRLogError(kFIRLoggerAppCheck, kFIRLoggerAppCheckMessageCodeProviderIsMissing,
|
|
@"Cannot instantiate `FIRAppCheck` for app: %@ without an app check provider. "
|
|
@"Please make sure the provide factory returns a valid app check provider.",
|
|
app.name);
|
|
return nil;
|
|
}
|
|
|
|
FIRAppCheckSettings *settings =
|
|
[[FIRAppCheckSettings alloc] initWithApp:app
|
|
userDefault:[NSUserDefaults standardUserDefaults]
|
|
mainBundle:[NSBundle mainBundle]];
|
|
FIRAppCheckTokenRefreshResult *refreshResult =
|
|
[[FIRAppCheckTokenRefreshResult alloc] initWithStatusNever];
|
|
FIRAppCheckTokenRefresher *tokenRefresher =
|
|
[[FIRAppCheckTokenRefresher alloc] initWithRefreshResult:refreshResult settings:settings];
|
|
|
|
FIRAppCheckStorage *storage = [[FIRAppCheckStorage alloc] initWithAppName:app.name
|
|
appID:app.options.googleAppID
|
|
accessGroup:app.options.appGroupID];
|
|
|
|
return [self initWithAppName:app.name
|
|
appCheckProvider:appCheckProvider
|
|
storage:storage
|
|
tokenRefresher:tokenRefresher
|
|
notificationCenter:NSNotificationCenter.defaultCenter
|
|
settings:settings];
|
|
}
|
|
|
|
- (instancetype)initWithAppName:(NSString *)appName
|
|
appCheckProvider:(id<FIRAppCheckProvider>)appCheckProvider
|
|
storage:(id<FIRAppCheckStorageProtocol>)storage
|
|
tokenRefresher:(id<FIRAppCheckTokenRefresherProtocol>)tokenRefresher
|
|
notificationCenter:(NSNotificationCenter *)notificationCenter
|
|
settings:(id<FIRAppCheckSettingsProtocol>)settings {
|
|
self = [super init];
|
|
if (self) {
|
|
_appName = appName;
|
|
_appCheckProvider = appCheckProvider;
|
|
_storage = storage;
|
|
_tokenRefresher = tokenRefresher;
|
|
_notificationCenter = notificationCenter;
|
|
_settings = settings;
|
|
|
|
__auto_type __weak weakSelf = self;
|
|
tokenRefresher.tokenRefreshHandler = ^(FIRAppCheckTokenRefreshCompletion _Nonnull completion) {
|
|
__auto_type strongSelf = weakSelf;
|
|
[strongSelf periodicTokenRefreshWithCompletion:completion];
|
|
};
|
|
}
|
|
return self;
|
|
}
|
|
|
|
#pragma mark - Public
|
|
|
|
+ (instancetype)appCheck {
|
|
FIRApp *defaultApp = [FIRApp defaultApp];
|
|
if (!defaultApp) {
|
|
[NSException raise:kFIRAppCheckErrorDomain
|
|
format:@"The default FirebaseApp instance must be configured before the default"
|
|
@"AppCheck instance can be initialized. One way to ensure that is to "
|
|
@"call `[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App"
|
|
@" Delegate's `application:didFinishLaunchingWithOptions:` "
|
|
@"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
|
|
}
|
|
return [self appCheckWithApp:defaultApp];
|
|
}
|
|
|
|
+ (nullable instancetype)appCheckWithApp:(FIRApp *)firebaseApp {
|
|
id<FIRAppCheckInterop> appCheck = FIR_COMPONENT(FIRAppCheckInterop, firebaseApp.container);
|
|
return (FIRAppCheck *)appCheck;
|
|
}
|
|
|
|
+ (void)setAppCheckProviderFactory:(nullable id<FIRAppCheckProviderFactory>)factory {
|
|
self.providerFactory = factory;
|
|
}
|
|
|
|
- (void)setIsTokenAutoRefreshEnabled:(BOOL)isTokenAutoRefreshEnabled {
|
|
self.settings.isTokenAutoRefreshEnabled = isTokenAutoRefreshEnabled;
|
|
}
|
|
|
|
- (BOOL)isTokenAutoRefreshEnabled {
|
|
return self.settings.isTokenAutoRefreshEnabled;
|
|
}
|
|
|
|
#pragma mark - App Check Provider Ingestion
|
|
|
|
+ (void)setProviderFactory:(nullable id<FIRAppCheckProviderFactory>)providerFactory {
|
|
@synchronized(self) {
|
|
_providerFactory = providerFactory;
|
|
}
|
|
}
|
|
|
|
+ (nullable id<FIRAppCheckProviderFactory>)providerFactory {
|
|
@synchronized(self) {
|
|
return _providerFactory;
|
|
}
|
|
}
|
|
|
|
#pragma mark - FIRAppCheckInterop
|
|
|
|
- (void)getTokenForcingRefresh:(BOOL)forcingRefresh
|
|
completion:(FIRAppCheckTokenHandlerInterop)handler {
|
|
[self retrieveOrRefreshTokenForcingRefresh:forcingRefresh]
|
|
.then(^id _Nullable(FIRAppCheckToken *token) {
|
|
FIRAppCheckTokenResult *result = [[FIRAppCheckTokenResult alloc] initWithToken:token.token
|
|
error:nil];
|
|
handler(result);
|
|
return result;
|
|
})
|
|
.catch(^(NSError *_Nonnull error) {
|
|
FIRAppCheckTokenResult *result =
|
|
[[FIRAppCheckTokenResult alloc] initWithToken:kDummyFACTokenValue error:error];
|
|
handler(result);
|
|
});
|
|
}
|
|
|
|
- (nonnull NSString *)tokenDidChangeNotificationName {
|
|
return FIRAppCheckAppCheckTokenDidChangeNotification;
|
|
}
|
|
|
|
- (nonnull NSString *)notificationAppNameKey {
|
|
return kFIRAppCheckAppNameNotificationKey;
|
|
}
|
|
|
|
- (nonnull NSString *)notificationTokenKey {
|
|
return kFIRAppCheckTokenNotificationKey;
|
|
}
|
|
|
|
#pragma mark - FAA token cache
|
|
|
|
- (FBLPromise<FIRAppCheckToken *> *)retrieveOrRefreshTokenForcingRefresh:(BOOL)forcingRefresh {
|
|
return [FBLPromise do:^id _Nullable {
|
|
if (self.ongoingRetrieveOrRefreshTokenPromise == nil) {
|
|
// Kick off a new operation only when there is not an ongoing one.
|
|
self.ongoingRetrieveOrRefreshTokenPromise =
|
|
[self createRetrieveOrRefreshTokenPromiseForcingRefresh:forcingRefresh]
|
|
|
|
// Release the ongoing operation promise on completion.
|
|
.then(^FIRAppCheckToken *(FIRAppCheckToken *token) {
|
|
self.ongoingRetrieveOrRefreshTokenPromise = nil;
|
|
return token;
|
|
})
|
|
.recover(^NSError *(NSError *error) {
|
|
self.ongoingRetrieveOrRefreshTokenPromise = nil;
|
|
return error;
|
|
});
|
|
}
|
|
return self.ongoingRetrieveOrRefreshTokenPromise;
|
|
}];
|
|
}
|
|
|
|
- (FBLPromise<FIRAppCheckToken *> *)createRetrieveOrRefreshTokenPromiseForcingRefresh:
|
|
(BOOL)forcingRefresh {
|
|
return [self getCachedValidTokenForcingRefresh:forcingRefresh].recover(
|
|
^id _Nullable(NSError *_Nonnull error) {
|
|
return [self refreshToken];
|
|
});
|
|
}
|
|
|
|
- (FBLPromise<FIRAppCheckToken *> *)getCachedValidTokenForcingRefresh:(BOOL)forcingRefresh {
|
|
if (forcingRefresh) {
|
|
FBLPromise *rejectedPromise = [FBLPromise pendingPromise];
|
|
[rejectedPromise reject:[FIRAppCheckErrorUtil cachedTokenNotFound]];
|
|
return rejectedPromise;
|
|
}
|
|
|
|
return [self.storage getToken].then(^id(FIRAppCheckToken *_Nullable token) {
|
|
if (token == nil) {
|
|
return [FIRAppCheckErrorUtil cachedTokenNotFound];
|
|
}
|
|
|
|
BOOL isTokenExpiredOrExpiresSoon =
|
|
[token.expirationDate timeIntervalSinceNow] < kTokenExpirationThreshold;
|
|
if (isTokenExpiredOrExpiresSoon) {
|
|
return [FIRAppCheckErrorUtil cachedTokenExpired];
|
|
}
|
|
|
|
return token;
|
|
});
|
|
}
|
|
|
|
- (FBLPromise<FIRAppCheckToken *> *)refreshToken {
|
|
return [FBLPromise
|
|
wrapObjectOrErrorCompletion:^(FBLPromiseObjectOrErrorCompletion _Nonnull handler) {
|
|
[self.appCheckProvider getTokenWithCompletion:handler];
|
|
}]
|
|
.then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
|
|
return [self.storage setToken:token];
|
|
})
|
|
.then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
|
|
// 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.
|
|
__auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc]
|
|
initWithStatusSuccessAndExpirationDate:token.expirationDate
|
|
receivedAtDate:token.receivedAtDate];
|
|
[self.tokenRefresher updateWithRefreshResult:refreshResult];
|
|
[self postTokenUpdateNotificationWithToken:token];
|
|
return token;
|
|
});
|
|
}
|
|
|
|
#pragma mark - Token auto refresh
|
|
|
|
- (void)periodicTokenRefreshWithCompletion:(FIRAppCheckTokenRefreshCompletion)completion {
|
|
[self retrieveOrRefreshTokenForcingRefresh:NO]
|
|
.then(^id _Nullable(FIRAppCheckToken *_Nullable token) {
|
|
__auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc]
|
|
initWithStatusSuccessAndExpirationDate:token.expirationDate
|
|
receivedAtDate:token.receivedAtDate];
|
|
completion(refreshResult);
|
|
return nil;
|
|
})
|
|
.catch(^(NSError *error) {
|
|
__auto_type refreshResult = [[FIRAppCheckTokenRefreshResult alloc] initWithStatusFailure];
|
|
completion(refreshResult);
|
|
});
|
|
}
|
|
|
|
#pragma mark - Token update notification
|
|
|
|
- (void)postTokenUpdateNotificationWithToken:(FIRAppCheckToken *)token {
|
|
[self.notificationCenter postNotificationName:FIRAppCheckAppCheckTokenDidChangeNotification
|
|
object:self
|
|
userInfo:@{
|
|
kFIRAppCheckTokenNotificationKey : token.token,
|
|
kFIRAppCheckAppNameNotificationKey : self.appName
|
|
}];
|
|
}
|
|
|
|
@end
|
|
|
|
NS_ASSUME_NONNULL_END
|