GIDSignInTest.m 54 KB

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