Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

App Check: optimize auto-refresh #8232

Merged
merged 51 commits into from
Jun 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
ff204f3
App Attest provider: attestation sequence (#7971)
maksymmalyhin Apr 26, 2021
869f87c
Implement app attest key ID storage (#8014)
ncooke3 May 3, 2021
f2b77f0
Merge branch 'master' into appcheck-appattest-main
maksymmalyhin May 4, 2021
39ae2d3
App Check App Attest workflow updates: initial handshake (#8032)
maksymmalyhin May 5, 2021
ccac49c
FIRAppAttestArtifactStorage implementation and tests (#8041)
maksymmalyhin May 5, 2021
c7558b5
Implement App Attest `getRandomChallenge` (#8033)
ncooke3 May 6, 2021
e7f1ff8
Merge branch 'master' into appcheck-appattest-main
maksymmalyhin May 6, 2021
ed07e4b
Define Exchange AppAttest Assertion for FAC token API (#8058)
ncooke3 May 11, 2021
67b5c3a
Merge branch 'master' into appcheck-appattest-main
maksymmalyhin May 11, 2021
786f613
App Check App Attest: attestation request (#8059)
maksymmalyhin May 12, 2021
6742e33
Merge branch 'master' into appcheck-appattest-main
maksymmalyhin May 12, 2021
a35d7bd
App Check App Attest initial handshake adjustments (#8067)
maksymmalyhin May 12, 2021
2b16a5f
Merge remote-tracking branch 'origin/master' into appcheck-appattest-…
maksymmalyhin May 13, 2021
c2bb06b
Implement API for ExchangeAppAttestAssertionRequest endpoint (#8065)
ncooke3 May 13, 2021
cd53ea8
Merge remote-tracking branch 'origin/master' into appcheck-appattest-…
maksymmalyhin May 14, 2021
e04a789
Merge branch 'appcheck-appattest-main' of github.com:firebase/firebas…
maksymmalyhin May 14, 2021
ac17a23
App Check App Attest assertion flow (#8083)
maksymmalyhin May 17, 2021
b9d638e
Merge remote-tracking branch 'origin/master' into appcheck-appattest-…
maksymmalyhin May 17, 2021
cea2f68
App Check: store App Attest artifact per key ID (#8097)
maksymmalyhin May 18, 2021
2b70bf0
App Check: prevent concurrent token requests (#8117)
maksymmalyhin May 21, 2021
f134778
Merge remote-tracking branch 'origin/master' into appcheck-appattest-…
maksymmalyhin May 21, 2021
2102187
Changelog
maksymmalyhin May 21, 2021
c0650aa
Merge branch 'master' into appcheck-appattest-main
maksymmalyhin May 31, 2021
b8f80f3
App Check App Attest: handle attestation rejection (#8170)
maksymmalyhin Jun 1, 2021
76486af
Add FIRAppAttestProvider.h the umbrella header
maksymmalyhin Jun 1, 2021
67c6d91
Add receivedAtDate property to the FAC token
maksymmalyhin Jun 2, 2021
a7c4792
Update tests to check receivedAtDate field where important
maksymmalyhin Jun 2, 2021
0317855
[WIP] Use FIRAppCheckTokenRefreshResult instead in the refresher API
maksymmalyhin Jun 3, 2021
e24afb9
Merge remote-tracking branch 'origin/master' into mm/appcheck-refresh
maksymmalyhin Jun 4, 2021
8c40b6d
[WIP] Fix refgresher usage
maksymmalyhin Jun 4, 2021
e0e570c
Update tests with new API, keep old logic
maksymmalyhin Jun 4, 2021
e30ba15
Merge remote-tracking branch 'origin/master' into mm/appcheck-refresh
maksymmalyhin Jun 7, 2021
6b846fc
Update tests with new logic
maksymmalyhin Jun 7, 2021
847fb98
WIP
maksymmalyhin Jun 7, 2021
813c671
WIP
maksymmalyhin Jun 8, 2021
5987d2e
Initial refresh tests and fixes.
maksymmalyhin Jun 9, 2021
8894e82
Add #import <TargetConditionals.h> where needed.
maksymmalyhin Jun 9, 2021
4391ce9
Formatting
maksymmalyhin Jun 9, 2021
93836e3
Cleanup and test updates
maksymmalyhin Jun 10, 2021
5276c56
style
maksymmalyhin Jun 10, 2021
40fc64b
Comments
maksymmalyhin Jun 10, 2021
5c312bc
Merge remote-tracking branch 'origin/master' into mm/appcheck-refresh
maksymmalyhin Jun 10, 2021
f4a7c7f
Cleanup and comments
maksymmalyhin Jun 10, 2021
a9812ca
Fix catalyst
maksymmalyhin Jun 10, 2021
4713d08
Changelog
maksymmalyhin Jun 10, 2021
9825b6f
Changelog version fix
maksymmalyhin Jun 11, 2021
3ec8edc
Typo
maksymmalyhin Jun 11, 2021
26241c6
Cleanup
maksymmalyhin Jun 11, 2021
f9d140d
Typo
maksymmalyhin Jun 11, 2021
d62661c
Merge branch 'mm/appcheck-refresh' of github.com:firebase/firebase-io…
maksymmalyhin Jun 11, 2021
c6aa5ca
Imports order
maksymmalyhin Jun 11, 2021
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
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
  • Loading branch information
maksymmalyhin authored May 12, 2021
commit 786f613be0f98ee9335ea2a7dba1c08ea33c3051
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,29 @@
#import <Foundation/Foundation.h>

@class FBLPromise<Result>;
@class FIRAppAttestAttestationResponse;
@class FIRAppCheckToken;
@protocol FIRAppCheckAPIServiceProtocol;

NS_ASSUME_NONNULL_BEGIN

/// Methods to send API requests required for App Attest based attestation sequence.
@protocol FIRAppAttestAPIServiceProtocol <NSObject>

/// Request a random challenge from server.
- (FBLPromise<NSData *> *)getRandomChallenge;

/// Exchanges attestation data to FAC token.
- (FBLPromise<FIRAppCheckToken *> *)appCheckTokenWithAttestation:(NSData *)attestation
keyID:(NSString *)keyID
challenge:(NSData *)challenge;
/// Sends attestation data to Firebase backend for validation.
/// @param attestation The App Attest key attestation data obtained from the method
/// `-[DCAppAttestService attestKey:clientDataHash:completionHandler:]` using the random challenge
/// received from Firebase backend.
/// @param keyID The key ID used to generate the attestation.
/// @param challenge The challenge used to generate the attestation.
/// @return A promise that is fulfilled with a response object with an encrypted attestation
/// artifact and an Firebase App Check token or rejected with an error.
- (FBLPromise<FIRAppAttestAttestationResponse *> *)attestKeyWithAttestation:(NSData *)attestation
keyID:(NSString *)keyID
challenge:(NSData *)challenge;

/// Exchanges attestation data (artifact & assertion) and a challenge for a FAC token.
- (FBLPromise<FIRAppCheckToken *> *)appCheckTokenWithArtifact:(NSData *)artifact
Expand All @@ -39,8 +48,14 @@ NS_ASSUME_NONNULL_BEGIN

@end

/// A default implementation of `FIRAppAttestAPIServiceProtocol`.
@interface FIRAppAttestAPIService : NSObject <FIRAppAttestAPIServiceProtocol>

/// Default initializer.
/// @param APIService An instance implementing `FIRAppCheckAPIServiceProtocol` to be used to send
/// network requests to Firebase App Check backend.
/// @param projectID A Firebase project ID for the requests (`FIRApp.options.projectID`).
/// @param appID A Firebase app ID for the requests (`FIRApp.options.googleAppID`).
- (instancetype)initWithAPIService:(id<FIRAppCheckAPIServiceProtocol>)APIService
projectID:(NSString *)projectID
appID:(NSString *)appID;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,21 @@
#import "FBLPromises.h"
#endif

#import "FirebaseAppCheck/Sources/AppAttestProvider/API/FIRAppAttestAttestationResponse.h"
#import "FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckAPIService.h"

#import <GoogleUtilities/GULURLSessionDataResponse.h>
#import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h"

NS_ASSUME_NONNULL_BEGIN

static NSString *const kRequestFieldAttestation = @"attestation_statement";
static NSString *const kRequestFieldKeyID = @"key_id";
static NSString *const kRequestFieldChallenge = @"challenge";

static NSString *const kContentTypeKey = @"Content-Type";
static NSString *const kJSONContentType = @"application/json";

@interface FIRAppAttestAPIService ()

@property(nonatomic, readonly) id<FIRAppCheckAPIServiceProtocol> APIService;
Expand All @@ -50,28 +60,26 @@ - (instancetype)initWithAPIService:(id<FIRAppCheckAPIServiceProtocol>)APIService
return self;
}

- (dispatch_queue_t)backgroundQueue {
return dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
}

- (FBLPromise<FIRAppCheckToken *> *)appCheckTokenWithArtifact:(NSData *)artifact
challenge:(NSData *)challenge
assertion:(NSData *)assertion {
// TODO: Implement.
return [FBLPromise resolvedWith:nil];
}

- (nonnull FBLPromise<FIRAppCheckToken *> *)
appCheckTokenWithAttestation:(nonnull NSData *)attestation
keyID:(nonnull NSString *)keyID
challenge:(nonnull NSData *)challenge {
// TODO: Implement.
return [FBLPromise resolvedWith:nil];
}
#pragma mark - Random Challenge

- (nonnull FBLPromise<NSData *> *)getRandomChallenge {
NSString *URLString =
[NSString stringWithFormat:@"%@/projects/%@/apps/%@:generateAppAttestChallenge",
self.APIService.baseURL, self.projectID, self.appID];
NSURL *URL = [NSURL URLWithString:URLString];

return [FBLPromise onQueue:[self defaultQueue]
return [FBLPromise onQueue:[self backgroundQueue]
do:^id _Nullable {
return [self.APIService sendRequestWithURL:URL
HTTPMethod:@"POST"
Expand All @@ -86,7 +94,7 @@ - (instancetype)initWithAPIService:(id<FIRAppCheckAPIServiceProtocol>)APIService
#pragma mark - Challenge response parsing

- (FBLPromise<NSData *> *)randomChallengeWithAPIResponse:(GULURLSessionDataResponse *)response {
return [FBLPromise onQueue:[self defaultQueue]
return [FBLPromise onQueue:[self backgroundQueue]
do:^id _Nullable {
NSError *error;

Expand All @@ -98,7 +106,7 @@ - (instancetype)initWithAPIService:(id<FIRAppCheckAPIServiceProtocol>)APIService
}];
}

- (NSData *)randomChallengeFromResponseBody:(NSData *)response error:(NSError **)outError {
- (nullable NSData *)randomChallengeFromResponseBody:(NSData *)response error:(NSError **)outError {
if (response.length <= 0) {
FIRAppCheckSetErrorToPointer(
[FIRAppCheckErrorUtil errorWithFailureReason:@"Empty server response body."], outError);
Expand Down Expand Up @@ -126,8 +134,70 @@ - (NSData *)randomChallengeFromResponseBody:(NSData *)response error:(NSError **
return randomChallenge;
}

- (dispatch_queue_t)defaultQueue {
return dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
#pragma mark - Attestation request

- (FBLPromise<FIRAppAttestAttestationResponse *> *)attestKeyWithAttestation:(NSData *)attestation
keyID:(NSString *)keyID
challenge:(NSData *)challenge {
NSString *URLString =
[NSString stringWithFormat:@"%@/projects/%@/apps/%@:exchangeAppAttestAttestation",
self.APIService.baseURL, self.projectID, self.appID];
NSURL *URL = [NSURL URLWithString:URLString];

return [self HTTPBodyWithAttestation:attestation keyID:keyID challenge:challenge]
.then(^FBLPromise<GULURLSessionDataResponse *> *(NSData *HTTPBody) {
return [self.APIService sendRequestWithURL:URL
HTTPMethod:@"POST"
body:HTTPBody
additionalHeaders:@{kContentTypeKey : kJSONContentType}];
})
.then(^id _Nullable(GULURLSessionDataResponse *_Nullable URLResponse) {
NSError *error;

__auto_type response =
[[FIRAppAttestAttestationResponse alloc] initWithResponseData:URLResponse.HTTPBody
requestDate:[NSDate date]
error:&error];

return response ?: error;
});
}

- (FBLPromise<NSData *> *)HTTPBodyWithAttestation:(NSData *)attestation
keyID:(NSString *)keyID
challenge:(NSData *)challenge {
if (attestation.length <= 0 || keyID.length <= 0 || challenge.length <= 0) {
FBLPromise *rejectedPromise = [FBLPromise pendingPromise];
[rejectedPromise reject:[FIRAppCheckErrorUtil
errorWithFailureReason:@"Missing or empty request parameter."]];
return rejectedPromise;
}

return [FBLPromise
onQueue:[self backgroundQueue]
do:^id _Nullable {
NSError *encodingError;
NSData *payloadJSON = [NSJSONSerialization dataWithJSONObject:@{
kRequestFieldKeyID : keyID,
kRequestFieldAttestation : [self base64StringWithData:attestation],
kRequestFieldChallenge : [self base64StringWithData:challenge]
}
options:0
error:&encodingError];

if (payloadJSON != nil) {
return payloadJSON;
} else {
return [FIRAppCheckErrorUtil JSONSerializationError:encodingError];
}
}];
}

- (NSString *)base64StringWithData:(NSData *)data {
// TODO: Need to encode in base64URL?
return [data base64EncodedStringWithOptions:0];
}

@end

NS_ASSUME_NONNULL_END
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

NS_ASSUME_NONNULL_BEGIN

@interface FIRAppAttestInitialHandshakeResponse : NSObject
@interface FIRAppAttestAttestationResponse : NSObject

/// App Attest attestation artifact required to refresh Firebase App Check token.
@property(nonatomic, readonly) NSData *artifact;
Expand All @@ -33,6 +33,11 @@ NS_ASSUME_NONNULL_BEGIN
- (instancetype)initWithArtifact:(NSData *)artifact
token:(FIRAppCheckToken *)token NS_DESIGNATED_INITIALIZER;

/// Init with the server response.
- (nullable instancetype)initWithResponseData:(NSData *)response
requestDate:(NSDate *)requestDate
error:(NSError **)outError;

@end

NS_ASSUME_NONNULL_END
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* 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/AppAttestProvider/API/FIRAppAttestAttestationResponse.h"

#import "FirebaseAppCheck/Sources/Core/APIService/FIRAppCheckToken+APIResponse.h"
#import "FirebaseAppCheck/Sources/Core/Errors/FIRAppCheckErrorUtil.h"

@implementation FIRAppAttestAttestationResponse

- (instancetype)initWithArtifact:(NSData *)artifact token:(FIRAppCheckToken *)token {
self = [super init];
if (self) {
_artifact = artifact;
_token = token;
}
return self;
}

- (nullable instancetype)initWithResponseData:(NSData *)response
requestDate:(NSDate *)requestDate
error:(NSError **)outError {
if (response.length <= 0) {
FIRAppCheckSetErrorToPointer(
[FIRAppCheckErrorUtil
errorWithFailureReason:
@"Failed to parse the initial handshake response. Empty server response body."],
outError);
return nil;
}

NSError *JSONError;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&JSONError];

if (![responseDict isKindOfClass:[NSDictionary class]]) {
FIRAppCheckSetErrorToPointer([FIRAppCheckErrorUtil JSONSerializationError:JSONError], outError);
return nil;
}

NSString *artifactBase64String = responseDict[@"artifact"];
if (![artifactBase64String isKindOfClass:[NSString class]]) {
FIRAppCheckSetErrorToPointer(
[FIRAppCheckErrorUtil appAttestAttestationResponseErrorWithMissingField:@"artifact"],
outError);
return nil;
}
NSData *artifactData = [[NSData alloc] initWithBase64EncodedString:artifactBase64String
options:0];
if (artifactData == nil) {
FIRAppCheckSetErrorToPointer(
[FIRAppCheckErrorUtil appAttestAttestationResponseErrorWithMissingField:@"artifact"],
outError);
return nil;
}

NSDictionary *attestationTokenDict = responseDict[@"attestationToken"];
if (![attestationTokenDict isKindOfClass:[NSDictionary class]]) {
FIRAppCheckSetErrorToPointer(
[FIRAppCheckErrorUtil
appAttestAttestationResponseErrorWithMissingField:@"attestationToken"],
outError);
return nil;
}

FIRAppCheckToken *appCheckToken =
[[FIRAppCheckToken alloc] initWithResponseDict:attestationTokenDict
requestDate:requestDate
error:outError];

if (appCheckToken == nil) {
return nil;
}

return [self initWithArtifact:artifactData token:appCheckToken];
}

@end

This file was deleted.

23 changes: 19 additions & 4 deletions FirebaseAppCheck/Sources/AppAttestProvider/FIRAppAttestProvider.m
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#endif

#import "FirebaseAppCheck/Sources/AppAttestProvider/API/FIRAppAttestAPIService.h"
#import "FirebaseAppCheck/Sources/AppAttestProvider/API/FIRAppAttestAttestationResponse.h"
#import "FirebaseAppCheck/Sources/AppAttestProvider/FIRAppAttestProviderState.h"
#import "FirebaseAppCheck/Sources/AppAttestProvider/FIRAppAttestService.h"
#import "FirebaseAppCheck/Sources/AppAttestProvider/Storage/FIRAppAttestArtifactStorage.h"
Expand Down Expand Up @@ -184,14 +185,28 @@ - (void)getTokenWithCompletion:(void (^)(FIRAppCheckToken *_Nullable, NSError *_
})
// TODO: Handle a possible key rejection - generate another key.
.thenOn(self.queue,
^FBLPromise<FIRAppCheckToken *> *(FIRAppAttestKeyAttestationResult *result) {
^FBLPromise<FIRAppAttestAttestationResponse *> *(
FIRAppAttestKeyAttestationResult *result) {
// 3. Exchange the attestation to FAC token.
return [self.APIService appCheckTokenWithAttestation:result.attestation
keyID:result.keyID
challenge:result.challenge];
return [self.APIService attestKeyWithAttestation:result.attestation
keyID:result.keyID
challenge:result.challenge];
})
.thenOn(self.queue,
^FBLPromise<FIRAppCheckToken *> *(FIRAppAttestAttestationResponse *response) {
// 4. Save the artifact and return the received FAC token.
return [self saveArtifactAndGetAppCheckTokenFromResponse:response];
});
}

- (FBLPromise<FIRAppCheckToken *> *)saveArtifactAndGetAppCheckTokenFromResponse:
(FIRAppAttestAttestationResponse *)response {
return [self.artifactStorage setArtifact:response.artifact].thenOn(
self.queue, ^FIRAppCheckToken *(id result) {
return response.token;
});
}

#pragma mark - Token refresh sequence

- (FBLPromise<FIRAppCheckToken *> *)refreshTokenWithKeyID:(NSString *)keyID
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ NS_ASSUME_NONNULL_BEGIN
requestDate:(NSDate *)requestDate
error:(NSError **)outError;

- (nullable instancetype)initWithResponseDict:(NSDictionary<NSString *, id> *)responseDict
requestDate:(NSDate *)requestDate
error:(NSError **)outError;

@end

NS_ASSUME_NONNULL_END
Loading