GIDSignInTest.m 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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/GIDSignIn_Private.h"
  26. #import "GoogleSignIn/Sources/GIDSignInPreferences.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 OAuthLoginWithAddScopesFlow:NO
  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 OAuthLoginWithAddScopesFlow:NO
  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 OAuthLoginWithAddScopesFlow:NO
  404. authError:nil
  405. tokenError:nil
  406. emmPasscodeInfoRequired:NO
  407. keychainError:NO
  408. restoredSignIn:YES
  409. oldAccessToken:YES
  410. modalCancel:NO];
  411. }
  412. - (void)testOAuthLogin_AdditionalScopes {
  413. NSString *expectedScopeString;
  414. [self OAuthLoginWithAddScopesFlow:NO
  415. authError:nil
  416. tokenError:nil
  417. emmPasscodeInfoRequired:NO
  418. keychainError:NO
  419. restoredSignIn:NO
  420. oldAccessToken:NO
  421. modalCancel:NO
  422. useAdditionalScopes:YES
  423. additionalScopes:nil];
  424. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  425. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  426. [self OAuthLoginWithAddScopesFlow:NO
  427. authError:nil
  428. tokenError:nil
  429. emmPasscodeInfoRequired:NO
  430. keychainError:NO
  431. restoredSignIn:NO
  432. oldAccessToken:NO
  433. modalCancel:NO
  434. useAdditionalScopes:YES
  435. additionalScopes:@[ kScope ]];
  436. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  437. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  438. [self OAuthLoginWithAddScopesFlow:NO
  439. authError:nil
  440. tokenError:nil
  441. emmPasscodeInfoRequired:NO
  442. keychainError:NO
  443. restoredSignIn:NO
  444. oldAccessToken:NO
  445. modalCancel:NO
  446. useAdditionalScopes:YES
  447. additionalScopes:@[ kScope, kScope2 ]];
  448. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  449. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  450. }
  451. - (void)testAddScopes {
  452. // Restore the previous sign-in account. This is the preparation for adding scopes.
  453. [self OAuthLoginWithAddScopesFlow:NO
  454. authError:nil
  455. tokenError:nil
  456. emmPasscodeInfoRequired:NO
  457. keychainError:NO
  458. restoredSignIn:YES
  459. oldAccessToken:NO
  460. modalCancel:NO];
  461. XCTAssertNotNil(_signIn.currentUser);
  462. id profile = OCMStrictClassMock([GIDProfileData class]);
  463. OCMStub([profile email]).andReturn(kUserEmail);
  464. OCMStub([_user authentication]).andReturn(_authentication);
  465. OCMStub([_authentication clientID]).andReturn(kClientId);
  466. OCMStub([_user serverClientID]).andReturn(nil);
  467. OCMStub([_user hostedDomain]).andReturn(nil);
  468. OCMStub([_user openIDRealm]).andReturn(kOpenIDRealm);
  469. OCMStub([_user profile]).andReturn(profile);
  470. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  471. [self OAuthLoginWithAddScopesFlow:YES
  472. authError:nil
  473. tokenError:nil
  474. emmPasscodeInfoRequired:NO
  475. keychainError:NO
  476. restoredSignIn:NO
  477. oldAccessToken:NO
  478. modalCancel:NO];
  479. NSArray<NSString *> *grantedScopes;
  480. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  481. if (grantedScopeString) {
  482. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  483. [NSCharacterSet whitespaceCharacterSet]];
  484. // Tokenize with space as a delimiter.
  485. NSMutableArray<NSString *> *parsedScopes =
  486. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  487. // Remove empty strings.
  488. [parsedScopes removeObject:@""];
  489. grantedScopes = [parsedScopes copy];
  490. }
  491. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  492. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  493. [profile stopMocking];
  494. }
  495. - (void)testOpenIDRealm {
  496. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  497. serverClientID:nil
  498. hostedDomain:nil
  499. openIDRealm:kOpenIDRealm];
  500. [self OAuthLoginWithAddScopesFlow:NO
  501. authError:nil
  502. tokenError:nil
  503. emmPasscodeInfoRequired:NO
  504. keychainError:NO
  505. restoredSignIn:NO
  506. oldAccessToken:NO
  507. modalCancel:NO];
  508. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  509. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  510. }
  511. - (void)testOAuthLogin_LoginHint {
  512. _hint = kUserEmail;
  513. [self OAuthLoginWithAddScopesFlow:NO
  514. authError:nil
  515. tokenError:nil
  516. emmPasscodeInfoRequired:NO
  517. keychainError:NO
  518. restoredSignIn:NO
  519. oldAccessToken:NO
  520. modalCancel:NO];
  521. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  522. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  523. }
  524. - (void)testOAuthLogin_HostedDomain {
  525. _configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  526. serverClientID:nil
  527. hostedDomain:kHostedDomain
  528. openIDRealm:nil];
  529. [self OAuthLoginWithAddScopesFlow:NO
  530. authError:nil
  531. tokenError:nil
  532. emmPasscodeInfoRequired:NO
  533. keychainError:NO
  534. restoredSignIn:NO
  535. oldAccessToken:NO
  536. modalCancel:NO];
  537. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  538. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  539. }
  540. - (void)testOAuthLogin_ConsentCanceled {
  541. [self OAuthLoginWithAddScopesFlow:NO
  542. authError:@"access_denied"
  543. tokenError:nil
  544. emmPasscodeInfoRequired:NO
  545. keychainError:NO
  546. restoredSignIn:NO
  547. oldAccessToken:NO
  548. modalCancel:NO];
  549. [self waitForExpectationsWithTimeout:1 handler:nil];
  550. XCTAssertTrue(_callbackCalled, @"should call delegate");
  551. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  552. }
  553. - (void)testOAuthLogin_ModalCanceled {
  554. [self OAuthLoginWithAddScopesFlow:NO
  555. authError:nil
  556. tokenError:nil
  557. emmPasscodeInfoRequired:NO
  558. keychainError:NO
  559. restoredSignIn:NO
  560. oldAccessToken:NO
  561. modalCancel:YES];
  562. [self waitForExpectationsWithTimeout:1 handler:nil];
  563. XCTAssertTrue(_callbackCalled, @"should call delegate");
  564. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  565. }
  566. - (void)testOAuthLogin_KeychainError {
  567. [self OAuthLoginWithAddScopesFlow:NO
  568. authError:nil
  569. tokenError:nil
  570. emmPasscodeInfoRequired:NO
  571. keychainError:YES
  572. restoredSignIn:NO
  573. oldAccessToken:NO
  574. modalCancel:NO];
  575. [self waitForExpectationsWithTimeout:1 handler:nil];
  576. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  577. XCTAssertTrue(_callbackCalled, @"should call delegate");
  578. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  579. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  580. }
  581. - (void)testSignOut {
  582. // Sign in a user so that we can then sign them out.
  583. [self OAuthLoginWithAddScopesFlow:NO
  584. authError:nil
  585. tokenError:nil
  586. emmPasscodeInfoRequired:NO
  587. keychainError:NO
  588. restoredSignIn:YES
  589. oldAccessToken:NO
  590. modalCancel:NO];
  591. XCTAssertNotNil(_signIn.currentUser);
  592. [_signIn signOut];
  593. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  594. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  595. XCTAssertTrue([_changedKeyPaths containsObject:NSStringFromSelector(@selector(currentUser))],
  596. @"should notify observers that signed in user changed");
  597. }
  598. - (void)testNotHandleWrongScheme {
  599. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  600. @"should not handle URL");
  601. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  602. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  603. }
  604. - (void)testNotHandleWrongPath {
  605. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  606. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  607. XCTAssertFalse(_callbackCalled, @"should not call delegate");
  608. }
  609. #pragma mark - Tests - disconnectWithCallback:
  610. // Verifies disconnect calls callback with no errors if access token is present.
  611. - (void)testDisconnect_accessToken {
  612. [[[_authorization expect] andReturn:_authState] authState];
  613. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  614. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  615. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  616. XCTestExpectation *expectation =
  617. [self expectationWithDescription:@"Callback called with nil error"];
  618. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  619. if (error == nil) {
  620. [expectation fulfill];
  621. }
  622. }];
  623. [self verifyAndRevokeToken:kAccessToken hasCallback:YES];
  624. [_authorization verify];
  625. [_authState verify];
  626. [_tokenResponse verify];
  627. }
  628. // Verifies disconnect if access token is present.
  629. - (void)testDisconnectNoCallback_accessToken {
  630. [[[_authorization expect] andReturn:_authState] authState];
  631. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  632. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  633. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  634. [_signIn disconnectWithCallback:nil];
  635. [self verifyAndRevokeToken:kAccessToken hasCallback:NO];
  636. [_authorization verify];
  637. [_authState verify];
  638. [_tokenResponse verify];
  639. }
  640. // Verifies disconnect calls callback with no errors if refresh token is present.
  641. - (void)testDisconnect_refreshToken {
  642. [[[_authorization expect] andReturn:_authState] authState];
  643. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  644. [[[_tokenResponse expect] andReturn:nil] accessToken];
  645. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  646. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  647. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  648. XCTestExpectation *expectation =
  649. [self expectationWithDescription:@"Callback called with nil error"];
  650. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  651. if (error == nil) {
  652. [expectation fulfill];
  653. }
  654. }];
  655. [self verifyAndRevokeToken:kRefreshToken hasCallback:YES];
  656. [_authorization verify];
  657. [_authState verify];
  658. [_tokenResponse verify];
  659. }
  660. // Verifies disconnect errors are passed along to the callback.
  661. - (void)testDisconnect_errors {
  662. [[[_authorization expect] andReturn:_authState] authState];
  663. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  664. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  665. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  666. XCTestExpectation *expectation =
  667. [self expectationWithDescription:@"Callback called with an error"];
  668. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  669. if (error != nil) {
  670. [expectation fulfill];
  671. }
  672. }];
  673. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  674. // Emulate result back from server.
  675. NSError *error = [self error];
  676. [self didFetch:nil error:error];
  677. [self waitForExpectationsWithTimeout:1 handler:nil];
  678. [_authorization verify];
  679. [_authState verify];
  680. [_tokenResponse verify];
  681. }
  682. // Verifies disconnect with errors
  683. - (void)testDisconnectNoCallback_errors {
  684. [[[_authorization expect] andReturn:_authState] authState];
  685. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  686. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  687. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  688. [_signIn disconnectWithCallback:nil];
  689. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  690. // Emulate result back from server.
  691. NSError *error = [self error];
  692. [self didFetch:nil error:error];
  693. [_authorization verify];
  694. [_authState verify];
  695. [_tokenResponse verify];
  696. }
  697. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  698. - (void)testDisconnect_noTokens {
  699. [[[_authorization expect] andReturn:_authState] authState];
  700. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  701. [[[_tokenResponse expect] andReturn:nil] accessToken];
  702. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  703. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  704. XCTestExpectation *expectation =
  705. [self expectationWithDescription:@"Callback called with nil error"];
  706. [_signIn disconnectWithCallback:^(NSError * _Nullable error) {
  707. if (error == nil) {
  708. [expectation fulfill];
  709. }
  710. }];
  711. [self waitForExpectationsWithTimeout:1 handler:nil];
  712. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  713. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  714. [_authorization verify];
  715. [_authState verify];
  716. [_tokenResponse verify];
  717. }
  718. // Verifies disconnect clears keychain if no tokens are present.
  719. - (void)testDisconnectNoCallback_noTokens {
  720. [[[_authorization expect] andReturn:_authState] authState];
  721. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  722. [[[_tokenResponse expect] andReturn:nil] accessToken];
  723. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  724. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  725. [_signIn disconnectWithCallback:nil];
  726. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  727. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  728. [_authorization verify];
  729. [_authState verify];
  730. [_tokenResponse verify];
  731. }
  732. - (void)testPresentingViewControllerException {
  733. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  734. _presentingViewController = nil;
  735. #elif TARGET_OS_OSX
  736. _presentingWindow = nil;
  737. #endif
  738. XCTAssertThrows([_signIn signInWithConfiguration:_configuration
  739. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  740. presentingViewController:_presentingViewController
  741. #elif TARGET_OS_OSX
  742. presentingWindow:_presentingWindow
  743. #endif
  744. hint:_hint
  745. callback:_callback]);
  746. }
  747. - (void)testClientIDMissingException {
  748. #pragma GCC diagnostic push
  749. #pragma GCC diagnostic ignored "-Wnonnull"
  750. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  751. #pragma GCC diagnostic pop
  752. BOOL threw = NO;
  753. @try {
  754. [_signIn signInWithConfiguration:configuration
  755. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  756. presentingViewController:_presentingViewController
  757. #elif TARGET_OS_OSX
  758. presentingWindow:_presentingWindow
  759. #endif
  760. callback:nil];
  761. } @catch (NSException *exception) {
  762. threw = YES;
  763. XCTAssertEqualObjects(exception.description,
  764. @"You must specify |clientID| in |GIDConfiguration|");
  765. } @finally {
  766. }
  767. XCTAssert(threw);
  768. }
  769. - (void)testSchemesNotSupportedException {
  770. [_fakeMainBundle fakeMissingAllSchemes];
  771. BOOL threw = NO;
  772. @try {
  773. [_signIn signInWithConfiguration:_configuration
  774. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  775. presentingViewController:_presentingViewController
  776. #elif TARGET_OS_OSX
  777. presentingWindow:_presentingWindow
  778. #endif
  779. hint:_hint
  780. callback:_callback];
  781. } @catch (NSException *exception) {
  782. threw = YES;
  783. XCTAssertEqualObjects(exception.description,
  784. @"Your app is missing support for the following URL schemes: "
  785. "fakeclientid");
  786. } @finally {
  787. }
  788. XCTAssert(threw);
  789. }
  790. #pragma mark - Restarting Authentication Tests
  791. // Verifies that URL is not handled if there is no pending sign-in
  792. - (void)testRequiringPendingSignIn {
  793. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  794. XCTAssertFalse(result);
  795. }
  796. #pragma mark - EMM tests
  797. #if TARGET_OS_IOS
  798. - (void)testEmmSupportRequestParameters {
  799. [self OAuthLoginWithAddScopesFlow:NO
  800. authError:nil
  801. tokenError:nil
  802. emmPasscodeInfoRequired:NO
  803. keychainError:NO
  804. restoredSignIn:NO
  805. oldAccessToken:NO
  806. modalCancel:NO];
  807. NSString *systemName = [UIDevice currentDevice].systemName;
  808. if ([systemName isEqualToString:@"iPhone OS"]) {
  809. systemName = @"iOS";
  810. }
  811. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  812. systemName, [UIDevice currentDevice].systemVersion];
  813. NSDictionary<NSString *, NSObject *> *authParams =
  814. _savedAuthorizationRequest.additionalParameters;
  815. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  816. if (_isEligibleForEMM) {
  817. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  818. @"EMM support should match in auth request");
  819. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  820. @"OS version should match in auth request");
  821. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  822. @"EMM support should match in token request");
  823. XCTAssertEqualObjects(tokenParams[@"device_os"],
  824. expectedOSVersion,
  825. @"OS version should match in token request");
  826. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  827. @"no passcode info should be in token request");
  828. } else {
  829. XCTAssertNil(authParams[@"emm_support"],
  830. @"EMM support should not be in auth request for unsupported OS");
  831. XCTAssertNil(authParams[@"device_os"],
  832. @"OS version should not be in auth request for unsupported OS");
  833. XCTAssertNil(tokenParams[@"emm_support"],
  834. @"EMM support should not be in token request for unsupported OS");
  835. XCTAssertNil(tokenParams[@"device_os"],
  836. @"OS version should not be in token request for unsupported OS");
  837. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  838. @"passcode info should not be in token request for unsupported OS");
  839. }
  840. }
  841. - (void)testEmmPasscodeInfo {
  842. [self OAuthLoginWithAddScopesFlow:NO
  843. authError:nil
  844. tokenError:nil
  845. emmPasscodeInfoRequired:YES
  846. keychainError:NO
  847. restoredSignIn:NO
  848. oldAccessToken:NO
  849. modalCancel:NO];
  850. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  851. if (_isEligibleForEMM) {
  852. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  853. @"passcode info should be in token request");
  854. } else {
  855. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  856. @"passcode info should not be in token request for unsupported OS");
  857. }
  858. }
  859. - (void)testAuthEndpointEMMError {
  860. if (!_isEligibleForEMM) {
  861. return;
  862. }
  863. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  864. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  865. __block void (^completion)(void);
  866. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  867. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  868. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  869. [self OAuthLoginWithAddScopesFlow:NO
  870. authError:callbackParams[@"error"]
  871. tokenError:nil
  872. emmPasscodeInfoRequired:NO
  873. keychainError:NO
  874. restoredSignIn:NO
  875. oldAccessToken:NO
  876. modalCancel:NO];
  877. [mockEMMErrorHandler verify];
  878. [mockEMMErrorHandler stopMocking];
  879. completion();
  880. [self waitForExpectationsWithTimeout:1 handler:nil];
  881. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  882. XCTAssertTrue(_callbackCalled, @"should call delegate");
  883. XCTAssertNotNil(_authError, @"should have error");
  884. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  885. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  886. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  887. }
  888. - (void)testTokenEndpointEMMError {
  889. if (!_isEligibleForEMM) {
  890. return;
  891. }
  892. __block void (^completion)(NSError *);
  893. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  894. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  895. code:12345
  896. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  897. [[_authentication expect] handleTokenFetchEMMError:emmError
  898. completion:SAVE_TO_ARG_BLOCK(completion)];
  899. [self OAuthLoginWithAddScopesFlow:NO
  900. authError:nil
  901. tokenError:emmError
  902. emmPasscodeInfoRequired:NO
  903. keychainError:NO
  904. restoredSignIn:NO
  905. oldAccessToken:NO
  906. modalCancel:NO];
  907. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  908. code:kGIDSignInErrorCodeEMM
  909. userInfo:emmError.userInfo];
  910. completion(handledError);
  911. [self waitForExpectationsWithTimeout:1 handler:nil];
  912. [_authentication verify];
  913. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  914. XCTAssertTrue(_callbackCalled, @"should call delegate");
  915. XCTAssertNotNil(_authError, @"should have error");
  916. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  917. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  918. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  919. }
  920. #endif
  921. #pragma mark - Helpers
  922. // Whether or not a fetcher has been started.
  923. - (BOOL)isFetcherStarted {
  924. NSUInteger count = _fetcherService.fetchers.count;
  925. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  926. return !!count;
  927. }
  928. // Gets the URL being fetched.
  929. - (NSURL *)fetchedURL {
  930. return [_fetcherService.fetchers[0] requestURL];
  931. }
  932. // Emulates server returning the data as in JSON.
  933. - (void)didFetch:(id)dataObject error:(NSError *)error {
  934. NSData *data = nil;
  935. if (dataObject) {
  936. NSError *jsonError = nil;
  937. data = [NSJSONSerialization dataWithJSONObject:dataObject
  938. options:0
  939. error:&jsonError];
  940. XCTAssertNil(jsonError, @"must provide valid data");
  941. }
  942. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  943. }
  944. - (NSError *)error {
  945. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  946. }
  947. // Verifies a fetcher has started for revoking token and emulates a server response.
  948. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  949. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  950. NSURL *url = [self fetchedURL];
  951. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  952. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  953. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  954. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  955. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  956. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  957. @"token parameter should match");
  958. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  959. @"SDK version logging parameter should match");
  960. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  961. @"Environment logging parameter should match");
  962. // Emulate result back from server.
  963. [self didFetch:nil error:nil];
  964. if (hasCallback) {
  965. [self waitForExpectationsWithTimeout:1 handler:nil];
  966. }
  967. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  968. }
  969. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  970. authError:(NSString *)authError
  971. tokenError:(NSError *)tokenError
  972. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  973. keychainError:(BOOL)keychainError
  974. restoredSignIn:(BOOL)restoredSignIn
  975. oldAccessToken:(BOOL)oldAccessToken
  976. modalCancel:(BOOL)modalCancel {
  977. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  978. authError:authError
  979. tokenError:tokenError
  980. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  981. keychainError:keychainError
  982. restoredSignIn:restoredSignIn
  983. oldAccessToken:oldAccessToken
  984. modalCancel:modalCancel
  985. useAdditionalScopes:NO
  986. additionalScopes:nil];
  987. }
  988. // The authorization flow with parameters to control which branches to take.
  989. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  990. authError:(NSString *)authError
  991. tokenError:(NSError *)tokenError
  992. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  993. keychainError:(BOOL)keychainError
  994. restoredSignIn:(BOOL)restoredSignIn
  995. oldAccessToken:(BOOL)oldAccessToken
  996. modalCancel:(BOOL)modalCancel
  997. useAdditionalScopes:(BOOL)useAdditionalScopes
  998. additionalScopes:(NSArray *)additionalScopes {
  999. if (restoredSignIn) {
  1000. // clearAndAuthenticateWithOptions
  1001. [[[_authorization expect] andReturn:_authState] authState];
  1002. BOOL isAuthorized = restoredSignIn ? YES : NO;
  1003. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1004. }
  1005. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1006. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1007. OIDAuthorizationResponse *authResponse =
  1008. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1009. errorString:authError];
  1010. OIDTokenResponse *tokenResponse =
  1011. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1012. accessToken:restoredSignIn ? kAccessToken : nil
  1013. expiresIn:oldAccessToken ? @(300) : nil
  1014. tokenRequest:nil];
  1015. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1016. initWithConfiguration:authResponse.request.configuration
  1017. grantType:OIDGrantTypeRefreshToken
  1018. authorizationCode:nil
  1019. redirectURL:nil
  1020. clientID:authResponse.request.clientID
  1021. clientSecret:authResponse.request.clientSecret
  1022. scope:nil
  1023. refreshToken:kRefreshToken
  1024. codeVerifier:nil
  1025. additionalParameters:tokenResponse.request.additionalParameters];
  1026. if (restoredSignIn) {
  1027. // maybeFetchToken
  1028. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1029. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1030. if (oldAccessToken) {
  1031. #if TARGET_OS_IOS
  1032. // Corresponds to EMM support
  1033. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1034. #endif
  1035. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1036. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1037. [[[_authState expect] andReturn:tokenRequest]
  1038. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1039. }
  1040. } else {
  1041. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  1042. GIDSignInCallback callback = ^(GIDGoogleUser * _Nullable user, NSError * _Nullable error) {
  1043. [expectation fulfill];
  1044. if (!user) {
  1045. XCTAssertNotNil(error, @"should have an error if user is nil");
  1046. }
  1047. XCTAssertFalse(self->_callbackCalled, @"callback already called");
  1048. self->_callbackCalled = YES;
  1049. self->_authError = error;
  1050. };
  1051. if (addScopesFlow) {
  1052. [_signIn addScopes:@[kNewScope]
  1053. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1054. presentingViewController:_presentingViewController
  1055. #elif TARGET_OS_OSX
  1056. presentingWindow:_presentingWindow
  1057. #endif
  1058. callback:callback];
  1059. } else {
  1060. if (useAdditionalScopes) {
  1061. [_signIn signInWithConfiguration:_configuration
  1062. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1063. presentingViewController:_presentingViewController
  1064. #elif TARGET_OS_OSX
  1065. presentingWindow:_presentingWindow
  1066. #endif
  1067. hint:_hint
  1068. additionalScopes:additionalScopes
  1069. callback:callback];
  1070. } else {
  1071. [_signIn signInWithConfiguration:_configuration
  1072. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1073. presentingViewController:_presentingViewController
  1074. #elif TARGET_OS_OSX
  1075. presentingWindow:_presentingWindow
  1076. #endif
  1077. hint:_hint
  1078. callback:callback];
  1079. }
  1080. }
  1081. [_authorization verify];
  1082. [_authState verify];
  1083. XCTAssertNotNil(_savedAuthorizationRequest);
  1084. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1085. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1086. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1087. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1088. XCTAssertNotNil(_savedAuthorizationCallback);
  1089. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1090. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1091. #elif TARGET_OS_OSX
  1092. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1093. #endif
  1094. // maybeFetchToken
  1095. if (!(authError || modalCancel)) {
  1096. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1097. #if TARGET_OS_IOS
  1098. // Corresponds to EMM support
  1099. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1100. #endif
  1101. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1102. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1103. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1104. }
  1105. // Simulate auth endpoint response
  1106. if (modalCancel) {
  1107. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1108. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1109. userInfo:nil];
  1110. _savedAuthorizationCallback(nil, error);
  1111. } else {
  1112. _savedAuthorizationCallback(authResponse, nil);
  1113. }
  1114. if (authError || modalCancel) {
  1115. return;
  1116. }
  1117. [_authState verify];
  1118. }
  1119. if (restoredSignIn && oldAccessToken) {
  1120. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1121. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1122. NSError * _Nullable error) {
  1123. [expectation fulfill];
  1124. XCTAssertNil(error, @"should have no error");
  1125. }];
  1126. }
  1127. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1128. XCTAssertNotNil(_savedTokenRequest);
  1129. XCTAssertNotNil(_savedTokenCallback);
  1130. // OIDTokenCallback
  1131. if (tokenError) {
  1132. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1133. } else {
  1134. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1135. }
  1136. }
  1137. if (tokenError) {
  1138. _savedTokenCallback(nil, tokenError);
  1139. return;
  1140. }
  1141. // DecodeIdTokenCallback
  1142. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1143. // SaveAuthCallback
  1144. __block OIDAuthState *authState;
  1145. __block GIDProfileData *profileData;
  1146. if (keychainError) {
  1147. _saveAuthorizationReturnValue = NO;
  1148. } else {
  1149. if (addScopesFlow) {
  1150. [[_user expect] updateAuthState:SAVE_TO_ARG_BLOCK(authState)
  1151. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1152. } else {
  1153. [[[_user stub] andReturn:_user] alloc];
  1154. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1155. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1156. }
  1157. }
  1158. if (restoredSignIn && !oldAccessToken) {
  1159. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1160. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1161. NSError * _Nullable error) {
  1162. [expectation fulfill];
  1163. XCTAssertNil(error, @"should have no error");
  1164. }];
  1165. } else {
  1166. // Simulate token endpoint response.
  1167. _savedTokenCallback(tokenResponse, nil);
  1168. }
  1169. [_authState verify];
  1170. if (keychainError) {
  1171. return;
  1172. }
  1173. [self waitForExpectationsWithTimeout:1 handler:nil];
  1174. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1175. XCTAssertNotNil(authState);
  1176. // Check fat ID token decoding
  1177. XCTAssertEqualObjects(profileData.name, kFatName);
  1178. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1179. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1180. XCTAssertTrue(profileData.hasImage);
  1181. // If attempt to authenticate again, will reuse existing auth object.
  1182. _callbackCalled = NO;
  1183. _keychainRemoved = NO;
  1184. _keychainSaved = NO;
  1185. _authError = nil;
  1186. if (!addScopesFlow) {
  1187. [[[_user expect] andReturn:_authentication] authentication];
  1188. [[[_user expect] andReturn:_authentication] authentication];
  1189. }
  1190. __block GIDAuthenticationAction action;
  1191. [[_authentication expect] doWithFreshTokens:SAVE_TO_ARG_BLOCK(action)];
  1192. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1193. [_signIn restorePreviousSignInWithCallback:^(GIDGoogleUser * _Nullable user,
  1194. NSError * _Nullable error) {
  1195. [expectation fulfill];
  1196. XCTAssertNil(error, @"should have no error");
  1197. }];
  1198. action(_authentication, nil);
  1199. [self waitForExpectationsWithTimeout:1 handler:nil];
  1200. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1201. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1202. }
  1203. #pragma mark - Key Value Observing
  1204. - (void)observeValueForKeyPath:(NSString *)keyPath
  1205. ofObject:(id)object
  1206. change:(NSDictionary<NSKeyValueChangeKey, id> *)change
  1207. context:(void *)context {
  1208. if (context == kTestObserverContext && object == _signIn) {
  1209. [_changedKeyPaths addObject:keyPath];
  1210. }
  1211. }
  1212. @end