Files
firebase-ios-sdk/FirebaseAppCheck/Tests/Unit/DeviceCheckProvider/FIRDeviceCheckProviderTests.m
T
Maksym MalyhinandNick Cooke 2ec4dbdae4 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 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>
2021-06-11 17:35:37 -04:00

178 lines
7.1 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 <XCTest/XCTest.h>
#import <OCMock/OCMock.h>
#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/FIRDeviceCheckProvider.h"
#import "FirebaseCore/Sources/Private/FirebaseCoreInternal.h"
API_AVAILABLE(ios(11.0), macos(10.15), tvos(11.0))
API_UNAVAILABLE(watchos)
@interface FIRDeviceCheckProviderTests : XCTestCase
@property(nonatomic) FIRDeviceCheckProvider *provider;
@property(nonatomic) id fakeAPIService;
@property(nonatomic) id fakeTokenGenerator;
@end
@interface FIRDeviceCheckProvider (Tests)
- (instancetype)initWithAPIService:(id<FIRDeviceCheckAPIServiceProtocol>)APIService
deviceTokenGenerator:(id<FIRDeviceCheckTokenGenerator>)deviceTokenGenerator;
@end
@implementation FIRDeviceCheckProviderTests
- (void)setUp {
[super setUp];
self.fakeAPIService = OCMProtocolMock(@protocol(FIRDeviceCheckAPIServiceProtocol));
self.fakeTokenGenerator = OCMProtocolMock(@protocol(FIRDeviceCheckTokenGenerator));
self.provider = [[FIRDeviceCheckProvider alloc] initWithAPIService:self.fakeAPIService
deviceTokenGenerator:self.fakeTokenGenerator];
}
- (void)tearDown {
self.provider = nil;
self.fakeAPIService = nil;
self.fakeTokenGenerator = nil;
}
- (void)testInitWithValidApp {
FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"app_id" GCMSenderID:@"sender_id"];
options.APIKey = @"api_key";
options.projectID = @"project_id";
FIRApp *app = [[FIRApp alloc] initInstanceWithName:@"testInitWithValidApp" options:options];
XCTAssertNotNil([[FIRDeviceCheckProvider alloc] initWithApp:app]);
}
- (void)testInitWithIncompleteApp {
FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"app_id" GCMSenderID:@"sender_id"];
options.projectID = @"project_id";
FIRApp *missingAPIKeyApp = [[FIRApp alloc] initInstanceWithName:@"testInitWithValidApp"
options:options];
XCTAssertNil([[FIRDeviceCheckProvider alloc] initWithApp:missingAPIKeyApp]);
options.projectID = nil;
options.APIKey = @"api_key";
FIRApp *missingProjectIDApp = [[FIRApp alloc] initInstanceWithName:@"testInitWithValidApp"
options:options];
XCTAssertNil([[FIRDeviceCheckProvider alloc] initWithApp:missingProjectIDApp]);
}
- (void)testGetTokenSuccess {
// 1. Expect device token to be generated.
NSData *deviceToken = [NSData data];
id generateTokenArg = [OCMArg invokeBlockWithArgs:deviceToken, [NSNull null], nil];
OCMExpect([self.fakeTokenGenerator generateTokenWithCompletionHandler:generateTokenArg]);
// 2. Expect FAA token to be requested.
FIRAppCheckToken *validToken = [[FIRAppCheckToken alloc] initWithToken:@"valid_token"
expirationDate:[NSDate distantFuture]
receivedAtDate:[NSDate date]];
OCMExpect([self.fakeAPIService appCheckTokenWithDeviceToken:deviceToken])
.andReturn([FBLPromise resolvedWith:validToken]);
// 3. Call getToken and validate the result.
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"completionExpectation"];
[self.provider
getTokenWithCompletion:^(FIRAppCheckToken *_Nullable token, NSError *_Nullable error) {
[completionExpectation fulfill];
XCTAssertEqualObjects(token.token, validToken.token);
XCTAssertEqualObjects(token.expirationDate, validToken.expirationDate);
XCTAssertEqualObjects(token.receivedAtDate, validToken.receivedAtDate);
XCTAssertNil(error);
}];
[self waitForExpectations:@[ completionExpectation ] timeout:0.5];
// 4. Verify fakes.
OCMVerifyAll(self.fakeAPIService);
OCMVerifyAll(self.fakeTokenGenerator);
}
- (void)testGetTokenWhenDeviceTokenFails {
// 1. Expect device token to be generated.
NSError *deviceTokenError = [NSError errorWithDomain:@"FIRDeviceCheckProviderTests"
code:-1
userInfo:nil];
id generateTokenArg = [OCMArg invokeBlockWithArgs:[NSNull null], deviceTokenError, nil];
OCMExpect([self.fakeTokenGenerator generateTokenWithCompletionHandler:generateTokenArg]);
// 2. Don't expect FAA token to be requested.
OCMReject([self.fakeAPIService appCheckTokenWithDeviceToken:[OCMArg any]]);
// 3. Call getToken and validate the result.
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"completionExpectation"];
[self.provider
getTokenWithCompletion:^(FIRAppCheckToken *_Nullable token, NSError *_Nullable error) {
[completionExpectation fulfill];
XCTAssertNil(token);
XCTAssertEqualObjects(error, deviceTokenError);
}];
[self waitForExpectations:@[ completionExpectation ] timeout:0.5];
// 4. Verify fakes.
OCMVerifyAll(self.fakeAPIService);
OCMVerifyAll(self.fakeTokenGenerator);
}
- (void)testGetTokenWhenAPIServiceFails {
// 1. Expect device token to be generated.
NSData *deviceToken = [NSData data];
id generateTokenArg = [OCMArg invokeBlockWithArgs:deviceToken, [NSNull null], nil];
OCMExpect([self.fakeTokenGenerator generateTokenWithCompletionHandler:generateTokenArg]);
// 2. Expect FAA token to be requested.
NSError *APIServiceError = [NSError errorWithDomain:@"FIRDeviceCheckProviderTests"
code:-1
userInfo:nil];
FBLPromise *rejectedPromise = [FBLPromise pendingPromise];
[rejectedPromise reject:APIServiceError];
OCMExpect([self.fakeAPIService appCheckTokenWithDeviceToken:deviceToken])
.andReturn(rejectedPromise);
// 3. Call getToken and validate the result.
XCTestExpectation *completionExpectation =
[self expectationWithDescription:@"completionExpectation"];
[self.provider
getTokenWithCompletion:^(FIRAppCheckToken *_Nullable token, NSError *_Nullable error) {
[completionExpectation fulfill];
XCTAssertNil(token);
XCTAssertEqualObjects(error, APIServiceError);
}];
[self waitForExpectations:@[ completionExpectation ] timeout:0.5];
// 4. Verify fakes.
OCMVerifyAll(self.fakeAPIService);
OCMVerifyAll(self.fakeTokenGenerator);
}
@end