GIDSignInTest.m 49 KB

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