GIDSignInTest.m 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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 callback 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 error"];
  513. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  514. if (error == nil) {
  515. [expectation fulfill];
  516. }
  517. }];
  518. [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
  519. [_authorization verify];
  520. [_authState verify];
  521. [_tokenResponse verify];
  522. }
  523. // Verifies disconnect if access token is present.
  524. - (void)testDisconnectNoCallback_accessToken {
  525. [[[_authorization expect] andReturn:_authState] authState];
  526. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  527. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  528. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  529. [_signIn disconnectWithCallback:nil];
  530. [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
  531. [_authorization verify];
  532. [_authState verify];
  533. [_tokenResponse verify];
  534. }
  535. // Verifies disconnect calls callback with no errors if refresh token is present.
  536. - (void)testDisconnect_refreshToken {
  537. [[[_authorization expect] andReturn:_authState] authState];
  538. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  539. [[[_tokenResponse expect] andReturn:nil] accessToken];
  540. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  541. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  542. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  543. XCTestExpectation *expectation =
  544. [self expectationWithDescription:@"Callback called with nil error"];
  545. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  546. if (error == nil) {
  547. [expectation fulfill];
  548. }
  549. }];
  550. [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
  551. [_authorization verify];
  552. [_authState verify];
  553. [_tokenResponse verify];
  554. }
  555. // Verifies disconnect errors are passed along to the callback.
  556. - (void)testDisconnect_errors {
  557. [[[_authorization expect] andReturn:_authState] authState];
  558. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  559. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  560. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  561. XCTestExpectation *expectation =
  562. [self expectationWithDescription:@"Callback called with an error"];
  563. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  564. if (error != nil) {
  565. [expectation fulfill];
  566. }
  567. }];
  568. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  569. // Emulate result back from server.
  570. NSError *error = [self error];
  571. [self didFetch:nil error:error];
  572. [self waitForExpectationsWithTimeout:1 handler:nil];
  573. [_authorization verify];
  574. [_authState verify];
  575. [_tokenResponse verify];
  576. }
  577. // Verifies disconnect with errors
  578. - (void)testDisconnectNoCallback_errors {
  579. [[[_authorization expect] andReturn:_authState] authState];
  580. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  581. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  582. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  583. [_signIn disconnectWithCallback:nil];
  584. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  585. // Emulate result back from server.
  586. NSError *error = [self error];
  587. [self didFetch:nil error:error];
  588. [_authorization verify];
  589. [_authState verify];
  590. [_tokenResponse verify];
  591. }
  592. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  593. - (void)testDisconnect_noTokens {
  594. [[[_authorization expect] andReturn:_authState] authState];
  595. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  596. [[[_tokenResponse expect] andReturn:nil] accessToken];
  597. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  598. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  599. XCTestExpectation *expectation =
  600. [self expectationWithDescription:@"Callback called with nil error"];
  601. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  602. if (error == nil) {
  603. [expectation fulfill];
  604. }
  605. }];
  606. [self waitForExpectationsWithTimeout:1 handler:nil];
  607. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  608. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  609. [_authorization verify];
  610. [_authState verify];
  611. [_tokenResponse verify];
  612. }
  613. // Verifies disconnect clears keychain if no tokens are present.
  614. - (void)testDisconnectNoCallback_noTokens {
  615. [[[_authorization expect] andReturn:_authState] authState];
  616. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  617. [[[_tokenResponse expect] andReturn:nil] accessToken];
  618. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  619. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  620. [_signIn disconnectWithCallback:nil];
  621. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  622. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  623. [_authorization verify];
  624. [_authState verify];
  625. [_tokenResponse verify];
  626. }
  627. - (void)testPresentingViewControllerException {
  628. _signIn.presentingViewController = nil;
  629. XCTAssertThrows([_signIn signIn]);
  630. }
  631. - (void)testNoPresentingViewControllerExceptionForSilentSignIn {
  632. [[[_authorization expect] andReturn:_authState] authState];
  633. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  634. _signIn.presentingViewController = nil;
  635. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  636. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  637. NSError * _Nullable error) {
  638. [expectation fulfill];
  639. }];
  640. [self waitForExpectationsWithTimeout:1 handler:nil];
  641. [_authorization verify];
  642. [_authState verify];
  643. }
  644. - (void)testClientIDMissingException {
  645. _signIn.clientID = nil;
  646. BOOL threw = NO;
  647. @try {
  648. [_signIn signIn];
  649. } @catch (NSException *exception) {
  650. threw = YES;
  651. XCTAssertEqualObjects(exception.description,
  652. @"You must specify |clientID| for |GIDSignIn|");
  653. } @finally {
  654. }
  655. XCTAssert(threw);
  656. }
  657. - (void)testSchemesNotSupportedException {
  658. [_fakeMainBundle fakeMissingAllSchemes];
  659. BOOL threw = NO;
  660. @try {
  661. [_signIn signIn];
  662. } @catch (NSException *exception) {
  663. threw = YES;
  664. XCTAssertEqualObjects(exception.description,
  665. @"Your app is missing support for the following URL schemes: "
  666. "fakeclientid");
  667. } @finally {
  668. }
  669. XCTAssert(threw);
  670. }
  671. #pragma mark - Tests - UI Delegate
  672. - (void)testAssertValidPresentingViewControllerWithNilPresentingViewController {
  673. _signIn.presentingViewController = nil;
  674. XCTAssertThrows([_signIn assertValidPresentingViewContoller]);
  675. }
  676. #pragma mark - Restarting Authentication Tests
  677. // Verifies that URL is not handled if there is no pending sign-in
  678. - (void)testRequiringPendingSignIn {
  679. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  680. XCTAssertFalse(result);
  681. }
  682. #pragma mark - EMM tests
  683. - (void)testEmmSupportRequestParameters {
  684. [self OAuthLoginWithOptions:nil
  685. authError:nil
  686. tokenError:nil
  687. emmPasscodeInfoRequired:NO
  688. keychainError:NO
  689. restoredSignIn:NO
  690. oldAccessToken:NO
  691. modalCancel:NO];
  692. NSString *systemName = [UIDevice currentDevice].systemName;
  693. if ([systemName isEqualToString:@"iPhone OS"]) {
  694. systemName = @"iOS";
  695. }
  696. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  697. systemName, [UIDevice currentDevice].systemVersion];
  698. NSDictionary<NSString *, NSObject *> *authParams =
  699. _savedAuthorizationRequest.additionalParameters;
  700. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  701. if (_isEligibleForEMM) {
  702. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  703. @"EMM support should match in auth request");
  704. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  705. @"OS version should match in auth request");
  706. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  707. @"EMM support should match in token request");
  708. XCTAssertEqualObjects(tokenParams[@"device_os"],
  709. expectedOSVersion,
  710. @"OS version should match in token request");
  711. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  712. @"no passcode info should be in token request");
  713. } else {
  714. XCTAssertNil(authParams[@"emm_support"],
  715. @"EMM support should not be in auth request for unsupported OS");
  716. XCTAssertNil(authParams[@"device_os"],
  717. @"OS version should not be in auth request for unsupported OS");
  718. XCTAssertNil(tokenParams[@"emm_support"],
  719. @"EMM support should not be in token request for unsupported OS");
  720. XCTAssertNil(tokenParams[@"device_os"],
  721. @"OS version should not be in token request for unsupported OS");
  722. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  723. @"passcode info should not be in token request for unsupported OS");
  724. }
  725. }
  726. - (void)testEmmPasscodeInfo {
  727. [self OAuthLoginWithOptions:nil
  728. authError:nil
  729. tokenError:nil
  730. emmPasscodeInfoRequired:YES
  731. keychainError:NO
  732. restoredSignIn:NO
  733. oldAccessToken:NO
  734. modalCancel:NO];
  735. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  736. if (_isEligibleForEMM) {
  737. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  738. @"passcode info should be in token request");
  739. } else {
  740. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  741. @"passcode info should not be in token request for unsupported OS");
  742. }
  743. }
  744. - (void)testAuthEndpointEMMError {
  745. if (!_isEligibleForEMM) {
  746. return;
  747. }
  748. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  749. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  750. __block void (^completion)(void);
  751. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  752. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  753. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  754. [self OAuthLoginWithOptions:nil
  755. authError:callbackParams[@"error"]
  756. tokenError:nil
  757. emmPasscodeInfoRequired:NO
  758. keychainError:NO
  759. restoredSignIn:NO
  760. oldAccessToken:NO
  761. modalCancel:NO];
  762. [mockEMMErrorHandler verify];
  763. [mockEMMErrorHandler stopMocking];
  764. completion();
  765. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  766. XCTAssertTrue(_delegateCalled, @"should call delegate");
  767. XCTAssertNotNil(_authError, @"should have error");
  768. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  769. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  770. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  771. }
  772. - (void)testTokenEndpointEMMError {
  773. if (!_isEligibleForEMM) {
  774. return;
  775. }
  776. __block void (^completion)(NSError *);
  777. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  778. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  779. code:12345
  780. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  781. [[_authentication expect] handleTokenFetchEMMError:emmError
  782. completion:SAVE_TO_ARG_BLOCK(completion)];
  783. [self OAuthLoginWithOptions:nil
  784. authError:nil
  785. tokenError:emmError
  786. emmPasscodeInfoRequired:NO
  787. keychainError:NO
  788. restoredSignIn:NO
  789. oldAccessToken:NO
  790. modalCancel:NO];
  791. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  792. code:kGIDSignInErrorCodeEMM
  793. userInfo:emmError.userInfo];
  794. completion(handledError);
  795. [_authentication verify];
  796. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  797. XCTAssertTrue(_delegateCalled, @"should call delegate");
  798. XCTAssertNotNil(_authError, @"should have error");
  799. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  800. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  801. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  802. }
  803. #pragma mark - Helpers
  804. // Whether or not a fetcher has been started.
  805. - (BOOL)isFetcherStarted {
  806. NSUInteger count = _fetcherService.fetchers.count;
  807. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  808. return !!count;
  809. }
  810. // Gets the URL being fetched.
  811. - (NSURL *)fetchedURL {
  812. return [_fetcherService.fetchers[0] requestURL];
  813. }
  814. // Emulates server returning the data as in JSON.
  815. - (void)didFetch:(id)dataObject error:(NSError *)error {
  816. NSData *data = nil;
  817. if (dataObject) {
  818. NSError *jsonError = nil;
  819. data = [NSJSONSerialization dataWithJSONObject:dataObject
  820. options:0
  821. error:&jsonError];
  822. XCTAssertNil(jsonError, @"must provide valid data");
  823. }
  824. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  825. }
  826. - (NSError *)error {
  827. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  828. }
  829. // Verifies a fetcher has started for revoking token and emulates a server response.
  830. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  831. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  832. NSURL *url = [self fetchedURL];
  833. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  834. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  835. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  836. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  837. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  838. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  839. @"token parameter should match");
  840. // Emulate result back from server.
  841. [self didFetch:nil error:nil];
  842. if (hasCallback) {
  843. [self waitForExpectationsWithTimeout:1 handler:nil];
  844. }
  845. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  846. }
  847. // The authorization flow with parameters to control which branches to take.
  848. - (void)OAuthLoginWithOptions:(GIDSignInInternalOptions *)options
  849. authError:(NSString *)authError
  850. tokenError:(NSError *)tokenError
  851. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  852. keychainError:(BOOL)keychainError
  853. restoredSignIn:(BOOL)restoredSignIn
  854. oldAccessToken:(BOOL)oldAccessToken
  855. modalCancel:(BOOL)modalCancel {
  856. if (restoredSignIn) {
  857. // clearAndAuthenticateWithOptions
  858. [[[_authorization expect] andReturn:_authState] authState];
  859. BOOL isAuthorized = restoredSignIn ? YES : NO;
  860. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  861. }
  862. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  863. @{ @"emm_passcode_info_required" : @"1" } : nil;
  864. OIDAuthorizationResponse *authResponse =
  865. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  866. errorString:authError];
  867. OIDTokenResponse *tokenResponse =
  868. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  869. accessToken:restoredSignIn ? kAccessToken : nil
  870. expiresIn:oldAccessToken ? @(300) : nil
  871. tokenRequest:nil];
  872. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  873. initWithConfiguration:authResponse.request.configuration
  874. grantType:OIDGrantTypeRefreshToken
  875. authorizationCode:nil
  876. redirectURL:nil
  877. clientID:authResponse.request.clientID
  878. clientSecret:authResponse.request.clientSecret
  879. scope:nil
  880. refreshToken:kRefreshToken
  881. codeVerifier:nil
  882. additionalParameters:tokenResponse.request.additionalParameters];
  883. if (restoredSignIn) {
  884. // maybeFetchToken
  885. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  886. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  887. if (oldAccessToken) {
  888. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  889. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  890. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  891. [[[_authState expect] andReturn:tokenRequest]
  892. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  893. }
  894. } else {
  895. if (options) {
  896. [_signIn signInWithOptions:options];
  897. } else {
  898. [_signIn signIn];
  899. }
  900. [_authorization verify];
  901. [_authState verify];
  902. XCTAssertNotNil(_savedAuthorizationRequest);
  903. XCTAssertNotNil(_savedAuthorizationCallback);
  904. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  905. // maybeFetchToken
  906. if (!(authError || modalCancel)) {
  907. [[[_authState expect] andReturn:nil] lastTokenResponse];
  908. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  909. [[[_authState expect] andReturn:nil] lastTokenResponse];
  910. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  911. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  912. }
  913. // Simulate auth endpoint response
  914. if (modalCancel) {
  915. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  916. code:OIDErrorCodeUserCanceledAuthorizationFlow
  917. userInfo:nil];
  918. _savedAuthorizationCallback(nil, error);
  919. } else {
  920. _savedAuthorizationCallback(authResponse, nil);
  921. }
  922. if (authError || modalCancel) {
  923. return;
  924. }
  925. [_authState verify];
  926. }
  927. if (restoredSignIn && oldAccessToken) {
  928. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  929. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  930. NSError * _Nullable error) {
  931. [expectation fulfill];
  932. XCTAssertNil(error, @"should have no error");
  933. }];
  934. }
  935. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  936. XCTAssertNotNil(_savedTokenRequest);
  937. XCTAssertNotNil(_savedTokenCallback);
  938. // OIDTokenCallback
  939. if (tokenError) {
  940. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  941. } else {
  942. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  943. }
  944. }
  945. if (tokenError) {
  946. _savedTokenCallback(nil, tokenError);
  947. return;
  948. }
  949. // DecodeIdTokenCallback
  950. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  951. // SaveAuthCallback
  952. [[[_user stub] andReturn:_user] alloc];
  953. __block OIDAuthState *authState;
  954. __block GIDProfileData *profileData;
  955. if (keychainError) {
  956. _saveAuthorizationReturnValue = NO;
  957. } else {
  958. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  959. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  960. }
  961. if (restoredSignIn && !oldAccessToken) {
  962. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  963. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  964. NSError * _Nullable error) {
  965. [expectation fulfill];
  966. XCTAssertNil(error, @"should have no error");
  967. }];
  968. } else {
  969. // Simulate token endpoint response.
  970. _savedTokenCallback(tokenResponse, nil);
  971. }
  972. [_authState verify];
  973. if (keychainError) {
  974. return;
  975. }
  976. if (restoredSignIn) {
  977. [self waitForExpectationsWithTimeout:1 handler:nil];
  978. }
  979. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  980. XCTAssertNotNil(authState);
  981. // Check fat ID token decoding
  982. XCTAssertEqualObjects(profileData.name, kFatName);
  983. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  984. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  985. XCTAssertTrue(profileData.hasImage);
  986. // If attempt to authenticate again, will reuse existing auth object.
  987. _delegateCalled = NO;
  988. _keychainRemoved = NO;
  989. _keychainSaved = NO;
  990. _authError = nil;
  991. [[[_user expect] andReturn:_authentication] authentication];
  992. [[[_user expect] andReturn:_authentication] authentication];
  993. __block GIDAuthenticationAction action;
  994. [[_authentication expect] doWithFreshTokens:SAVE_TO_ARG_BLOCK(action)];
  995. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  996. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  997. NSError * _Nullable error) {
  998. [expectation fulfill];
  999. XCTAssertNil(error, @"should have no error");
  1000. }];
  1001. action(_authentication, nil);
  1002. [self waitForExpectationsWithTimeout:1 handler:nil];
  1003. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1004. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1005. }
  1006. #pragma mark - Key Value Observing
  1007. - (void)observeValueForKeyPath:(NSString *)keyPath
  1008. ofObject:(id)object
  1009. change:(NSDictionary<NSKeyValueChangeKey, id> *)change
  1010. context:(void *)context {
  1011. if (context == kTestObserverContext && object == _signIn) {
  1012. [_changedKeyPaths addObject:keyPath];
  1013. }
  1014. }
  1015. #pragma mark - GIDSignInDelegate
  1016. - (void)signIn:(GIDSignIn *)signIn
  1017. didSignInForUser:(GIDGoogleUser *)user
  1018. withError:(NSError *)error {
  1019. if (!user) {
  1020. XCTAssertNotNil(error, @"should have an error if user is nil");
  1021. }
  1022. XCTAssertFalse(_delegateCalled, @"delegate already called");
  1023. _delegateCalled = YES;
  1024. _authError = error;
  1025. }
  1026. @end