GIDSignInTest.m 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164
  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 <SafariServices/SafariServices.h>
  15. #import <UIKit/UIKit.h>
  16. #import <XCTest/XCTest.h>
  17. // Test module imports
  18. @import GoogleSignIn;
  19. #import "GoogleSignIn/Sources/GIDGoogleUser_Private.h"
  20. #import "GoogleSignIn/Sources/GIDSignInInternalOptions.h"
  21. #import "GoogleSignIn/Sources/GIDSignIn_Private.h"
  22. #import "GoogleSignIn/Sources/GIDAuthentication_Private.h"
  23. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  24. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
  25. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
  26. #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.h"
  27. #import "GoogleSignIn/Tests/Unit/OIDAuthorizationResponse+Testing.h"
  28. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  29. #ifdef SWIFT_PACKAGE
  30. @import AppAuth;
  31. @import GTMAppAuth;
  32. @import GTMSessionFetcherCore;
  33. @import OCMock;
  34. #else
  35. #import <AppAuth/OIDAuthState.h>
  36. #import <AppAuth/OIDAuthorizationRequest.h>
  37. #import <AppAuth/OIDAuthorizationResponse.h>
  38. #import <AppAuth/OIDAuthorizationService.h>
  39. #import <AppAuth/OIDError.h>
  40. #import <AppAuth/OIDGrantTypes.h>
  41. #import <AppAuth/OIDTokenRequest.h>
  42. #import <AppAuth/OIDTokenResponse.h>
  43. #import <AppAuth/OIDURLQueryComponent.h>
  44. #import <AppAuth/OIDAuthorizationService+IOS.h>
  45. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization+Keychain.h>
  46. #import <GTMAppAuth/GTMAppAuthFetcherAuthorization.h>
  47. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  48. #import <OCMock/OCMock.h>
  49. #endif
  50. // Create a BLOCK to store the actual address for arg in param.
  51. #define SAVE_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  52. param = arg;\
  53. return YES;\
  54. }]
  55. #define COPY_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  56. param = [arg copy];\
  57. return YES;\
  58. }]
  59. static NSString * const kFakeGaiaID = @"123456789";
  60. static NSString * const kFakeIDToken = @"FakeIDToken";
  61. static NSString * const kClientId = @"FakeClientID";
  62. static NSString * const kDotReversedClientId = @"FakeClientID";
  63. static NSString * const kClientId2 = @"FakeClientID2";
  64. static NSString * const kAppBundleId = @"FakeBundleID";
  65. static NSString * const kLanguage = @"FakeLanguage";
  66. static NSString * const kScope = @"FakeScope";
  67. static NSString * const kScope2 = @"FakeScope2";
  68. static NSString * const kAuthCode = @"FakeAuthCode";
  69. static NSString * const kPassword = @"FakePassword";
  70. static NSString * const kFakeKeychainName = @"FakeKeychainName";
  71. static NSString * const kUserEmail = @"FakeUserEmail";
  72. static NSString * const kVerifier = @"FakeVerifier";
  73. static NSString * const kOpenIDRealm = @"FakeRealm";
  74. static NSString * const kFakeHostedDomain = @"fakehosteddomain.com";
  75. static NSString * const kFakeUserName = @"fake username";
  76. static NSString * const kFakeUserGivenName = @"fake";
  77. static NSString * const kFakeUserFamilyName = @"username";
  78. static NSString * const kFakeUserPictureURL = @"fake_user_picture_url";
  79. static NSString * const kContinueURL = @"com.google.UnitTests:/oauth2callback";
  80. static NSString * const kContinueURLWithClientID = @"FakeClientID:/oauth2callback";
  81. static NSString * const kWrongSchemeURL = @"wrong.app:/oauth2callback";
  82. static NSString * const kWrongPathURL = @"com.google.UnitTests:/wrong_path";
  83. static NSString * const kEMMRestartAuthURL =
  84. @"com.google.UnitTests:///emmcallback?action=restart_auth";
  85. static NSString * const kEMMWrongPathURL =
  86. @"com.google.UnitTests:///unknowcallback?action=restart_auth";
  87. static NSString * const kEMMWrongActionURL =
  88. @"com.google.UnitTests:///emmcallback?action=unrecognized";
  89. static NSString * const kDevicePolicyAppBundleID = @"com.google.DevicePolicy";
  90. static NSString * const kAppHasRunBeforeKey = @"GPP_AppHasRunBefore";
  91. static NSString * const kFingerprintKeychainName = @"fingerprint";
  92. static NSString * const kVerifierKeychainName = @"verifier";
  93. static NSString * const kVerifierKey = @"verifier";
  94. static NSString * const kOpenIDRealmKey = @"openid.realm";
  95. static NSString * const kSavedKeychainServiceName = @"saved-keychain";
  96. static NSString * const kKeychainAccountName = @"GooglePlus";
  97. static NSString * const kUserNameKey = @"name";
  98. static NSString * const kUserGivenNameKey = @"givenName";
  99. static NSString * const kUserFamilyNameKey = @"familyName";
  100. static NSString * const kUserImageKey = @"picture";
  101. static NSString * const kAppName = @"UnitTests";
  102. static NSString * const kUserIDKey = @"userID";
  103. static NSString * const kHostedDomainKey = @"hostedDomain";
  104. static NSString * const kIDTokenExpirationKey = @"idTokenExp";
  105. static NSString * const kScopeKey = @"scope";
  106. // Basic profile (Fat ID Token / userinfo endpoint) keys
  107. static NSString *const kBasicProfilePictureKey = @"picture";
  108. static NSString *const kBasicProfileNameKey = @"name";
  109. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  110. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  111. static NSString * const kCustomKeychainName = @"CUSTOM_KEYCHAIN_NAME";
  112. static NSString * const kAddActivity = @"http://schemas.google.com/AddActivity";
  113. static NSString * const kErrorDomain = @"ERROR_DOMAIN";
  114. static NSInteger const kErrorCode = 212;
  115. static NSString *const kDriveScope = @"https://www.googleapis.com/auth/drive";
  116. static NSString *const kTokenURL = @"https://oauth2.googleapis.com/token";
  117. static NSString *const kFakeURL = @"http://foo.com";
  118. static NSString *const kEMMSupport = @"1";
  119. /// Unique pointer value for KVO tests.
  120. static void *kTestObserverContext = &kTestObserverContext;
  121. // This category is used to allow the test to swizzle a private method.
  122. @interface UIViewController (Testing)
  123. // This private method provides access to the window. It's declared here to avoid a warning about
  124. // an unrecognized selector in the test.
  125. - (UIWindow *)_window;
  126. @end
  127. // This class extension exposes GIDSignIn methods to our tests.
  128. @interface GIDSignIn ()
  129. // Exposing private method so we can call it to disambiguate between interactive and non-interactive
  130. // sign-in attempts for the purposes of testing the GIDSignInUIDelegate (which should not be
  131. // called in the case of a non-interactive sign in).
  132. - (void)authenticateMaybeInteractively:(BOOL)interactive withParams:(NSDictionary *)params;
  133. - (BOOL)assertValidPresentingViewContoller;
  134. @end
  135. @interface GIDSignInTest : XCTestCase {
  136. @private
  137. // Whether or not the OS version is eligible for EMM.
  138. BOOL _isEligibleForEMM;
  139. // Mock |OIDAuthState|.
  140. id _authState;
  141. // Mock |OIDTokenResponse|.
  142. id _tokenResponse;
  143. // Mock |OIDTokenRequest|.
  144. id _tokenRequest;
  145. // Mock |GTMAppAuthFetcherAuthorization|.
  146. id _authorization;
  147. // Mock |UIViewController|.
  148. id _presentingViewController;
  149. // Mock for |GIDGoogleUser|.
  150. id _user;
  151. // Mock for |GIDAuthentication|.
  152. id _authentication;
  153. // Mock for |OIDAuthorizationService|
  154. id _oidAuthorizationService;
  155. // Parameter saved from delegate call.
  156. NSError *_authError;
  157. // Whether callback block has been called.
  158. BOOL _callbackCalled;
  159. // Fake fetcher service to emulate network requests.
  160. GIDFakeFetcherService *_fetcherService;
  161. // Fake [NSBundle mainBundle];
  162. GIDFakeMainBundle *_fakeMainBundle;
  163. // Whether |saveParamsToKeychainForName:authentication:| has been called.
  164. BOOL _keychainSaved;
  165. // Whether |removeAuthFromKeychainForName:| has been called.
  166. BOOL _keychainRemoved;
  167. // The |GIDSignIn| object being tested.
  168. GIDSignIn *_signIn;
  169. // The configuration to be used when testing |GIDSignIn|.
  170. GIDConfiguration *_configuration;
  171. // The login hint to be used when testing |GIDSignIn|.
  172. NSString *_hint;
  173. // The callback to be used when testing |GIDSignIn|.
  174. GIDSignInCallback _callback;
  175. // The saved authorization request.
  176. OIDAuthorizationRequest *_savedAuthorizationRequest;
  177. // The saved presentingViewController from the authorization request.
  178. UIViewController *_savedPresentingViewController;
  179. // The saved authorization callback.
  180. OIDAuthorizationCallback _savedAuthorizationCallback;
  181. // The saved token request.
  182. OIDTokenRequest *_savedTokenRequest;
  183. // The saved token request callback.
  184. OIDTokenCallback _savedTokenCallback;
  185. // Set of all |GIDSignIn| key paths which were observed to change.
  186. NSMutableSet *_changedKeyPaths;
  187. // Status returned by saveAuthorization:toKeychainForName:
  188. BOOL _saveAuthorizationReturnValue;
  189. }
  190. @end
  191. @implementation GIDSignInTest
  192. #pragma mark - Lifecycle
  193. - (void)setUp {
  194. [super setUp];
  195. _isEligibleForEMM = [UIDevice currentDevice].systemVersion.integerValue >= 9;
  196. _saveAuthorizationReturnValue = YES;
  197. // States
  198. _callbackCalled = NO;
  199. _keychainSaved = NO;
  200. _keychainRemoved = NO;
  201. _changedKeyPaths = [[NSMutableSet alloc] init];
  202. // Mocks
  203. _presentingViewController = OCMStrictClassMock([UIViewController class]);
  204. _authState = OCMStrictClassMock([OIDAuthState class]);
  205. OCMStub([_authState alloc]).andReturn(_authState);
  206. OCMStub([_authState initWithAuthorizationResponse:OCMOCK_ANY]).andReturn(_authState);
  207. _tokenResponse = OCMStrictClassMock([OIDTokenResponse class]);
  208. _tokenRequest = OCMStrictClassMock([OIDTokenRequest class]);
  209. _authorization = OCMStrictClassMock([GTMAppAuthFetcherAuthorization class]);
  210. OCMStub([_authorization authorizationFromKeychainForName:OCMOCK_ANY]).andReturn(_authorization);
  211. OCMStub([_authorization alloc]).andReturn(_authorization);
  212. OCMStub([_authorization initWithAuthState:OCMOCK_ANY]).andReturn(_authorization);
  213. OCMStub([_authorization saveAuthorization:OCMOCK_ANY toKeychainForName:OCMOCK_ANY])
  214. .andDo(^(NSInvocation *invocation) {
  215. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  216. [invocation setReturnValue:&self->_saveAuthorizationReturnValue];
  217. });
  218. OCMStub([_authorization removeAuthorizationFromKeychainForName:OCMOCK_ANY])
  219. .andDo(^(NSInvocation *invocation) {
  220. self->_keychainRemoved = YES;
  221. });
  222. _user = OCMStrictClassMock([GIDGoogleUser class]);
  223. _authentication = OCMStrictClassMock([GIDAuthentication class]);
  224. _oidAuthorizationService = OCMStrictClassMock([OIDAuthorizationService class]);
  225. OCMStub([_oidAuthorizationService
  226. presentAuthorizationRequest:SAVE_TO_ARG_BLOCK(self->_savedAuthorizationRequest)
  227. presentingViewController:SAVE_TO_ARG_BLOCK(self->_savedPresentingViewController)
  228. callback:COPY_TO_ARG_BLOCK(self->_savedAuthorizationCallback)]);
  229. OCMStub([self->_oidAuthorizationService
  230. performTokenRequest:SAVE_TO_ARG_BLOCK(self->_savedTokenRequest)
  231. callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
  232. // Fakes
  233. _fetcherService = [[GIDFakeFetcherService alloc] init];
  234. _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
  235. [_fakeMainBundle startFakingWithBundleId:kAppBundleId clientId:kClientId];
  236. [_fakeMainBundle fakeAllSchemesSupported];
  237. // Object under test
  238. [[NSUserDefaults standardUserDefaults] setBool:YES
  239. forKey:kAppHasRunBeforeKey];
  240. _signIn = [[GIDSignIn alloc] initPrivate];
  241. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId];
  242. _hint = nil;
  243. __weak GIDSignInTest *weakSelf = self;
  244. _callback = ^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  245. GIDSignInTest *strongSelf = weakSelf;
  246. if (!user) {
  247. XCTAssertNotNil(error, @"should have an error if user is nil");
  248. }
  249. XCTAssertFalse(strongSelf->_callbackCalled, @"callback already called");
  250. strongSelf->_callbackCalled = YES;
  251. strongSelf->_authError = error;
  252. };
  253. [_signIn addObserver:self
  254. forKeyPath:NSStringFromSelector(@selector(currentUser))
  255. options:0
  256. context:kTestObserverContext];
  257. }
  258. - (void)tearDown {
  259. OCMVerifyAll(_authState);
  260. OCMVerifyAll(_tokenResponse);
  261. OCMVerifyAll(_tokenRequest);
  262. OCMVerifyAll(_authorization);
  263. OCMVerifyAll(_presentingViewController);
  264. OCMVerifyAll(_user);
  265. OCMVerifyAll(_authentication);
  266. OCMVerifyAll(_oidAuthorizationService);
  267. [_fakeMainBundle stopFaking];
  268. [super tearDown];
  269. [_signIn removeObserver:self
  270. forKeyPath:NSStringFromSelector(@selector(currentUser))
  271. context:kTestObserverContext];
  272. }
  273. #pragma mark - Tests
  274. - (void)testShareInstance {
  275. GIDSignIn *signIn1 = GIDSignIn.sharedInstance;
  276. GIDSignIn *signIn2 = GIDSignIn.sharedInstance;
  277. XCTAssertTrue(signIn1 == signIn2, @"shared instance must be singleton");
  278. }
  279. - (void)testRestorePreviousSignInNoRefresh_hasPreviousUser {
  280. [[[_authorization expect] andReturn:_authState] authState];
  281. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  282. OCMStub([_tokenResponse scope]).andReturn(nil);
  283. OCMStub([_tokenResponse additionalParameters]).andReturn(nil);
  284. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  285. OCMStub([_tokenResponse request]).andReturn(_tokenRequest);
  286. OCMStub([_tokenRequest additionalParameters]).andReturn(nil);
  287. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  288. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  289. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  290. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  291. [_signIn restorePreviousSignInNoRefresh];
  292. [_authorization verify];
  293. [_authState verify];
  294. [_tokenResponse verify];
  295. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  296. }
  297. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  298. [[[_authorization expect] andReturn:nil] authState];
  299. [_signIn restorePreviousSignInNoRefresh];
  300. [_authorization verify];
  301. XCTAssertNil(_signIn.currentUser);
  302. }
  303. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  304. [[[_authorization expect] andReturn:_authState] authState];
  305. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  306. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  307. [_authorization verify];
  308. [_authState verify];
  309. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  310. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  311. XCTAssertNil(_authError, @"should have no error");
  312. }
  313. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  314. [[[_authorization expect] andReturn:_authState] authState];
  315. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  316. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  317. [_authorization verify];
  318. [_authState verify];
  319. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  320. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  321. }
  322. - (void)testRestorePreviousSignInWhenSignedOut {
  323. [[[_authorization expect] andReturn:_authState] authState];
  324. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  325. _callbackCalled = NO;
  326. _authError = nil;
  327. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  328. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  329. NSError * _Nullable error) {
  330. [expectation fulfill];
  331. XCTAssertNotNil(error, @"error should not have been nil");
  332. XCTAssertEqual(error.domain,
  333. kGIDSignInErrorDomain,
  334. @"error domain should have been the sign-in error domain.");
  335. XCTAssertEqual(error.code,
  336. kGIDSignInErrorCodeHasNoAuthInKeychain,
  337. @"error code should have been the 'NoAuthInKeychain' error code.");
  338. }];
  339. [self waitForExpectationsWithTimeout:1 handler:nil];
  340. [_authorization verify];
  341. [_authState verify];
  342. }
  343. - (void)testOAuthLogin {
  344. [self OAuthLoginWithOptions:nil
  345. authError:nil
  346. tokenError:nil
  347. emmPasscodeInfoRequired:NO
  348. keychainError:NO
  349. restoredSignIn:NO
  350. oldAccessToken:NO
  351. modalCancel:NO];
  352. }
  353. - (void)testOAuthLogin_RestoredSignIn {
  354. [self OAuthLoginWithOptions:nil
  355. authError:nil
  356. tokenError:nil
  357. emmPasscodeInfoRequired:NO
  358. keychainError:NO
  359. restoredSignIn:YES
  360. oldAccessToken:NO
  361. modalCancel:NO];
  362. }
  363. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  364. [self OAuthLoginWithOptions:nil
  365. authError:nil
  366. tokenError:nil
  367. emmPasscodeInfoRequired:NO
  368. keychainError:NO
  369. restoredSignIn:YES
  370. oldAccessToken:YES
  371. modalCancel:NO];
  372. }
  373. - (void)testOpenIDRealm {
  374. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  375. serverClientID:nil
  376. hostedDomain:nil
  377. openIDRealm:kOpenIDRealm];
  378. [self OAuthLoginWithOptions:nil
  379. authError:nil
  380. tokenError:nil
  381. emmPasscodeInfoRequired:NO
  382. keychainError:NO
  383. restoredSignIn:NO
  384. oldAccessToken:NO
  385. modalCancel:NO];
  386. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  387. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  388. }
  389. - (void)testOAuthLogin_LoginHint {
  390. _hint = kUserEmail;
  391. [self OAuthLoginWithOptions:nil
  392. authError:nil
  393. tokenError:nil
  394. emmPasscodeInfoRequired:NO
  395. keychainError:NO
  396. restoredSignIn:NO
  397. oldAccessToken:NO
  398. modalCancel:NO];
  399. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  400. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  401. }
  402. - (void)testOAuthLogin_HostedDomain {
  403. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  404. serverClientID:nil
  405. hostedDomain:kHostedDomain
  406. openIDRealm:nil];
  407. [self OAuthLoginWithOptions:nil
  408. authError:nil
  409. tokenError:nil
  410. emmPasscodeInfoRequired:NO
  411. keychainError:NO
  412. restoredSignIn:NO
  413. oldAccessToken:NO
  414. modalCancel:NO];
  415. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  416. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  417. }
  418. - (void)testOAuthLogin_ConsentCanceled {
  419. [self OAuthLoginWithOptions:nil
  420. authError:@"access_denied"
  421. tokenError:nil
  422. emmPasscodeInfoRequired:NO
  423. keychainError:NO
  424. restoredSignIn:NO
  425. oldAccessToken:NO
  426. modalCancel:NO];
  427. [self waitForExpectationsWithTimeout:1 handler:nil];
  428. XCTAssertTrue(_callbackCalled, @"should call delegate");
  429. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  430. }
  431. - (void)testOAuthLogin_ModalCanceled {
  432. [self OAuthLoginWithOptions:nil
  433. authError:nil
  434. tokenError:nil
  435. emmPasscodeInfoRequired:NO
  436. keychainError:NO
  437. restoredSignIn:NO
  438. oldAccessToken:NO
  439. modalCancel:YES];
  440. [self waitForExpectationsWithTimeout:1 handler:nil];
  441. XCTAssertTrue(_callbackCalled, @"should call delegate");
  442. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  443. }
  444. - (void)testOAuthLogin_KeychainError {
  445. [self OAuthLoginWithOptions:nil
  446. authError:nil
  447. tokenError:nil
  448. emmPasscodeInfoRequired:NO
  449. keychainError:YES
  450. restoredSignIn:NO
  451. oldAccessToken:NO
  452. modalCancel:NO];
  453. [self waitForExpectationsWithTimeout:1 handler:nil];
  454. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  455. XCTAssertTrue(_callbackCalled, @"should call delegate");
  456. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  457. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  458. }
  459. - (void)testSignOut {
  460. // Sign in a user so that we can then sign them out.
  461. [self OAuthLoginWithOptions:nil
  462. authError:nil
  463. tokenError:nil
  464. emmPasscodeInfoRequired:NO
  465. keychainError:NO
  466. restoredSignIn:YES
  467. oldAccessToken:NO
  468. modalCancel:NO];
  469. XCTAssertNotNil(_signIn.currentUser);
  470. [_signIn signOut];
  471. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  472. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  473. XCTAssertTrue([_changedKeyPaths containsObject:NSStringFromSelector(@selector(currentUser))],
  474. @"should notify observers that signed in user changed");
  475. }
  476. - (void)testNotHandleWrongScheme {
  477. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  478. @"should not handle URL");
  479. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  480. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  481. }
  482. - (void)testNotHandleWrongPath {
  483. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  484. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  485. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  486. }
  487. #pragma mark - Tests - disconnectWithCallback:
  488. // Verifies disconnect calls callback with no errors if access token is present.
  489. - (void)testDisconnect_accessToken {
  490. [[[_authorization expect] andReturn:_authState] authState];
  491. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  492. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  493. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  494. XCTestExpectation *expectation =
  495. [self expectationWithDescription:@"Callback called with nil error"];
  496. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  497. if (error == nil) {
  498. [expectation fulfill];
  499. }
  500. }];
  501. [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
  502. [_authorization verify];
  503. [_authState verify];
  504. [_tokenResponse verify];
  505. }
  506. // Verifies disconnect if access token is present.
  507. - (void)testDisconnectNoCallback_accessToken {
  508. [[[_authorization expect] andReturn:_authState] authState];
  509. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  510. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  511. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  512. [_signIn disconnectWithCallback:nil];
  513. [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
  514. [_authorization verify];
  515. [_authState verify];
  516. [_tokenResponse verify];
  517. }
  518. // Verifies disconnect calls callback with no errors if refresh token is present.
  519. - (void)testDisconnect_refreshToken {
  520. [[[_authorization expect] andReturn:_authState] authState];
  521. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  522. [[[_tokenResponse expect] andReturn:nil] accessToken];
  523. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  524. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  525. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  526. XCTestExpectation *expectation =
  527. [self expectationWithDescription:@"Callback called with nil error"];
  528. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  529. if (error == nil) {
  530. [expectation fulfill];
  531. }
  532. }];
  533. [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
  534. [_authorization verify];
  535. [_authState verify];
  536. [_tokenResponse verify];
  537. }
  538. // Verifies disconnect errors are passed along to the callback.
  539. - (void)testDisconnect_errors {
  540. [[[_authorization expect] andReturn:_authState] authState];
  541. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  542. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  543. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  544. XCTestExpectation *expectation =
  545. [self expectationWithDescription:@"Callback called with an error"];
  546. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  547. if (error != nil) {
  548. [expectation fulfill];
  549. }
  550. }];
  551. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  552. // Emulate result back from server.
  553. NSError *error = [self error];
  554. [self didFetch:nil error:error];
  555. [self waitForExpectationsWithTimeout:1 handler:nil];
  556. [_authorization verify];
  557. [_authState verify];
  558. [_tokenResponse verify];
  559. }
  560. // Verifies disconnect with errors
  561. - (void)testDisconnectNoCallback_errors {
  562. [[[_authorization expect] andReturn:_authState] authState];
  563. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  564. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  565. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  566. [_signIn disconnectWithCallback:nil];
  567. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  568. // Emulate result back from server.
  569. NSError *error = [self error];
  570. [self didFetch:nil error:error];
  571. [_authorization verify];
  572. [_authState verify];
  573. [_tokenResponse verify];
  574. }
  575. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  576. - (void)testDisconnect_noTokens {
  577. [[[_authorization expect] andReturn:_authState] authState];
  578. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  579. [[[_tokenResponse expect] andReturn:nil] accessToken];
  580. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  581. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  582. XCTestExpectation *expectation =
  583. [self expectationWithDescription:@"Callback called with nil error"];
  584. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  585. if (error == nil) {
  586. [expectation fulfill];
  587. }
  588. }];
  589. [self waitForExpectationsWithTimeout:1 handler:nil];
  590. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  591. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  592. [_authorization verify];
  593. [_authState verify];
  594. [_tokenResponse verify];
  595. }
  596. // Verifies disconnect clears keychain if no tokens are present.
  597. - (void)testDisconnectNoCallback_noTokens {
  598. [[[_authorization expect] andReturn:_authState] authState];
  599. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  600. [[[_tokenResponse expect] andReturn:nil] accessToken];
  601. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  602. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  603. [_signIn disconnectWithCallback:nil];
  604. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  605. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  606. [_authorization verify];
  607. [_authState verify];
  608. [_tokenResponse verify];
  609. }
  610. - (void)testPresentingViewControllerException {
  611. _presentingViewController = nil;
  612. XCTAssertThrows([_signIn signInWithConfiguration:_configuration
  613. presentingViewController:_presentingViewController
  614. hint:_hint
  615. callback:_callback]);
  616. }
  617. - (void)testClientIDMissingException {
  618. #pragma GCC diagnostic push
  619. #pragma GCC diagnostic ignored "-Wnonnull"
  620. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  621. #pragma GCC diagnostic pop
  622. BOOL threw = NO;
  623. @try {
  624. [_signIn signInWithConfiguration:configuration
  625. presentingViewController:_presentingViewController
  626. callback:nil];
  627. } @catch (NSException *exception) {
  628. threw = YES;
  629. XCTAssertEqualObjects(exception.description,
  630. @"You must specify |clientID| in |GIDConfiguration|");
  631. } @finally {
  632. }
  633. XCTAssert(threw);
  634. }
  635. - (void)testSchemesNotSupportedException {
  636. [_fakeMainBundle fakeMissingAllSchemes];
  637. BOOL threw = NO;
  638. @try {
  639. [_signIn signInWithConfiguration:_configuration
  640. presentingViewController:_presentingViewController
  641. hint:_hint
  642. callback:_callback];
  643. } @catch (NSException *exception) {
  644. threw = YES;
  645. XCTAssertEqualObjects(exception.description,
  646. @"Your app is missing support for the following URL schemes: "
  647. "fakeclientid");
  648. } @finally {
  649. }
  650. XCTAssert(threw);
  651. }
  652. #pragma mark - Restarting Authentication Tests
  653. // Verifies that URL is not handled if there is no pending sign-in
  654. - (void)testRequiringPendingSignIn {
  655. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  656. XCTAssertFalse(result);
  657. }
  658. #pragma mark - EMM tests
  659. - (void)testEmmSupportRequestParameters {
  660. [self OAuthLoginWithOptions:nil
  661. authError:nil
  662. tokenError:nil
  663. emmPasscodeInfoRequired:NO
  664. keychainError:NO
  665. restoredSignIn:NO
  666. oldAccessToken:NO
  667. modalCancel:NO];
  668. NSString *systemName = [UIDevice currentDevice].systemName;
  669. if ([systemName isEqualToString:@"iPhone OS"]) {
  670. systemName = @"iOS";
  671. }
  672. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  673. systemName, [UIDevice currentDevice].systemVersion];
  674. NSDictionary<NSString *, NSObject *> *authParams =
  675. _savedAuthorizationRequest.additionalParameters;
  676. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  677. if (_isEligibleForEMM) {
  678. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  679. @"EMM support should match in auth request");
  680. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  681. @"OS version should match in auth request");
  682. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  683. @"EMM support should match in token request");
  684. XCTAssertEqualObjects(tokenParams[@"device_os"],
  685. expectedOSVersion,
  686. @"OS version should match in token request");
  687. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  688. @"no passcode info should be in token request");
  689. } else {
  690. XCTAssertNil(authParams[@"emm_support"],
  691. @"EMM support should not be in auth request for unsupported OS");
  692. XCTAssertNil(authParams[@"device_os"],
  693. @"OS version should not be in auth request for unsupported OS");
  694. XCTAssertNil(tokenParams[@"emm_support"],
  695. @"EMM support should not be in token request for unsupported OS");
  696. XCTAssertNil(tokenParams[@"device_os"],
  697. @"OS version should not be in token request for unsupported OS");
  698. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  699. @"passcode info should not be in token request for unsupported OS");
  700. }
  701. }
  702. - (void)testEmmPasscodeInfo {
  703. [self OAuthLoginWithOptions:nil
  704. authError:nil
  705. tokenError:nil
  706. emmPasscodeInfoRequired:YES
  707. keychainError:NO
  708. restoredSignIn:NO
  709. oldAccessToken:NO
  710. modalCancel:NO];
  711. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  712. if (_isEligibleForEMM) {
  713. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  714. @"passcode info should be in token request");
  715. } else {
  716. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  717. @"passcode info should not be in token request for unsupported OS");
  718. }
  719. }
  720. - (void)testAuthEndpointEMMError {
  721. if (!_isEligibleForEMM) {
  722. return;
  723. }
  724. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  725. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  726. __block void (^completion)(void);
  727. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  728. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  729. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  730. [self OAuthLoginWithOptions:nil
  731. authError:callbackParams[@"error"]
  732. tokenError:nil
  733. emmPasscodeInfoRequired:NO
  734. keychainError:NO
  735. restoredSignIn:NO
  736. oldAccessToken:NO
  737. modalCancel:NO];
  738. [mockEMMErrorHandler verify];
  739. [mockEMMErrorHandler stopMocking];
  740. completion();
  741. [self waitForExpectationsWithTimeout:1 handler:nil];
  742. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  743. XCTAssertTrue(_callbackCalled, @"should call delegate");
  744. XCTAssertNotNil(_authError, @"should have error");
  745. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  746. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  747. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  748. }
  749. - (void)testTokenEndpointEMMError {
  750. if (!_isEligibleForEMM) {
  751. return;
  752. }
  753. __block void (^completion)(NSError *);
  754. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  755. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  756. code:12345
  757. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  758. [[_authentication expect] handleTokenFetchEMMError:emmError
  759. completion:SAVE_TO_ARG_BLOCK(completion)];
  760. [self OAuthLoginWithOptions:nil
  761. authError:nil
  762. tokenError:emmError
  763. emmPasscodeInfoRequired:NO
  764. keychainError:NO
  765. restoredSignIn:NO
  766. oldAccessToken:NO
  767. modalCancel:NO];
  768. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  769. code:kGIDSignInErrorCodeEMM
  770. userInfo:emmError.userInfo];
  771. completion(handledError);
  772. [self waitForExpectationsWithTimeout:1 handler:nil];
  773. [_authentication verify];
  774. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  775. XCTAssertTrue(_callbackCalled, @"should call delegate");
  776. XCTAssertNotNil(_authError, @"should have error");
  777. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  778. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  779. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  780. }
  781. #pragma mark - Helpers
  782. // Whether or not a fetcher has been started.
  783. - (BOOL)isFetcherStarted {
  784. NSUInteger count = _fetcherService.fetchers.count;
  785. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  786. return !!count;
  787. }
  788. // Gets the URL being fetched.
  789. - (NSURL *)fetchedURL {
  790. return [_fetcherService.fetchers[0] requestURL];
  791. }
  792. // Emulates server returning the data as in JSON.
  793. - (void)didFetch:(id)dataObject error:(NSError *)error {
  794. NSData *data = nil;
  795. if (dataObject) {
  796. NSError *jsonError = nil;
  797. data = [NSJSONSerialization dataWithJSONObject:dataObject
  798. options:0
  799. error:&jsonError];
  800. XCTAssertNil(jsonError, @"must provide valid data");
  801. }
  802. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  803. }
  804. - (NSError *)error {
  805. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  806. }
  807. // Verifies a fetcher has started for revoking token and emulates a server response.
  808. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  809. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  810. NSURL *url = [self fetchedURL];
  811. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  812. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  813. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  814. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  815. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  816. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  817. @"token parameter should match");
  818. // Emulate result back from server.
  819. [self didFetch:nil error:nil];
  820. if (hasCallback) {
  821. [self waitForExpectationsWithTimeout:1 handler:nil];
  822. }
  823. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  824. }
  825. // The authorization flow with parameters to control which branches to take.
  826. - (void)OAuthLoginWithOptions:(GIDSignInInternalOptions *)options
  827. authError:(NSString *)authError
  828. tokenError:(NSError *)tokenError
  829. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  830. keychainError:(BOOL)keychainError
  831. restoredSignIn:(BOOL)restoredSignIn
  832. oldAccessToken:(BOOL)oldAccessToken
  833. modalCancel:(BOOL)modalCancel {
  834. if (restoredSignIn) {
  835. // clearAndAuthenticateWithOptions
  836. [[[_authorization expect] andReturn:_authState] authState];
  837. BOOL isAuthorized = restoredSignIn ? YES : NO;
  838. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  839. }
  840. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  841. @{ @"emm_passcode_info_required" : @"1" } : nil;
  842. OIDAuthorizationResponse *authResponse =
  843. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  844. errorString:authError];
  845. OIDTokenResponse *tokenResponse =
  846. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  847. accessToken:restoredSignIn ? kAccessToken : nil
  848. expiresIn:oldAccessToken ? @(300) : nil
  849. tokenRequest:nil];
  850. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  851. initWithConfiguration:authResponse.request.configuration
  852. grantType:OIDGrantTypeRefreshToken
  853. authorizationCode:nil
  854. redirectURL:nil
  855. clientID:authResponse.request.clientID
  856. clientSecret:authResponse.request.clientSecret
  857. scope:nil
  858. refreshToken:kRefreshToken
  859. codeVerifier:nil
  860. additionalParameters:tokenResponse.request.additionalParameters];
  861. if (restoredSignIn) {
  862. // maybeFetchToken
  863. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  864. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  865. if (oldAccessToken) {
  866. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  867. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  868. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  869. [[[_authState expect] andReturn:tokenRequest]
  870. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  871. }
  872. } else {
  873. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  874. [_signIn signInWithConfiguration:_configuration
  875. presentingViewController:_presentingViewController
  876. hint:_hint
  877. callback:^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  878. [expectation fulfill];
  879. if (!user) {
  880. XCTAssertNotNil(error, @"should have an error if user is nil");
  881. }
  882. XCTAssertFalse(self->_callbackCalled, @"callback already called");
  883. self->_callbackCalled = YES;
  884. self->_authError = error;
  885. }];
  886. [_authorization verify];
  887. [_authState verify];
  888. XCTAssertNotNil(_savedAuthorizationRequest);
  889. XCTAssertNotNil(_savedAuthorizationCallback);
  890. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  891. // maybeFetchToken
  892. if (!(authError || modalCancel)) {
  893. [[[_authState expect] andReturn:nil] lastTokenResponse];
  894. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  895. [[[_authState expect] andReturn:nil] lastTokenResponse];
  896. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  897. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  898. }
  899. // Simulate auth endpoint response
  900. if (modalCancel) {
  901. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  902. code:OIDErrorCodeUserCanceledAuthorizationFlow
  903. userInfo:nil];
  904. _savedAuthorizationCallback(nil, error);
  905. } else {
  906. _savedAuthorizationCallback(authResponse, nil);
  907. }
  908. if (authError || modalCancel) {
  909. return;
  910. }
  911. [_authState verify];
  912. }
  913. if (restoredSignIn && oldAccessToken) {
  914. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  915. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  916. NSError * _Nullable error) {
  917. [expectation fulfill];
  918. XCTAssertNil(error, @"should have no error");
  919. }];
  920. }
  921. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  922. XCTAssertNotNil(_savedTokenRequest);
  923. XCTAssertNotNil(_savedTokenCallback);
  924. // OIDTokenCallback
  925. if (tokenError) {
  926. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  927. } else {
  928. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  929. }
  930. }
  931. if (tokenError) {
  932. _savedTokenCallback(nil, tokenError);
  933. return;
  934. }
  935. // DecodeIdTokenCallback
  936. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  937. // SaveAuthCallback
  938. [[[_user stub] andReturn:_user] alloc];
  939. __block OIDAuthState *authState;
  940. __block GIDProfileData *profileData;
  941. if (keychainError) {
  942. _saveAuthorizationReturnValue = NO;
  943. } else {
  944. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  945. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  946. }
  947. if (restoredSignIn && !oldAccessToken) {
  948. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  949. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  950. NSError * _Nullable error) {
  951. [expectation fulfill];
  952. XCTAssertNil(error, @"should have no error");
  953. }];
  954. } else {
  955. // Simulate token endpoint response.
  956. _savedTokenCallback(tokenResponse, nil);
  957. }
  958. [_authState verify];
  959. if (keychainError) {
  960. return;
  961. }
  962. [self waitForExpectationsWithTimeout:1 handler:nil];
  963. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  964. XCTAssertNotNil(authState);
  965. // Check fat ID token decoding
  966. XCTAssertEqualObjects(profileData.name, kFatName);
  967. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  968. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  969. XCTAssertTrue(profileData.hasImage);
  970. // If attempt to authenticate again, will reuse existing auth object.
  971. _callbackCalled = NO;
  972. _keychainRemoved = NO;
  973. _keychainSaved = NO;
  974. _authError = nil;
  975. [[[_user expect] andReturn:_authentication] authentication];
  976. [[[_user expect] andReturn:_authentication] authentication];
  977. __block GIDAuthenticationAction action;
  978. [[_authentication expect] doWithFreshTokens:SAVE_TO_ARG_BLOCK(action)];
  979. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  980. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  981. NSError * _Nullable error) {
  982. [expectation fulfill];
  983. XCTAssertNil(error, @"should have no error");
  984. }];
  985. action(_authentication, nil);
  986. [self waitForExpectationsWithTimeout:1 handler:nil];
  987. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  988. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  989. }
  990. #pragma mark - Key Value Observing
  991. - (void)observeValueForKeyPath:(NSString *)keyPath
  992. ofObject:(id)object
  993. change:(NSDictionary<NSKeyValueChangeKey, id> *)change
  994. context:(void *)context {
  995. if (context == kTestObserverContext && object == _signIn) {
  996. [_changedKeyPaths addObject:keyPath];
  997. }
  998. }
  999. @end