GIDSignInTest.m 47 KB

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