GIDSignInTest.m 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. GIDUserAuthCompletion _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 = ^(GIDUserAuth *_Nullable userAuth, NSError * _Nullable error) {
  254. GIDSignInTest *strongSelf = weakSelf;
  255. if (!userAuth) {
  256. XCTAssertNotNil(error, @"should have an error if the userAuth 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. }
  691. // Verifies disconnect with errors
  692. - (void)testDisconnectNoCallback_errors {
  693. [_keychainHandler saveAuthState:_authState];
  694. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  695. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  696. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  697. [_signIn disconnectWithCompletion:nil];
  698. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  699. // Emulate result back from server.
  700. NSError *error = [self error];
  701. [self didFetch:nil error:error];
  702. [_authorization verify];
  703. [_authState verify];
  704. [_tokenResponse verify];
  705. }
  706. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  707. - (void)testDisconnect_noTokens {
  708. [_keychainHandler saveAuthState:_authState];
  709. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  710. [[[_tokenResponse expect] andReturn:nil] accessToken];
  711. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  712. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  713. XCTestExpectation *expectation =
  714. [self expectationWithDescription:@"Callback called with nil error"];
  715. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  716. if (error == nil) {
  717. [expectation fulfill];
  718. }
  719. }];
  720. [self waitForExpectationsWithTimeout:1 handler:nil];
  721. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  722. [_authorization verify];
  723. [_authState verify];
  724. [_tokenResponse verify];
  725. XCTAssertNil([_keychainHandler loadAuthState]);
  726. }
  727. // Verifies disconnect clears keychain if no tokens are present.
  728. - (void)testDisconnectNoCallback_noTokens {
  729. [_keychainHandler saveAuthState:_authState];
  730. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  731. [[[_tokenResponse expect] andReturn:nil] accessToken];
  732. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  733. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  734. [_signIn disconnectWithCompletion:nil];
  735. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  736. [_authorization verify];
  737. [_authState verify];
  738. [_tokenResponse verify];
  739. XCTAssertNil([_keychainHandler loadAuthState]);
  740. }
  741. - (void)testPresentingViewControllerException {
  742. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  743. _presentingViewController = nil;
  744. #elif TARGET_OS_OSX
  745. _presentingWindow = nil;
  746. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  747. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  748. XCTAssertThrows([_signIn signInWithPresentingViewController:_presentingViewController
  749. #elif TARGET_OS_OSX
  750. XCTAssertThrows([_signIn signInWithPresentingWindow:_presentingWindow
  751. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  752. hint:_hint
  753. completion:_completion]);
  754. }
  755. - (void)testClientIDMissingException {
  756. #pragma GCC diagnostic push
  757. #pragma GCC diagnostic ignored "-Wnonnull"
  758. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  759. #pragma GCC diagnostic pop
  760. BOOL threw = NO;
  761. @try {
  762. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  763. [_signIn signInWithPresentingViewController:_presentingViewController
  764. #elif TARGET_OS_OSX
  765. [_signIn signInWithPresentingWindow:_presentingWindow
  766. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  767. completion:nil];
  768. } @catch (NSException *exception) {
  769. threw = YES;
  770. XCTAssertEqualObjects(exception.description,
  771. @"You must specify |clientID| in |GIDConfiguration|");
  772. } @finally {
  773. }
  774. XCTAssert(threw);
  775. }
  776. - (void)testSchemesNotSupportedException {
  777. [_fakeMainBundle fakeMissingAllSchemes];
  778. BOOL threw = NO;
  779. @try {
  780. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  781. [_signIn signInWithPresentingViewController:_presentingViewController
  782. #elif TARGET_OS_OSX
  783. [_signIn signInWithPresentingWindow:_presentingWindow
  784. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  785. hint:_hint
  786. completion:_completion];
  787. } @catch (NSException *exception) {
  788. threw = YES;
  789. XCTAssertEqualObjects(exception.description,
  790. @"Your app is missing support for the following URL schemes: "
  791. "fakeclientid");
  792. } @finally {
  793. }
  794. XCTAssert(threw);
  795. }
  796. #pragma mark - Restarting Authentication Tests
  797. // Verifies that URL is not handled if there is no pending sign-in
  798. - (void)testRequiringPendingSignIn {
  799. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  800. XCTAssertFalse(result);
  801. }
  802. #pragma mark - EMM tests
  803. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  804. - (void)testEmmSupportRequestParameters {
  805. [self OAuthLoginWithAddScopesFlow:NO
  806. authError:nil
  807. tokenError:nil
  808. emmPasscodeInfoRequired:NO
  809. keychainError:NO
  810. restoredSignIn:NO
  811. oldAccessToken:NO
  812. modalCancel:NO];
  813. NSString *systemName = [UIDevice currentDevice].systemName;
  814. if ([systemName isEqualToString:@"iPhone OS"]) {
  815. systemName = @"iOS";
  816. }
  817. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  818. systemName, [UIDevice currentDevice].systemVersion];
  819. NSDictionary<NSString *, NSObject *> *authParams =
  820. _savedAuthorizationRequest.additionalParameters;
  821. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  822. if (_isEligibleForEMM) {
  823. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  824. @"EMM support should match in auth request");
  825. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  826. @"OS version should match in auth request");
  827. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  828. @"EMM support should match in token request");
  829. XCTAssertEqualObjects(tokenParams[@"device_os"],
  830. expectedOSVersion,
  831. @"OS version should match in token request");
  832. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  833. @"no passcode info should be in token request");
  834. } else {
  835. XCTAssertNil(authParams[@"emm_support"],
  836. @"EMM support should not be in auth request for unsupported OS");
  837. XCTAssertNil(authParams[@"device_os"],
  838. @"OS version should not be in auth request for unsupported OS");
  839. XCTAssertNil(tokenParams[@"emm_support"],
  840. @"EMM support should not be in token request for unsupported OS");
  841. XCTAssertNil(tokenParams[@"device_os"],
  842. @"OS version should not be in token request for unsupported OS");
  843. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  844. @"passcode info should not be in token request for unsupported OS");
  845. }
  846. }
  847. - (void)testEmmPasscodeInfo {
  848. [self OAuthLoginWithAddScopesFlow:NO
  849. authError:nil
  850. tokenError:nil
  851. emmPasscodeInfoRequired:YES
  852. keychainError:NO
  853. restoredSignIn:NO
  854. oldAccessToken:NO
  855. modalCancel:NO];
  856. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  857. if (_isEligibleForEMM) {
  858. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  859. @"passcode info should be in token request");
  860. } else {
  861. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  862. @"passcode info should not be in token request for unsupported OS");
  863. }
  864. }
  865. - (void)testAuthEndpointEMMError {
  866. if (!_isEligibleForEMM) {
  867. return;
  868. }
  869. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  870. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  871. __block void (^completion)(void);
  872. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  873. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  874. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  875. [self OAuthLoginWithAddScopesFlow:NO
  876. authError:callbackParams[@"error"]
  877. tokenError:nil
  878. emmPasscodeInfoRequired:NO
  879. keychainError:NO
  880. restoredSignIn:NO
  881. oldAccessToken:NO
  882. modalCancel:NO];
  883. [mockEMMErrorHandler verify];
  884. [mockEMMErrorHandler stopMocking];
  885. completion();
  886. [self waitForExpectationsWithTimeout:1 handler:nil];
  887. XCTAssertTrue(_completionCalled, @"should call delegate");
  888. XCTAssertNotNil(_authError, @"should have error");
  889. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  890. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  891. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  892. }
  893. - (void)testTokenEndpointEMMError {
  894. if (!_isEligibleForEMM) {
  895. return;
  896. }
  897. __block void (^completion)(NSError *);
  898. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  899. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  900. code:12345
  901. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  902. id emmSupport = OCMStrictClassMock([GIDEMMSupport class]);
  903. [[emmSupport expect] handleTokenFetchEMMError:emmError
  904. completion:SAVE_TO_ARG_BLOCK(completion)];
  905. [self OAuthLoginWithAddScopesFlow:NO
  906. authError:nil
  907. tokenError:emmError
  908. emmPasscodeInfoRequired:NO
  909. keychainError:NO
  910. restoredSignIn:NO
  911. oldAccessToken:NO
  912. modalCancel:NO];
  913. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  914. code:kGIDSignInErrorCodeEMM
  915. userInfo:emmError.userInfo];
  916. completion(handledError);
  917. [self waitForExpectationsWithTimeout:1 handler:nil];
  918. [emmSupport verify];
  919. XCTAssertTrue(_completionCalled, @"should call delegate");
  920. XCTAssertNotNil(_authError, @"should have error");
  921. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  922. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  923. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  924. }
  925. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  926. #pragma mark - Helpers
  927. // Whether or not a fetcher has been started.
  928. - (BOOL)isFetcherStarted {
  929. NSUInteger count = _fetcherService.fetchers.count;
  930. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  931. return !!count;
  932. }
  933. // Gets the URL being fetched.
  934. - (NSURL *)fetchedURL {
  935. return [_fetcherService.fetchers[0] requestURL];
  936. }
  937. // Emulates server returning the data as in JSON.
  938. - (void)didFetch:(id)dataObject error:(NSError *)error {
  939. NSData *data = nil;
  940. if (dataObject) {
  941. NSError *jsonError = nil;
  942. data = [NSJSONSerialization dataWithJSONObject:dataObject
  943. options:0
  944. error:&jsonError];
  945. XCTAssertNil(jsonError, @"must provide valid data");
  946. }
  947. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  948. }
  949. - (NSError *)error {
  950. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  951. }
  952. // Verifies a fetcher has started for revoking token and emulates a server response.
  953. - (void)verifyAndRevokeToken:(NSString *)token hasCallback:(BOOL)hasCallback {
  954. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  955. NSURL *url = [self fetchedURL];
  956. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  957. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  958. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  959. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  960. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  961. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  962. @"token parameter should match");
  963. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  964. @"SDK version logging parameter should match");
  965. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  966. @"Environment logging parameter should match");
  967. // Emulate result back from server.
  968. [self didFetch:nil error:nil];
  969. if (hasCallback) {
  970. [self waitForExpectationsWithTimeout:1 handler:nil];
  971. }
  972. }
  973. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  974. authError:(NSString *)authError
  975. tokenError:(NSError *)tokenError
  976. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  977. keychainError:(BOOL)keychainError
  978. restoredSignIn:(BOOL)restoredSignIn
  979. oldAccessToken:(BOOL)oldAccessToken
  980. modalCancel:(BOOL)modalCancel {
  981. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  982. authError:authError
  983. tokenError:tokenError
  984. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  985. keychainError:keychainError
  986. restoredSignIn:restoredSignIn
  987. oldAccessToken:oldAccessToken
  988. modalCancel:modalCancel
  989. useAdditionalScopes:NO
  990. additionalScopes:nil];
  991. }
  992. // The authorization flow with parameters to control which branches to take.
  993. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  994. authError:(NSString *)authError
  995. tokenError:(NSError *)tokenError
  996. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  997. keychainError:(BOOL)keychainError
  998. restoredSignIn:(BOOL)restoredSignIn
  999. oldAccessToken:(BOOL)oldAccessToken
  1000. modalCancel:(BOOL)modalCancel
  1001. useAdditionalScopes:(BOOL)useAdditionalScopes
  1002. additionalScopes:(NSArray *)additionalScopes {
  1003. if (restoredSignIn) {
  1004. // clearAndAuthenticateWithOptions
  1005. [_keychainHandler saveAuthState:_authState];
  1006. BOOL isAuthorized = restoredSignIn ? YES : NO;
  1007. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1008. }
  1009. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1010. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1011. OIDAuthorizationResponse *authResponse =
  1012. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1013. errorString:authError];
  1014. OIDTokenResponse *tokenResponse =
  1015. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1016. accessToken:restoredSignIn ? kAccessToken : nil
  1017. expiresIn:oldAccessToken ? @(300) : nil
  1018. refreshToken:kRefreshToken
  1019. tokenRequest:nil];
  1020. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1021. initWithConfiguration:authResponse.request.configuration
  1022. grantType:OIDGrantTypeRefreshToken
  1023. authorizationCode:nil
  1024. redirectURL:nil
  1025. clientID:authResponse.request.clientID
  1026. clientSecret:authResponse.request.clientSecret
  1027. scope:nil
  1028. refreshToken:kRefreshToken
  1029. codeVerifier:nil
  1030. additionalParameters:tokenResponse.request.additionalParameters];
  1031. if (restoredSignIn) {
  1032. // maybeFetchToken
  1033. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1034. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1035. if (oldAccessToken) {
  1036. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1037. // Corresponds to EMM support
  1038. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1039. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1040. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1041. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1042. [[[_authState expect] andReturn:tokenRequest]
  1043. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1044. }
  1045. } else {
  1046. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback called"];
  1047. GIDUserAuthCompletion completion =
  1048. ^(GIDUserAuth *_Nullable userAuth, NSError * _Nullable error) {
  1049. [expectation fulfill];
  1050. if (userAuth) {
  1051. XCTAssertEqualObjects(userAuth.serverAuthCode, kServerAuthCode);
  1052. } else {
  1053. XCTAssertNotNil(error, @"Should have an error if the userAuth is nil");
  1054. }
  1055. XCTAssertFalse(self->_completionCalled, @"callback already called");
  1056. self->_completionCalled = YES;
  1057. self->_authError = error;
  1058. };
  1059. if (addScopesFlow) {
  1060. [_signIn addScopes:@[kNewScope]
  1061. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1062. presentingViewController:_presentingViewController
  1063. #elif TARGET_OS_OSX
  1064. presentingWindow:_presentingWindow
  1065. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1066. completion:completion];
  1067. } else {
  1068. if (useAdditionalScopes) {
  1069. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1070. [_signIn signInWithPresentingViewController:_presentingViewController
  1071. #elif TARGET_OS_OSX
  1072. [_signIn signInWithPresentingWindow:_presentingWindow
  1073. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1074. hint:_hint
  1075. additionalScopes:additionalScopes
  1076. completion:completion];
  1077. } else {
  1078. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1079. [_signIn signInWithPresentingViewController:_presentingViewController
  1080. #elif TARGET_OS_OSX
  1081. [_signIn signInWithPresentingWindow:_presentingWindow
  1082. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1083. hint:_hint
  1084. completion:completion];
  1085. }
  1086. }
  1087. [_authState verify];
  1088. XCTAssertNotNil(_savedAuthorizationRequest);
  1089. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1090. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1091. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1092. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1093. XCTAssertNotNil(_savedAuthorizationCallback);
  1094. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1095. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1096. #elif TARGET_OS_OSX
  1097. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1098. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1099. // maybeFetchToken
  1100. if (!(authError || modalCancel)) {
  1101. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1102. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1103. // Corresponds to EMM support
  1104. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1105. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1106. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1107. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1108. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1109. }
  1110. // Simulate auth endpoint response
  1111. if (modalCancel) {
  1112. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1113. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1114. userInfo:nil];
  1115. _savedAuthorizationCallback(nil, error);
  1116. } else {
  1117. _savedAuthorizationCallback(authResponse, nil);
  1118. }
  1119. if (authError || modalCancel) {
  1120. return;
  1121. }
  1122. [_authState verify];
  1123. }
  1124. if (restoredSignIn && oldAccessToken) {
  1125. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1126. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1127. NSError * _Nullable error) {
  1128. [expectation fulfill];
  1129. XCTAssertNil(error, @"should have no error");
  1130. }];
  1131. }
  1132. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1133. XCTAssertNotNil(_savedTokenRequest);
  1134. XCTAssertNotNil(_savedTokenCallback);
  1135. // OIDTokenCallback
  1136. if (tokenError) {
  1137. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1138. } else {
  1139. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1140. }
  1141. }
  1142. if (tokenError) {
  1143. _savedTokenCallback(nil, tokenError);
  1144. return;
  1145. }
  1146. // DecodeIdTokenCallback
  1147. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1148. // SaveAuthCallback
  1149. __block OIDAuthState *authState;
  1150. __block OIDTokenResponse *updatedTokenResponse;
  1151. __block OIDAuthorizationResponse *updatedAuthorizationResponse;
  1152. __block GIDProfileData *profileData;
  1153. if (keychainError) {
  1154. _keychainHandler.failToSave = YES;
  1155. } else {
  1156. if (addScopesFlow) {
  1157. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1158. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1159. [[_user expect] updateWithTokenResponse:SAVE_TO_ARG_BLOCK(updatedTokenResponse)
  1160. authorizationResponse:SAVE_TO_ARG_BLOCK(updatedAuthorizationResponse)
  1161. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1162. } else {
  1163. [[[_user stub] andReturn:_user] alloc];
  1164. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1165. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1166. }
  1167. }
  1168. // CompletionCallback - mock server auth code parsing
  1169. if (!keychainError) {
  1170. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1171. }
  1172. if (restoredSignIn && !oldAccessToken) {
  1173. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1174. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1175. NSError * _Nullable error) {
  1176. [expectation fulfill];
  1177. XCTAssertNil(error, @"should have no error");
  1178. }];
  1179. } else {
  1180. // Simulate token endpoint response.
  1181. _savedTokenCallback(tokenResponse, nil);
  1182. }
  1183. if (keychainError) {
  1184. return;
  1185. }
  1186. [self waitForExpectationsWithTimeout:1 handler:nil];
  1187. [_authState verify];
  1188. if (addScopesFlow) {
  1189. XCTAssertNotNil(updatedTokenResponse);
  1190. XCTAssertNotNil(updatedAuthorizationResponse);
  1191. } else {
  1192. XCTAssertNotNil(authState);
  1193. }
  1194. // Check fat ID token decoding
  1195. XCTAssertEqualObjects(profileData.name, kFatName);
  1196. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1197. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1198. XCTAssertTrue(profileData.hasImage);
  1199. // If attempt to authenticate again, will reuse existing auth object.
  1200. _completionCalled = NO;
  1201. _authError = nil;
  1202. __block GIDGoogleUserCompletion completion;
  1203. [[_user expect] refreshTokensIfNeededWithCompletion:SAVE_TO_ARG_BLOCK(completion)];
  1204. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called"];
  1205. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1206. NSError * _Nullable error) {
  1207. [expectation fulfill];
  1208. XCTAssertNil(error, @"should have no error");
  1209. }];
  1210. completion(_user, nil);
  1211. [self waitForExpectationsWithTimeout:1 handler:nil];
  1212. }
  1213. @end