GIDSignInTest.m 56 KB

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