GIDSignInTest.m 45 KB

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