GIDSignInTest.m 43 KB

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