GIDSignInTest.m 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128
  1. // Copyright 2021 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #import <TargetConditionals.h>
  15. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  16. #import <UIKit/UIKit.h>
  17. #elif TARGET_OS_OSX
  18. #import <AppKit/AppKit.h>
  19. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  20. #import <SafariServices/SafariServices.h>
  21. #import <XCTest/XCTest.h>
  22. // Test module imports
  23. @import GoogleSignIn;
  24. #import "GoogleSignIn/Sources/GIDAuthorizationFlowProcessor/API/GIDAuthorizationFlowProcessor.h"
  25. #import "GoogleSignIn/Sources/GIDAuthorizationFlowProcessor/Implementations/Fakes/GIDFakeAuthorizationFlowProcessor.h"
  26. #import "GoogleSignIn/Sources/GIDEMMSupport.h"
  27. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  28. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  29. #import "GoogleSignIn/Sources/GIDSignInPreferences.h"
  30. #import "GoogleSignIn/Sources/GIDKeychainHandler/Implementations/Fakes/GIDFakeKeychainHandler.h"
  31. #import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/Fakes/GIDFakeHTTPFetcher.h"
  32. #import "GoogleSignIn/Sources/GIDHTTPFetcher/Implementations/GIDHTTPFetcher.h"
  33. #import "GoogleSignIn/Sources/GIDProfileDataFetcher/API/GIDProfileDataFetcher.h"
  34. #import "GoogleSignIn/Sources/GIDProfileDataFetcher/Implementations/Fakes/GIDFakeProfileDataFetcher.h"
  35. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  36. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  37. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  38. #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.h"
  39. #import "GoogleSignIn/Tests/Unit/GIDProfileData+Testing.h"
  40. #import "GoogleSignIn/Tests/Unit/OIDAuthorizationResponse+Testing.h"
  41. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  42. #ifdef SWIFT_PACKAGE
  43. @import AppAuth;
  44. @import GTMAppAuth;
  45. @import GTMSessionFetcherCore;
  46. @import OCMock;
  47. #else
  48. #import <AppAuth/OIDAuthState.h>
  49. #import <AppAuth/OIDAuthorizationRequest.h>
  50. #import <AppAuth/OIDAuthorizationResponse.h>
  51. #import <AppAuth/OIDAuthorizationService.h>
  52. #import <AppAuth/OIDError.h>
  53. #import <AppAuth/OIDGrantTypes.h>
  54. #import <AppAuth/OIDTokenRequest.h>
  55. #import <AppAuth/OIDTokenResponse.h>
  56. #import <AppAuth/OIDURLQueryComponent.h>
  57. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  58. #import <AppAuth/OIDAuthorizationService+IOS.h>
  59. #elif TARGET_OS_OSX
  60. #import <AppAuth/OIDAuthorizationService+Mac.h>
  61. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  62. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  63. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  64. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  65. #import <OCMock/OCMock.h>
  66. #endif
  67. // Create a BLOCK to store the actual address for arg in param.
  68. #define SAVE_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  69. param = arg;\
  70. return YES;\
  71. }]
  72. #define COPY_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  73. param = [arg copy];\
  74. return YES;\
  75. }]
  76. static NSString * const kFakeGaiaID = @"123456789";
  77. static NSString * const kFakeIDToken = @"FakeIDToken";
  78. static NSString * const kClientId = @"FakeClientID";
  79. static NSString * const kDotReversedClientId = @"FakeClientID";
  80. static NSString * const kClientId2 = @"FakeClientID2";
  81. static NSString * const kServerClientId = @"FakeServerClientID";
  82. static NSString * const kLanguage = @"FakeLanguage";
  83. static NSString * const kAuthCode = @"FakeAuthCode";
  84. static NSString * const kKeychainName = @"auth";
  85. static NSString * const kUserEmail = @"FakeUserEmail";
  86. static NSString * const kVerifier = @"FakeVerifier";
  87. static NSString * const kOpenIDRealm = @"FakeRealm";
  88. static NSString * const kFakeHostedDomain = @"fakehosteddomain.com";
  89. static NSString * const kFakeUserName = @"fake username";
  90. static NSString * const kFakeUserGivenName = @"fake";
  91. static NSString * const kFakeUserFamilyName = @"username";
  92. static NSString * const kFakeUserPictureURL = @"fake_user_picture_url";
  93. static NSString * const kContinueURL = @"com.google.UnitTests:/oauth2callback";
  94. static NSString * const kContinueURLWithClientID = @"FakeClientID:/oauth2callback";
  95. static NSString * const kWrongSchemeURL = @"wrong.app:/oauth2callback";
  96. static NSString * const kWrongPathURL = @"com.google.UnitTests:/wrong_path";
  97. static NSString * const kEMMRestartAuthURL =
  98. @"com.google.UnitTests:///emmcallback?action=restart_auth";
  99. static NSString * const kEMMWrongPathURL =
  100. @"com.google.UnitTests:///unknowcallback?action=restart_auth";
  101. static NSString * const kEMMWrongActionURL =
  102. @"com.google.UnitTests:///emmcallback?action=unrecognized";
  103. static NSString * const kDevicePolicyAppBundleID = @"com.google.DevicePolicy";
  104. static NSString * const kAppHasRunBeforeKey = @"GPP_AppHasRunBefore";
  105. static NSString * const kFingerprintKeychainName = @"fingerprint";
  106. static NSString * const kVerifierKeychainName = @"verifier";
  107. static NSString * const kVerifierKey = @"verifier";
  108. //static NSString * const kOpenIDRealmKey = @"openid.realm";
  109. static NSString * const kSavedKeychainServiceName = @"saved-keychain";
  110. static NSString * const kKeychainAccountName = @"GooglePlus";
  111. static NSString * const kUserNameKey = @"name";
  112. static NSString * const kUserGivenNameKey = @"givenName";
  113. static NSString * const kUserFamilyNameKey = @"familyName";
  114. static NSString * const kUserImageKey = @"picture";
  115. static NSString * const kAppName = @"UnitTests";
  116. static NSString * const kUserIDKey = @"userID";
  117. static NSString * const kHostedDomainKey = @"hostedDomain";
  118. static NSString * const kIDTokenExpirationKey = @"idTokenExp";
  119. static NSString * const kCustomKeychainName = @"CUSTOM_KEYCHAIN_NAME";
  120. static NSString * const kAddActivity = @"http://schemas.google.com/AddActivity";
  121. static NSString * const kErrorDomain = @"ERROR_DOMAIN";
  122. static NSInteger const kErrorCode = 212;
  123. static NSString *const kDriveScope = @"https://www.googleapis.com/auth/drive";
  124. static NSString *const kTokenURL = @"https://oauth2.googleapis.com/token";
  125. static NSString *const kFakeURL = @"http://foo.com";
  126. static NSString *const kNewScope = @"newScope";
  127. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  128. // This category is used to allow the test to swizzle a private method.
  129. @interface UIViewController (Testing)
  130. // This private method provides access to the window. It's declared here to avoid a warning about
  131. // an unrecognized selector in the test.
  132. - (UIWindow *)_window;
  133. @end
  134. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  135. // This class extension exposes GIDSignIn methods to our tests.
  136. @interface GIDSignIn ()
  137. // Exposing private method so we can call it to disambiguate between interactive and non-interactive
  138. // sign-in attempts for the purposes of testing the GIDSignInUIDelegate (which should not be
  139. // called in the case of a non-interactive sign in).
  140. - (void)authenticateMaybeInteractively:(BOOL)interactive withParams:(NSDictionary *)params;
  141. - (BOOL)assertValidPresentingViewContoller;
  142. @end
  143. @interface GIDSignInTest : XCTestCase {
  144. @private
  145. // Whether or not the OS version is eligible for EMM.
  146. BOOL _isEligibleForEMM;
  147. // Mock `OIDAuthState`.
  148. id _authState;
  149. // Mock `OIDTokenResponse`.
  150. id _tokenResponse;
  151. // Mock `OIDTokenRequest`.
  152. id _tokenRequest;
  153. // Mock `GTMAppAuthFetcherAuthorization`.
  154. id _authorization;
  155. // Fake for `GIDKeychainHandler`.
  156. GIDFakeKeychainHandler *_keychainHandler;
  157. // Fake for `GIDHTTPFetcher`.
  158. GIDFakeHTTPFetcher *_httpFetcher;
  159. // Fake for `GIDAuthorizationFlowProcessor`.
  160. GIDFakeAuthorizationFlowProcessor *_authorizationFlowProcessor;
  161. // Fake for `GIDProfileDataFetcher`.
  162. GIDFakeProfileDataFetcher *_profileDataFetcher;
  163. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  164. // Mock `UIViewController`.
  165. id _presentingViewController;
  166. #elif TARGET_OS_OSX
  167. // Mock `NSWindow`.
  168. id _presentingWindow;
  169. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  170. // Mock for `GIDGoogleUser`.
  171. id _user;
  172. // Mock for `OIDAuthorizationService`.
  173. id _oidAuthorizationService;
  174. // Parameter saved from delegate call.
  175. NSError *_authError;
  176. // Whether callback block has been called.
  177. BOOL _completionCalled;
  178. // Fake [NSBundle mainBundle];
  179. GIDFakeMainBundle *_fakeMainBundle;
  180. // The `GIDSignIn` object being tested.
  181. GIDSignIn *_signIn;
  182. // The configuration to be used when testing `GIDSignIn`.
  183. GIDConfiguration *_configuration;
  184. // The completion to be used when testing `GIDSignIn`.
  185. GIDSignInCompletion _completion;
  186. // The saved token request callback.
  187. OIDTokenCallback _savedTokenCallback;
  188. }
  189. @end
  190. @implementation GIDSignInTest
  191. #pragma mark - Lifecycle
  192. - (void)setUp {
  193. [super setUp];
  194. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  195. _isEligibleForEMM = [UIDevice currentDevice].systemVersion.integerValue >= 9;
  196. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  197. // States
  198. _completionCalled = NO;
  199. // Mocks
  200. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  201. _presentingViewController = OCMStrictClassMock([UIViewController class]);
  202. #elif TARGET_OS_OSX
  203. _presentingWindow = OCMStrictClassMock([NSWindow class]);
  204. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  205. _authState = OCMStrictClassMock([OIDAuthState class]);
  206. OCMStub([_authState alloc]).andReturn(_authState);
  207. OCMStub([_authState initWithAuthorizationResponse:OCMOCK_ANY]).andReturn(_authState);
  208. _tokenResponse = OCMStrictClassMock([OIDTokenResponse class]);
  209. _tokenRequest = OCMStrictClassMock([OIDTokenRequest class]);
  210. _authorization = OCMStrictClassMock([GTMAppAuthFetcherAuthorization class]);
  211. OCMStub([_authorization alloc]).andReturn(_authorization);
  212. OCMStub([_authorization initWithAuthState:OCMOCK_ANY]).andReturn(_authorization);
  213. _user = OCMStrictClassMock([GIDGoogleUser class]);
  214. _oidAuthorizationService = OCMStrictClassMock([OIDAuthorizationService class]);
  215. OCMStub([self->_oidAuthorizationService
  216. performTokenRequest:OCMOCK_ANY
  217. callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
  218. // Fakes
  219. _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
  220. [_fakeMainBundle startFakingWithClientID:kClientId];
  221. [_fakeMainBundle fakeAllSchemesSupported];
  222. // Object under test
  223. [[NSUserDefaults standardUserDefaults] setBool:YES
  224. forKey:kAppHasRunBeforeKey];
  225. _keychainHandler = [[GIDFakeKeychainHandler alloc] init];
  226. _httpFetcher = [[GIDFakeHTTPFetcher alloc] init];
  227. _authorizationFlowProcessor = [[GIDFakeAuthorizationFlowProcessor alloc] init];
  228. _profileDataFetcher = [[GIDFakeProfileDataFetcher alloc] init];
  229. _signIn = [[GIDSignIn alloc] initWithKeychainHandler:_keychainHandler
  230. httpFetcher:_httpFetcher
  231. profileDataFetcher:_profileDataFetcher
  232. authorizationFlowProcessor:_authorizationFlowProcessor];
  233. __weak GIDSignInTest *weakSelf = self;
  234. _completion = ^(GIDSignInResult *_Nullable signInResult, NSError * _Nullable error) {
  235. GIDSignInTest *strongSelf = weakSelf;
  236. if (!signInResult) {
  237. XCTAssertNotNil(error, @"should have an error if the signInResult is nil");
  238. }
  239. XCTAssertFalse(strongSelf->_completionCalled, @"callback already called");
  240. strongSelf->_completionCalled = YES;
  241. strongSelf->_authError = error;
  242. };
  243. }
  244. - (void)tearDown {
  245. OCMVerifyAll(_authState);
  246. OCMVerifyAll(_tokenResponse);
  247. OCMVerifyAll(_tokenRequest);
  248. OCMVerifyAll(_user);
  249. // OCMVerifyAll(_oidAuthorizationService);
  250. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  251. OCMVerifyAll(_presentingViewController);
  252. #elif TARGET_OS_OSX
  253. OCMVerifyAll(_presentingWindow);
  254. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  255. [_fakeMainBundle stopFaking];
  256. [super tearDown];
  257. }
  258. #pragma mark - Tests
  259. - (void)testShareInstance {
  260. GIDSignIn *signIn1 = GIDSignIn.sharedInstance;
  261. GIDSignIn *signIn2 = GIDSignIn.sharedInstance;
  262. XCTAssertTrue(signIn1 == signIn2, @"shared instance must be singleton");
  263. }
  264. - (void)testInitPrivate {
  265. GIDSignIn *signIn = [[GIDSignIn alloc] initPrivate];
  266. XCTAssertNotNil(signIn.configuration);
  267. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  268. XCTAssertNil(signIn.configuration.serverClientID);
  269. XCTAssertNil(signIn.configuration.hostedDomain);
  270. XCTAssertNil(signIn.configuration.openIDRealm);
  271. }
  272. - (void)testInitPrivate_noConfig {
  273. [_fakeMainBundle fakeWithClientID:nil
  274. serverClientID:nil
  275. hostedDomain:nil
  276. openIDRealm:nil];
  277. GIDSignIn *signIn = [[GIDSignIn alloc] initPrivate];
  278. XCTAssertNil(signIn.configuration);
  279. }
  280. - (void)testInitPrivate_fullConfig {
  281. [_fakeMainBundle fakeWithClientID:kClientId
  282. serverClientID:kServerClientId
  283. hostedDomain:kFakeHostedDomain
  284. openIDRealm:kOpenIDRealm];
  285. GIDSignIn *signIn = [[GIDSignIn alloc] initPrivate];
  286. XCTAssertNotNil(signIn.configuration);
  287. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  288. XCTAssertEqual(signIn.configuration.serverClientID, kServerClientId);
  289. XCTAssertEqual(signIn.configuration.hostedDomain, kFakeHostedDomain);
  290. XCTAssertEqual(signIn.configuration.openIDRealm, kOpenIDRealm);
  291. }
  292. - (void)testInitPrivate_invalidConfig {
  293. [_fakeMainBundle fakeWithClientID:@[ @"bad", @"config", @"values" ]
  294. serverClientID:nil
  295. hostedDomain:nil
  296. openIDRealm:nil];
  297. GIDSignIn *signIn = [[GIDSignIn alloc] initPrivate];
  298. XCTAssertNil(signIn.configuration);
  299. }
  300. - (void)testRestorePreviousSignInNoRefresh_hasPreviousUser {
  301. [[[_authorization stub] andReturn:_authState] authState];
  302. [[_authorization expect] setTokenRefreshDelegate:OCMOCK_ANY];
  303. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  304. OCMStub([_authState refreshToken]).andReturn(kRefreshToken);
  305. [[_authState expect] setStateChangeDelegate:OCMOCK_ANY];
  306. [_keychainHandler saveAuthState:_authState];
  307. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  308. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  309. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  310. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  311. // Mock generating a GIDConfiguration when initializing GIDGoogleUser.
  312. OIDAuthorizationResponse *authResponse =
  313. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:nil
  314. errorString:nil];
  315. OCMStub([_authState lastAuthorizationResponse]).andReturn(authResponse);
  316. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  317. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  318. OCMStub([_tokenResponse accessTokenExpirationDate]).andReturn(nil);
  319. GIDProfileData *fakeProfileData = [GIDProfileData testInstance];
  320. GIDProfileDataFetcherTestBlock testBlock = ^(GIDProfileDataFetcherFakeResponseProvider
  321. responseProvider) {
  322. responseProvider(fakeProfileData, nil);
  323. };
  324. _profileDataFetcher.testBlock = testBlock;
  325. [_signIn restorePreviousSignInNoRefresh];
  326. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  327. XCTAssertEqualObjects(_signIn.currentUser.profile, fakeProfileData);
  328. [idTokenDecoded stopMocking];
  329. }
  330. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  331. XCTAssertNil([_keychainHandler loadAuthState]);
  332. [_signIn restorePreviousSignInNoRefresh];
  333. XCTAssertNil(_signIn.currentUser);
  334. }
  335. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  336. [_keychainHandler saveAuthState:_authState];
  337. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  338. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  339. [_authState verify];
  340. XCTAssertFalse(_completionCalled, @"should not call delegate");
  341. XCTAssertNil(_authError, @"should have no error");
  342. }
  343. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  344. [_keychainHandler saveAuthState:_authState];
  345. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  346. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  347. [_authState verify];
  348. XCTAssertFalse(_completionCalled, @"should not call delegate");
  349. }
  350. - (void)testRestorePreviousSignInWhenSignedOut {
  351. [_keychainHandler saveAuthState:_authState];
  352. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  353. _completionCalled = NO;
  354. _authError = nil;
  355. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  356. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser *_Nullable user,
  357. NSError * _Nullable error) {
  358. [expectation fulfill];
  359. XCTAssertNotNil(error, @"error should not have been nil");
  360. XCTAssertEqual(error.domain,
  361. kGIDSignInErrorDomain,
  362. @"error domain should have been the sign-in error domain.");
  363. XCTAssertEqual(error.code,
  364. kGIDSignInErrorCodeHasNoAuthInKeychain,
  365. @"error code should have been the 'NoAuthInKeychain' error code.");
  366. }];
  367. [self waitForExpectationsWithTimeout:1 handler:nil];
  368. [_authState verify];
  369. }
  370. - (void)testOAuthLogin {
  371. [self OAuthLoginWithAddScopesFlow:NO
  372. authError:nil
  373. tokenError:nil
  374. emmPasscodeInfoRequired:NO
  375. keychainError:NO
  376. restoredSignIn:NO
  377. oldAccessToken:NO
  378. modalCancel:NO];
  379. }
  380. - (void)testOAuthLogin_RestoredSignIn {
  381. [self OAuthLoginWithAddScopesFlow:NO
  382. authError:nil
  383. tokenError:nil
  384. emmPasscodeInfoRequired:NO
  385. keychainError:NO
  386. restoredSignIn:YES
  387. oldAccessToken:NO
  388. modalCancel:NO];
  389. }
  390. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  391. [self OAuthLoginWithAddScopesFlow:NO
  392. authError:nil
  393. tokenError:nil
  394. emmPasscodeInfoRequired:NO
  395. keychainError:NO
  396. restoredSignIn:YES
  397. oldAccessToken:YES
  398. modalCancel:NO];
  399. }
  400. - (void)testOAuthLogin_ConsentCanceled {
  401. [self OAuthLoginWithAddScopesFlow:NO
  402. authError:@"access_denied"
  403. tokenError:nil
  404. emmPasscodeInfoRequired:NO
  405. keychainError:NO
  406. restoredSignIn:NO
  407. oldAccessToken:NO
  408. modalCancel:NO];
  409. [self waitForExpectationsWithTimeout:1 handler:nil];
  410. XCTAssertTrue(_completionCalled, @"should call delegate");
  411. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  412. }
  413. - (void)testOAuthLogin_ModalCanceled {
  414. [self OAuthLoginWithAddScopesFlow:NO
  415. authError:nil
  416. tokenError:nil
  417. emmPasscodeInfoRequired:NO
  418. keychainError:NO
  419. restoredSignIn:NO
  420. oldAccessToken:NO
  421. modalCancel:YES];
  422. [self waitForExpectationsWithTimeout:1 handler:nil];
  423. XCTAssertTrue(_completionCalled, @"should call delegate");
  424. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  425. }
  426. - (void)testOAuthLogin_KeychainError {
  427. [self OAuthLoginWithAddScopesFlow:NO
  428. authError:nil
  429. tokenError:nil
  430. emmPasscodeInfoRequired:NO
  431. keychainError:YES
  432. restoredSignIn:NO
  433. oldAccessToken:NO
  434. modalCancel:NO];
  435. [self waitForExpectationsWithTimeout:1 handler:nil];
  436. XCTAssertTrue(_completionCalled, @"should call delegate");
  437. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  438. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  439. }
  440. - (void)testSignOut {
  441. XCTAssert([_keychainHandler saveAuthState:_authState]);
  442. // Sign in a user so that we can then sign them out.
  443. [self OAuthLoginWithAddScopesFlow:NO
  444. authError:nil
  445. tokenError:nil
  446. emmPasscodeInfoRequired:NO
  447. keychainError:NO
  448. restoredSignIn:YES
  449. oldAccessToken:NO
  450. modalCancel:NO];
  451. XCTAssertNotNil(_signIn.currentUser);
  452. XCTAssertNotNil([_keychainHandler loadAuthState]);
  453. [_signIn signOut];
  454. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  455. XCTAssertNil([_keychainHandler loadAuthState]);
  456. }
  457. - (void)testNotHandleWrongPath {
  458. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  459. XCTAssertFalse(_completionCalled, @"should not call delegate");
  460. }
  461. #pragma mark - Tests - disconnectWithCallback:
  462. // Verifies disconnect calls callback with no errors if access token is present.
  463. - (void)testDisconnect_accessTokenIsPresent {
  464. [_keychainHandler saveAuthState:_authState];
  465. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  466. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  467. XCTestExpectation *fetcherExpectation =
  468. [self expectationWithDescription:@"testBlock is invoked."];
  469. GIDHTTPFetcherTestBlock testBlock =
  470. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  471. [self verifyRevokeRequest:request withToken:kAccessToken];
  472. NSData *data = [[NSData alloc] init];
  473. responseProvider(data, nil);
  474. [fetcherExpectation fulfill];
  475. };
  476. [_httpFetcher setTestBlock:testBlock];
  477. XCTestExpectation *completionExpectation =
  478. [self expectationWithDescription:@"Callback called with nil error"];
  479. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  480. XCTAssertNil(error);
  481. [completionExpectation fulfill];
  482. }];
  483. [self waitForExpectationsWithTimeout:1 handler:nil];
  484. XCTAssertNil([_keychainHandler loadAuthState]);
  485. }
  486. // Verifies disconnect if access token is present.
  487. - (void)testDisconnectNoCallback_accessTokenIsPresent {
  488. [_keychainHandler saveAuthState:_authState];
  489. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  490. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  491. XCTestExpectation *fetcherExpectation =
  492. [self expectationWithDescription:@"testBlock is invoked."];
  493. GIDHTTPFetcherTestBlock testBlock =
  494. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  495. [self verifyRevokeRequest:request withToken:kAccessToken];
  496. NSData *data = [[NSData alloc] init];
  497. responseProvider(data, nil);
  498. [fetcherExpectation fulfill];
  499. };
  500. [_httpFetcher setTestBlock:testBlock];
  501. [_signIn disconnectWithCompletion:nil];
  502. [self waitForExpectationsWithTimeout:1 handler:nil];
  503. XCTAssertNil([_keychainHandler loadAuthState]);
  504. }
  505. // Verifies disconnect calls callback with no errors if refresh token is present.
  506. - (void)testDisconnect_refreshTokenIsPresent {
  507. [_keychainHandler saveAuthState:_authState];
  508. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  509. OCMStub([_tokenResponse accessToken]).andReturn(nil);
  510. OCMStub([_tokenResponse refreshToken]).andReturn(kRefreshToken);
  511. XCTestExpectation *fetcherExpectation =
  512. [self expectationWithDescription:@"testBlock is invoked."];
  513. GIDHTTPFetcherTestBlock testBlock =
  514. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  515. [self verifyRevokeRequest:request withToken:kRefreshToken];
  516. NSData *data = [[NSData alloc] init];
  517. responseProvider(data, nil);
  518. [fetcherExpectation fulfill];
  519. };
  520. [_httpFetcher setTestBlock:testBlock];
  521. XCTestExpectation *completionExpectation =
  522. [self expectationWithDescription:@"Callback called with nil error"];
  523. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  524. XCTAssertNil(error);
  525. [completionExpectation fulfill];
  526. }];
  527. [self waitForExpectationsWithTimeout:1 handler:nil];
  528. XCTAssertNil([_keychainHandler loadAuthState]);
  529. }
  530. // Verifies disconnect errors are passed along to the callback.
  531. - (void)testDisconnect_errors {
  532. [_keychainHandler saveAuthState:_authState];
  533. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  534. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  535. XCTestExpectation *fetcherExpectation =
  536. [self expectationWithDescription:@"testBlock is invoked."];
  537. GIDHTTPFetcherTestBlock testBlock =
  538. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  539. [self verifyRevokeRequest:request withToken:kAccessToken];
  540. NSError *error = [self error];
  541. responseProvider(nil, error);
  542. [fetcherExpectation fulfill];
  543. };
  544. [_httpFetcher setTestBlock:testBlock];
  545. XCTestExpectation *completionExpectation =
  546. [self expectationWithDescription:@"Callback called with an error"];
  547. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  548. XCTAssertNotNil(error);
  549. [completionExpectation fulfill];
  550. }];
  551. [self waitForExpectationsWithTimeout:1 handler:nil];
  552. XCTAssertNotNil([_keychainHandler loadAuthState]);
  553. }
  554. // Verifies disconnect with errors
  555. - (void)testDisconnectNoCallback_errors {
  556. [_keychainHandler saveAuthState:_authState];
  557. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  558. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  559. XCTestExpectation *fetcherExpectation =
  560. [self expectationWithDescription:@"testBlock is invoked."];
  561. GIDHTTPFetcherTestBlock testBlock =
  562. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  563. [self verifyRevokeRequest:request withToken:kAccessToken];
  564. NSError *error = [self error];
  565. responseProvider(nil, error);
  566. [fetcherExpectation fulfill];
  567. };
  568. [_httpFetcher setTestBlock:testBlock];
  569. [_signIn disconnectWithCompletion:nil];
  570. [self waitForExpectationsWithTimeout:1 handler:nil];
  571. XCTAssertNotNil([_keychainHandler loadAuthState]);
  572. }
  573. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  574. - (void)testDisconnect_noTokens {
  575. [_keychainHandler saveAuthState:_authState];
  576. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  577. OCMStub([_tokenResponse accessToken]).andReturn(nil);
  578. OCMStub([_tokenResponse refreshToken]).andReturn(nil);
  579. GIDHTTPFetcherTestBlock testBlock =
  580. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  581. XCTFail(@"_httpFetcher should not be invoked.");
  582. };
  583. [_httpFetcher setTestBlock:testBlock];
  584. XCTestExpectation *expectation =
  585. [self expectationWithDescription:@"Callback called with nil error"];
  586. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  587. XCTAssertNil(error);
  588. [expectation fulfill];
  589. }];
  590. [self waitForExpectationsWithTimeout:1 handler:nil];
  591. XCTAssertNil([_keychainHandler loadAuthState]);
  592. }
  593. // Verifies disconnect clears keychain if no tokens are present.
  594. - (void)testDisconnectNoCallback_noTokens {
  595. [_keychainHandler saveAuthState:_authState];
  596. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  597. OCMStub([_tokenResponse accessToken]).andReturn(nil);
  598. OCMStub([_tokenResponse refreshToken]).andReturn(nil);
  599. GIDHTTPFetcherTestBlock testBlock =
  600. ^(NSURLRequest *request, GIDHTTPFetcherFakeResponseProviderBlock responseProvider) {
  601. XCTFail(@"_httpFetcher should not be invoked.");
  602. };
  603. [_httpFetcher setTestBlock:testBlock];
  604. [_signIn disconnectWithCompletion:nil];
  605. XCTAssertNil([_keychainHandler loadAuthState]);
  606. }
  607. - (void)testPresentingViewControllerException {
  608. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  609. _presentingViewController = nil;
  610. #elif TARGET_OS_OSX
  611. _presentingWindow = nil;
  612. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  613. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  614. XCTAssertThrows([_signIn signInWithPresentingViewController:_presentingViewController
  615. #elif TARGET_OS_OSX
  616. XCTAssertThrows([_signIn signInWithPresentingWindow:_presentingWindow
  617. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  618. hint:nil
  619. completion:_completion]);
  620. }
  621. - (void)testClientIDMissingException {
  622. #pragma GCC diagnostic push
  623. #pragma GCC diagnostic ignored "-Wnonnull"
  624. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  625. #pragma GCC diagnostic pop
  626. BOOL threw = NO;
  627. @try {
  628. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  629. [_signIn signInWithPresentingViewController:_presentingViewController
  630. #elif TARGET_OS_OSX
  631. [_signIn signInWithPresentingWindow:_presentingWindow
  632. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  633. completion:nil];
  634. } @catch (NSException *exception) {
  635. threw = YES;
  636. XCTAssertEqualObjects(exception.description,
  637. @"You must specify |clientID| in |GIDConfiguration|");
  638. } @finally {
  639. }
  640. XCTAssert(threw);
  641. }
  642. - (void)testSchemesNotSupportedException {
  643. [_fakeMainBundle fakeMissingAllSchemes];
  644. BOOL threw = NO;
  645. @try {
  646. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  647. [_signIn signInWithPresentingViewController:_presentingViewController
  648. #elif TARGET_OS_OSX
  649. [_signIn signInWithPresentingWindow:_presentingWindow
  650. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  651. hint:nil
  652. completion:_completion];
  653. } @catch (NSException *exception) {
  654. threw = YES;
  655. XCTAssertEqualObjects(exception.description,
  656. @"Your app is missing support for the following URL schemes: "
  657. "fakeclientid");
  658. } @finally {
  659. }
  660. XCTAssert(threw);
  661. }
  662. #pragma mark - Restarting Authentication Tests
  663. // Verifies that URL is not handled if there is no pending sign-in
  664. - (void)testRequiringPendingSignIn {
  665. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  666. XCTAssertFalse(result);
  667. }
  668. #pragma mark - EMM tests
  669. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  670. - (void)testAuthEndpointEMMError {
  671. if (!_isEligibleForEMM) {
  672. return;
  673. }
  674. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  675. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  676. __block void (^completion)(void);
  677. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  678. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  679. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  680. [self OAuthLoginWithAddScopesFlow:NO
  681. authError:callbackParams[@"error"]
  682. tokenError:nil
  683. emmPasscodeInfoRequired:NO
  684. keychainError:NO
  685. restoredSignIn:NO
  686. oldAccessToken:NO
  687. modalCancel:NO];
  688. [mockEMMErrorHandler verify];
  689. [mockEMMErrorHandler stopMocking];
  690. completion();
  691. [self waitForExpectationsWithTimeout:1 handler:nil];
  692. XCTAssertTrue(_completionCalled, @"should call delegate");
  693. XCTAssertNotNil(_authError, @"should have error");
  694. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  695. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  696. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  697. }
  698. - (void)testTokenEndpointEMMError {
  699. if (!_isEligibleForEMM) {
  700. return;
  701. }
  702. __block void (^completion)(NSError *);
  703. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  704. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  705. code:12345
  706. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  707. id emmSupport = OCMStrictClassMock([GIDEMMSupport class]);
  708. [[emmSupport expect] handleTokenFetchEMMError:emmError
  709. completion:SAVE_TO_ARG_BLOCK(completion)];
  710. [self OAuthLoginWithAddScopesFlow:NO
  711. authError:nil
  712. tokenError:emmError
  713. emmPasscodeInfoRequired:NO
  714. keychainError:NO
  715. restoredSignIn:NO
  716. oldAccessToken:NO
  717. modalCancel:NO];
  718. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  719. code:kGIDSignInErrorCodeEMM
  720. userInfo:emmError.userInfo];
  721. completion(handledError);
  722. [self waitForExpectationsWithTimeout:1 handler:nil];
  723. [emmSupport verify];
  724. XCTAssertTrue(_completionCalled, @"should call delegate");
  725. XCTAssertNotNil(_authError, @"should have error");
  726. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  727. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  728. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  729. }
  730. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  731. #pragma mark - Helpers
  732. - (NSError *)error {
  733. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  734. }
  735. - (void)verifyRevokeRequest:(NSURLRequest *)request withToken:(NSString *)token {
  736. NSURL *url = request.URL;
  737. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  738. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  739. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  740. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  741. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  742. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  743. @"SDK version logging parameter should match");
  744. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  745. @"Environment logging parameter should match");
  746. NSData *body = request.HTTPBody;
  747. NSString* bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
  748. NSArray<NSString *> *strings = [bodyString componentsSeparatedByString:@"="];
  749. XCTAssertEqualObjects(strings[1], token);
  750. }
  751. // The authorization flow with parameters to control which branches to take.
  752. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  753. authError:(NSString *)authError
  754. tokenError:(NSError *)tokenError
  755. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  756. keychainError:(BOOL)keychainError
  757. restoredSignIn:(BOOL)restoredSignIn
  758. oldAccessToken:(BOOL)oldAccessToken
  759. modalCancel:(BOOL)modalCancel {
  760. if (restoredSignIn) {
  761. // clearAndAuthenticateWithOptions
  762. [_keychainHandler saveAuthState:_authState];
  763. BOOL isAuthorized = restoredSignIn ? YES : NO;
  764. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  765. }
  766. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  767. @{ @"emm_passcode_info_required" : @"1" } : nil;
  768. OIDAuthorizationResponse *authResponse =
  769. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  770. errorString:authError];
  771. OIDTokenResponse *tokenResponse =
  772. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  773. accessToken:restoredSignIn ? kAccessToken : nil
  774. expiresIn:oldAccessToken ? @(300) : nil
  775. refreshToken:kRefreshToken
  776. tokenRequest:nil];
  777. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  778. initWithConfiguration:authResponse.request.configuration
  779. grantType:OIDGrantTypeRefreshToken
  780. authorizationCode:nil
  781. redirectURL:nil
  782. clientID:authResponse.request.clientID
  783. clientSecret:authResponse.request.clientSecret
  784. scope:nil
  785. refreshToken:kRefreshToken
  786. codeVerifier:nil
  787. additionalParameters:tokenResponse.request.additionalParameters];
  788. // Set the response for the auth endpoint.
  789. GIDAuthorizationFlowProcessorTestBlock authorizationFlowTestBlock;
  790. if (modalCancel) {
  791. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  792. code:OIDErrorCodeUserCanceledAuthorizationFlow
  793. userInfo:nil];
  794. authorizationFlowTestBlock =
  795. ^(GIDAuthorizationFlowProcessorFakeResponseProviderBlock responseProvider) {
  796. responseProvider(nil, error);
  797. };
  798. } else {
  799. authorizationFlowTestBlock =
  800. ^(GIDAuthorizationFlowProcessorFakeResponseProviderBlock responseProvider) {
  801. responseProvider(authResponse, nil);
  802. };
  803. }
  804. _authorizationFlowProcessor.testBlock = authorizationFlowTestBlock;
  805. // Set the response for `GIDProfileDataFetcher`.
  806. GIDProfileDataFetcherTestBlock profileDataFetcherTestBlock =
  807. ^(GIDProfileDataFetcherFakeResponseProvider responseProvider) {
  808. GIDProfileData *profileData = [GIDProfileData testInstance];
  809. responseProvider(profileData, nil);
  810. };
  811. _profileDataFetcher.testBlock = profileDataFetcherTestBlock;
  812. if (restoredSignIn) {
  813. // Mock `maybeFetchToken:` method in `restorePreviousSignIn:` flow.
  814. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  815. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  816. if (oldAccessToken) {
  817. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  818. // Corresponds to EMM support
  819. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  820. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  821. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  822. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  823. [[[_authState expect] andReturn:tokenRequest]
  824. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  825. }
  826. } else {
  827. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  828. GIDSignInCompletion completion = ^(GIDSignInResult *_Nullable signInResult,
  829. NSError * _Nullable error) {
  830. [expectation fulfill];
  831. if (signInResult) {
  832. XCTAssertEqualObjects(signInResult.serverAuthCode, kServerAuthCode);
  833. } else {
  834. XCTAssertNotNil(error, @"Should have an error if the signInResult is nil");
  835. }
  836. XCTAssertFalse(self->_completionCalled, @"callback already called");
  837. self->_completionCalled = YES;
  838. self->_authError = error;
  839. };
  840. if (addScopesFlow) {
  841. [_signIn addScopes:@[kNewScope]
  842. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  843. presentingViewController:_presentingViewController
  844. #elif TARGET_OS_OSX
  845. presentingWindow:_presentingWindow
  846. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  847. completion:completion];
  848. } else {
  849. // Mock `maybeFetchToken:` method in Sign in flow.
  850. if (!(authError || modalCancel)) {
  851. [[[_authState expect] andReturn:nil] lastTokenResponse];
  852. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  853. // Corresponds to EMM support
  854. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  855. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  856. [[[_authState expect] andReturn:nil] lastTokenResponse];
  857. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  858. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  859. }
  860. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  861. [_signIn signInWithPresentingViewController:_presentingViewController
  862. #elif TARGET_OS_OSX
  863. [_signIn signInWithPresentingWindow:_presentingWindow
  864. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  865. hint:nil
  866. completion:completion];
  867. }
  868. if (authError || modalCancel) {
  869. return;
  870. }
  871. [_authState verify];
  872. }
  873. if (restoredSignIn && oldAccessToken) {
  874. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  875. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  876. NSError * _Nullable error) {
  877. [expectation fulfill];
  878. XCTAssertNil(error, @"should have no error");
  879. }];
  880. }
  881. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  882. XCTAssertNotNil(_savedTokenCallback);
  883. // OIDTokenCallback
  884. if (tokenError) {
  885. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  886. } else {
  887. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  888. }
  889. }
  890. if (tokenError) {
  891. _savedTokenCallback(nil, tokenError);
  892. return;
  893. }
  894. // SaveAuthCallback
  895. __block OIDAuthState *authState;
  896. __block OIDTokenResponse *updatedTokenResponse;
  897. __block OIDAuthorizationResponse *updatedAuthorizationResponse;
  898. __block GIDProfileData *profileData;
  899. if (keychainError) {
  900. _keychainHandler.failToSave = YES;
  901. } else {
  902. if (addScopesFlow) {
  903. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  904. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  905. [[_user expect] updateWithTokenResponse:SAVE_TO_ARG_BLOCK(updatedTokenResponse)
  906. authorizationResponse:SAVE_TO_ARG_BLOCK(updatedAuthorizationResponse)
  907. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  908. } else {
  909. [[[_user stub] andReturn:_user] alloc];
  910. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  911. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  912. }
  913. }
  914. // CompletionCallback - mock server auth code parsing
  915. if (!keychainError) {
  916. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  917. }
  918. if (restoredSignIn && !oldAccessToken) {
  919. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  920. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  921. NSError * _Nullable error) {
  922. [expectation fulfill];
  923. XCTAssertNil(error, @"should have no error");
  924. }];
  925. } else {
  926. // Simulate token endpoint response.
  927. _savedTokenCallback(tokenResponse, nil);
  928. }
  929. if (keychainError) {
  930. return;
  931. }
  932. [self waitForExpectationsWithTimeout:1 handler:nil];
  933. [_authState verify];
  934. if (addScopesFlow) {
  935. XCTAssertNotNil(updatedTokenResponse);
  936. XCTAssertNotNil(updatedAuthorizationResponse);
  937. } else {
  938. XCTAssertNotNil(authState);
  939. }
  940. // Check fat ID token decoding
  941. XCTAssertEqualObjects(profileData, [GIDProfileData testInstance]);
  942. // If attempt to authenticate again, will reuse existing auth object.
  943. _completionCalled = NO;
  944. _authError = nil;
  945. __block GIDGoogleUserCompletion completion;
  946. [[_user expect] refreshTokensIfNeededWithCompletion:SAVE_TO_ARG_BLOCK(completion)];
  947. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  948. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  949. NSError * _Nullable error) {
  950. [expectation fulfill];
  951. XCTAssertNil(error, @"should have no error");
  952. }];
  953. completion(_user, nil);
  954. [self waitForExpectationsWithTimeout:1 handler:nil];
  955. }
  956. @end