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