GIDSignInTest.m 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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 GTMAppAuth;
  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. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  30. #import <AppCheckCore/GACAppCheckToken.h>
  31. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/GIDAppCheck.h"
  32. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/Fake/GIDAppCheckProviderFake.h"
  33. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  34. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  35. #import "GoogleSignIn/Sources/GIDAuthStateMigration/Fake/GIDFakeAuthStateMigration.h"
  36. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
  37. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
  38. #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.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 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 <GTMSessionFetcher/GTMSessionFetcher.h>
  61. #import <OCMock/OCMock.h>
  62. #endif
  63. // Create a BLOCK to store the actual address for arg in param.
  64. #define SAVE_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  65. param = arg;\
  66. return YES;\
  67. }]
  68. #define COPY_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  69. param = [arg copy];\
  70. return YES;\
  71. }]
  72. /// `NSUserDefaults` suite name for testing with `GIDAppCheck`.
  73. static NSString *const kUserDefaultsSuiteName = @"GIDAppCheckKeySuiteName";
  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 |GTMAuthSession|.
  162. id _authorization;
  163. // Mock |GTMKeychainStore|.
  164. id _keychainStore;
  165. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  166. // Mock |UIViewController|.
  167. id _presentingViewController;
  168. #elif TARGET_OS_OSX
  169. // Mock |NSWindow|.
  170. id _presentingWindow;
  171. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  172. // Mock for |GIDGoogleUser|.
  173. id _user;
  174. // Mock for |OIDAuthorizationService|
  175. id _oidAuthorizationService;
  176. // Parameter saved from delegate call.
  177. NSError *_authError;
  178. // Whether callback block has been called.
  179. BOOL _completionCalled;
  180. // Fake for |GIDAuthStateMigration|.
  181. GIDFakeAuthStateMigration *_authStateMigrationService;
  182. // Fake fetcher service to emulate network requests.
  183. GIDFakeFetcherService *_fetcherService;
  184. // Fake [NSBundle mainBundle];
  185. GIDFakeMainBundle *_fakeMainBundle;
  186. // Whether |saveParamsToKeychainForName:authentication:| has been called.
  187. BOOL _keychainSaved;
  188. // Whether |removeAuthFromKeychainForName:| has been called.
  189. BOOL _keychainRemoved;
  190. // The |GIDSignIn| object being tested.
  191. GIDSignIn *_signIn;
  192. // The configuration to be used when testing |GIDSignIn|.
  193. GIDConfiguration *_configuration;
  194. // The login hint to be used when testing |GIDSignIn|.
  195. NSString *_hint;
  196. // The completion to be used when testing |GIDSignIn|.
  197. GIDSignInCompletion _completion;
  198. // The saved authorization request.
  199. OIDAuthorizationRequest *_savedAuthorizationRequest;
  200. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  201. // The saved presentingViewController from the authorization request.
  202. UIViewController *_savedPresentingViewController;
  203. #elif TARGET_OS_OSX
  204. // The saved presentingWindow from the authorization request.
  205. NSWindow *_savedPresentingWindow;
  206. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  207. // The saved authorization callback.
  208. OIDAuthorizationCallback _savedAuthorizationCallback;
  209. // The saved token request.
  210. OIDTokenRequest *_savedTokenRequest;
  211. // The saved token request callback.
  212. OIDTokenCallback _savedTokenCallback;
  213. // Status returned by saveAuthorization:toKeychainForName:
  214. BOOL _saveAuthorizationReturnValue;
  215. // Test userDefaults for use with `GIDAppCheck`
  216. NSUserDefaults *_testUserDefaults;
  217. }
  218. @end
  219. @implementation GIDSignInTest
  220. #pragma mark - Lifecycle
  221. - (void)setUp {
  222. [super setUp];
  223. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  224. _isEligibleForEMM = [UIDevice currentDevice].systemVersion.integerValue >= 9;
  225. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  226. _saveAuthorizationReturnValue = YES;
  227. // States
  228. _completionCalled = NO;
  229. _keychainSaved = NO;
  230. _keychainRemoved = NO;
  231. // Mocks
  232. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  233. _presentingViewController = OCMStrictClassMock([UIViewController class]);
  234. #elif TARGET_OS_OSX
  235. _presentingWindow = OCMStrictClassMock([NSWindow class]);
  236. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  237. _authState = OCMClassMock([OIDAuthState class]);
  238. OCMStub([_authState alloc]).andReturn(_authState);
  239. OCMStub([_authState initWithAuthorizationResponse:OCMOCK_ANY]).andReturn(_authState);
  240. _tokenResponse = OCMStrictClassMock([OIDTokenResponse class]);
  241. _tokenRequest = OCMStrictClassMock([OIDTokenRequest class]);
  242. _authorization = OCMStrictClassMock([GTMAuthSession class]);
  243. _keychainStore = OCMStrictClassMock([GTMKeychainStore class]);
  244. OCMStub(
  245. [_keychainStore retrieveAuthSessionWithItemName:OCMOCK_ANY error:OCMArg.anyObjectRef]
  246. ).andReturn(_authorization);
  247. OCMStub([_keychainStore retrieveAuthSessionWithError:nil]).andReturn(_authorization);
  248. OCMStub([_authorization alloc]).andReturn(_authorization);
  249. OCMStub([_authorization initWithAuthState:OCMOCK_ANY]).andReturn(_authorization);
  250. OCMStub(
  251. [_keychainStore removeAuthSessionWithError:OCMArg.anyObjectRef]
  252. ).andDo(^(NSInvocation *invocation) {
  253. self->_keychainRemoved = YES;
  254. });
  255. _user = OCMStrictClassMock([GIDGoogleUser class]);
  256. _oidAuthorizationService = OCMStrictClassMock([OIDAuthorizationService class]);
  257. OCMStub([_oidAuthorizationService
  258. presentAuthorizationRequest:SAVE_TO_ARG_BLOCK(self->_savedAuthorizationRequest)
  259. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  260. presentingViewController:SAVE_TO_ARG_BLOCK(self->_savedPresentingViewController)
  261. #elif TARGET_OS_OSX
  262. presentingWindow:SAVE_TO_ARG_BLOCK(self->_savedPresentingWindow)
  263. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  264. callback:COPY_TO_ARG_BLOCK(self->_savedAuthorizationCallback)]);
  265. OCMStub([self->_oidAuthorizationService
  266. performTokenRequest:SAVE_TO_ARG_BLOCK(self->_savedTokenRequest)
  267. originalAuthorizationResponse:[OCMArg any]
  268. callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
  269. // Fakes
  270. _authStateMigrationService = [[GIDFakeAuthStateMigration alloc] init];
  271. _fetcherService = [[GIDFakeFetcherService alloc] init];
  272. _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
  273. [_fakeMainBundle startFakingWithClientID:kClientId];
  274. [_fakeMainBundle fakeAllSchemesSupported];
  275. // Object under test
  276. _testUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:kUserDefaultsSuiteName];
  277. [_testUserDefaults setBool:YES forKey:kAppHasRunBeforeKey];
  278. _signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  279. authStateMigrationService:_authStateMigrationService];
  280. _hint = nil;
  281. __weak GIDSignInTest *weakSelf = self;
  282. _completion = ^(GIDSignInResult *_Nullable signInResult, NSError * _Nullable error) {
  283. GIDSignInTest *strongSelf = weakSelf;
  284. if (!signInResult) {
  285. XCTAssertNotNil(error, @"should have an error if the signInResult is nil");
  286. }
  287. XCTAssertFalse(strongSelf->_completionCalled, @"callback already called");
  288. strongSelf->_completionCalled = YES;
  289. strongSelf->_authError = error;
  290. };
  291. }
  292. - (void)tearDown {
  293. OCMVerifyAll(_authState);
  294. OCMVerifyAll(_tokenResponse);
  295. OCMVerifyAll(_tokenRequest);
  296. OCMVerifyAll(_authorization);
  297. OCMVerifyAll(_user);
  298. OCMVerifyAll(_oidAuthorizationService);
  299. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  300. OCMVerifyAll(_presentingViewController);
  301. #elif TARGET_OS_OSX
  302. OCMVerifyAll(_presentingWindow);
  303. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  304. [_testUserDefaults removePersistentDomainForName:kUserDefaultsSuiteName];
  305. [_fakeMainBundle stopFaking];
  306. [super tearDown];
  307. }
  308. #pragma mark - Tests
  309. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  310. - (void)testConfigureSucceeds {
  311. if (@available(iOS 14, *)) {
  312. XCTestExpectation *configureSucceedsExpecation =
  313. [self expectationWithDescription:@"Configure succeeds expectation"];
  314. GACAppCheckToken *token = [[GACAppCheckToken alloc] initWithToken:@"foo"
  315. expirationDate:[NSDate distantFuture]];
  316. GIDAppCheckProviderFake *fakeProvider =
  317. [[GIDAppCheckProviderFake alloc] initWithAppCheckToken:token error:nil];
  318. GIDAppCheck *appCheck = [[GIDAppCheck alloc] initWithAppCheckProvider:fakeProvider
  319. userDefaults:_testUserDefaults];
  320. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  321. authStateMigrationService:_authStateMigrationService
  322. appCheck:appCheck];
  323. [signIn configureWithCompletion:^(NSError * _Nullable error) {
  324. XCTAssertNil(error);
  325. [configureSucceedsExpecation fulfill];
  326. }];
  327. [self waitForExpectations:@[configureSucceedsExpecation] timeout:1];
  328. XCTAssertTrue(appCheck.isPrepared);
  329. }
  330. }
  331. - (void)testConfigureFailsNoTokenOrError {
  332. if (@available(iOS 14, *)) {
  333. XCTestExpectation *configureFailsExpecation =
  334. [self expectationWithDescription:@"Configure fails expectation"];
  335. GIDAppCheckProviderFake *fakeProvider =
  336. [[GIDAppCheckProviderFake alloc] initWithAppCheckToken:nil error:nil];
  337. GIDAppCheck *appCheck =
  338. [[GIDAppCheck alloc] initWithAppCheckProvider:fakeProvider
  339. userDefaults:_testUserDefaults];
  340. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  341. authStateMigrationService:_authStateMigrationService
  342. appCheck:appCheck];
  343. // Should fail if missing both token and error
  344. [signIn configureWithCompletion:^(NSError * _Nullable error) {
  345. XCTAssertNotNil(error);
  346. XCTAssertEqual(error.code, kGIDAppCheckUnexpectedError);
  347. [configureFailsExpecation fulfill];
  348. }];
  349. [self waitForExpectations:@[configureFailsExpecation] timeout:1];
  350. XCTAssertFalse(appCheck.isPrepared);
  351. }
  352. }
  353. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  354. - (void)testInitWithKeychainStore {
  355. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  356. GIDSignIn *signIn;
  357. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  358. authStateMigrationService:_authStateMigrationService];
  359. XCTAssertNotNil(signIn.configuration);
  360. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  361. XCTAssertNil(signIn.configuration.serverClientID);
  362. XCTAssertNil(signIn.configuration.hostedDomain);
  363. XCTAssertNil(signIn.configuration.openIDRealm);
  364. }
  365. - (void)testInitWithKeychainStore_noConfig {
  366. [_fakeMainBundle fakeWithClientID:nil
  367. serverClientID:nil
  368. hostedDomain:nil
  369. openIDRealm:nil];
  370. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  371. GIDSignIn *signIn;
  372. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  373. authStateMigrationService:_authStateMigrationService];
  374. XCTAssertNil(signIn.configuration);
  375. }
  376. - (void)testInitWithKeychainStore_fullConfig {
  377. [_fakeMainBundle fakeWithClientID:kClientId
  378. serverClientID:kServerClientId
  379. hostedDomain:kFakeHostedDomain
  380. openIDRealm:kOpenIDRealm];
  381. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  382. GIDSignIn *signIn;
  383. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  384. authStateMigrationService:_authStateMigrationService];
  385. XCTAssertNotNil(signIn.configuration);
  386. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  387. XCTAssertEqual(signIn.configuration.serverClientID, kServerClientId);
  388. XCTAssertEqual(signIn.configuration.hostedDomain, kFakeHostedDomain);
  389. XCTAssertEqual(signIn.configuration.openIDRealm, kOpenIDRealm);
  390. }
  391. - (void)testInitWithKeychainStore_invalidConfig {
  392. [_fakeMainBundle fakeWithClientID:@[ @"bad", @"config", @"values" ]
  393. serverClientID:nil
  394. hostedDomain:nil
  395. openIDRealm:nil];
  396. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  397. GIDSignIn *signIn;
  398. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  399. authStateMigrationService:_authStateMigrationService];
  400. XCTAssertNil(signIn.configuration);
  401. }
  402. - (void)testInitWithKeychainStore_attemptsMigration {
  403. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  404. _authStateMigrationService.migrationInvokedCallback =
  405. ^(NSURL *tokenURL, NSString *callbackPath, BOOL isFreshInstall) {
  406. XCTAssertFalse(isFreshInstall);
  407. [expectation fulfill];
  408. };
  409. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:kKeychainName];
  410. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  411. authStateMigrationService:_authStateMigrationService];
  412. XCTAssertNotNil(signIn.configuration);
  413. [self waitForExpectationsWithTimeout:1 handler:nil];
  414. }
  415. - (void)testRestorePreviousSignInNoRefresh_hasPreviousUser {
  416. [[[_authorization stub] andReturn:_authState] authState];
  417. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  418. [[_authorization expect] setDelegate:OCMOCK_ANY];
  419. #endif // TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  420. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  421. OCMStub([_authState refreshToken]).andReturn(kRefreshToken);
  422. [[_authState expect] setStateChangeDelegate:OCMOCK_ANY];
  423. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  424. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  425. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  426. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  427. // Mock generating a GIDConfiguration when initializing GIDGoogleUser.
  428. OIDAuthorizationResponse *authResponse =
  429. [OIDAuthorizationResponse testInstance];
  430. OCMStub([_authState lastAuthorizationResponse]).andReturn(authResponse);
  431. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  432. OCMStub([_tokenResponse request]).andReturn(_tokenRequest);
  433. OCMStub([_tokenRequest additionalParameters]).andReturn(nil);
  434. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  435. OCMStub([_tokenResponse accessTokenExpirationDate]).andReturn(nil);
  436. [_signIn restorePreviousSignInNoRefresh];
  437. [idTokenDecoded verify];
  438. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  439. [idTokenDecoded stopMocking];
  440. }
  441. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  442. [[[_authorization expect] andReturn:nil] authState];
  443. [_signIn restorePreviousSignInNoRefresh];
  444. [_authorization verify];
  445. XCTAssertNil(_signIn.currentUser);
  446. }
  447. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  448. [[[_authorization expect] andReturn:_authState] authState];
  449. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  450. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  451. [_authorization verify];
  452. [_authState verify];
  453. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  454. XCTAssertFalse(_completionCalled, @"should not call delegate");
  455. XCTAssertNil(_authError, @"should have no error");
  456. }
  457. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  458. [[[_authorization expect] andReturn:_authState] authState];
  459. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  460. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  461. [_authorization verify];
  462. [_authState verify];
  463. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  464. XCTAssertFalse(_completionCalled, @"should not call delegate");
  465. }
  466. - (void)testRestorePreviousSignInWhenSignedOut {
  467. [[[_authorization expect] andReturn:_authState] authState];
  468. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  469. _completionCalled = NO;
  470. _authError = nil;
  471. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  472. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser *_Nullable user,
  473. NSError * _Nullable error) {
  474. [expectation fulfill];
  475. XCTAssertNotNil(error, @"error should not have been nil");
  476. XCTAssertEqual(error.domain,
  477. kGIDSignInErrorDomain,
  478. @"error domain should have been the sign-in error domain.");
  479. XCTAssertEqual(error.code,
  480. kGIDSignInErrorCodeHasNoAuthInKeychain,
  481. @"error code should have been the 'NoAuthInKeychain' error code.");
  482. }];
  483. [self waitForExpectationsWithTimeout:1 handler:nil];
  484. [_authorization verify];
  485. [_authState verify];
  486. }
  487. - (void)testNotRestorePreviousSignInWhenSignedOutAndCompletionIsNil {
  488. [[[_authorization expect] andReturn:_authState] authState];
  489. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  490. [_signIn restorePreviousSignInWithCompletion:nil];
  491. XCTAssertNil(_signIn.currentUser);
  492. }
  493. - (void)testRestorePreviousSignInWhenCompletionIsNil {
  494. [[[_authorization expect] andReturn:_authState] authState];
  495. [[_keychainStore expect] saveAuthSession:OCMOCK_ANY error:[OCMArg anyObjectRef]];
  496. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  497. OIDTokenResponse *tokenResponse =
  498. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  499. accessToken:kAccessToken
  500. expiresIn:nil
  501. refreshToken:kRefreshToken
  502. tokenRequest:nil];
  503. [[[_authState stub] andReturn:tokenResponse] lastTokenResponse];
  504. // TODO: Create a real GIDGoogleUser to verify the signed in user value(#306).
  505. [[[_user stub] andReturn:_user] alloc];
  506. (void)[[[_user expect] andReturn:_user] initWithAuthState:OCMOCK_ANY
  507. profileData:OCMOCK_ANY];
  508. XCTAssertNil(_signIn.currentUser);
  509. [_signIn restorePreviousSignInWithCompletion:nil];
  510. XCTAssertNotNil(_signIn.currentUser);
  511. }
  512. - (void)testOAuthLogin {
  513. OCMStub(
  514. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  515. ).andDo(^(NSInvocation *invocation) {
  516. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  517. });
  518. [self OAuthLoginWithAddScopesFlow:NO
  519. authError:nil
  520. tokenError:nil
  521. emmPasscodeInfoRequired:NO
  522. keychainError:NO
  523. restoredSignIn:NO
  524. oldAccessToken:NO
  525. modalCancel:NO];
  526. }
  527. - (void)testOAuthLogin_RestoredSignIn {
  528. OCMStub(
  529. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  530. ).andDo(^(NSInvocation *invocation) {
  531. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  532. });
  533. [self OAuthLoginWithAddScopesFlow:NO
  534. authError:nil
  535. tokenError:nil
  536. emmPasscodeInfoRequired:NO
  537. keychainError:NO
  538. restoredSignIn:YES
  539. oldAccessToken:NO
  540. modalCancel:NO];
  541. }
  542. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  543. OCMStub(
  544. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  545. ).andDo(^(NSInvocation *invocation) {
  546. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  547. });
  548. [self OAuthLoginWithAddScopesFlow:NO
  549. authError:nil
  550. tokenError:nil
  551. emmPasscodeInfoRequired:NO
  552. keychainError:NO
  553. restoredSignIn:YES
  554. oldAccessToken:YES
  555. modalCancel:NO];
  556. }
  557. - (void)testOAuthLogin_AdditionalScopes {
  558. NSString *expectedScopeString;
  559. OCMStub(
  560. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  561. ).andDo(^(NSInvocation *invocation) {
  562. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  563. });
  564. [self OAuthLoginWithAddScopesFlow:NO
  565. authError:nil
  566. tokenError:nil
  567. emmPasscodeInfoRequired:NO
  568. keychainError:NO
  569. restoredSignIn:NO
  570. oldAccessToken:NO
  571. modalCancel:NO
  572. useAdditionalScopes:YES
  573. additionalScopes:nil
  574. manualNonce:nil];
  575. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  576. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  577. [self OAuthLoginWithAddScopesFlow:NO
  578. authError:nil
  579. tokenError:nil
  580. emmPasscodeInfoRequired:NO
  581. keychainError:NO
  582. restoredSignIn:NO
  583. oldAccessToken:NO
  584. modalCancel:NO
  585. useAdditionalScopes:YES
  586. additionalScopes:@[ kScope ]
  587. manualNonce:nil];
  588. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  589. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  590. [self OAuthLoginWithAddScopesFlow:NO
  591. authError:nil
  592. tokenError:nil
  593. emmPasscodeInfoRequired:NO
  594. keychainError:NO
  595. restoredSignIn:NO
  596. oldAccessToken:NO
  597. modalCancel:NO
  598. useAdditionalScopes:YES
  599. additionalScopes:@[ kScope, kScope2 ]
  600. manualNonce:nil];
  601. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  602. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  603. }
  604. - (void)testAddScopes {
  605. // Restore the previous sign-in account. This is the preparation for adding scopes.
  606. OCMStub(
  607. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  608. ).andDo(^(NSInvocation *invocation) {
  609. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  610. });
  611. [self OAuthLoginWithAddScopesFlow:NO
  612. authError:nil
  613. tokenError:nil
  614. emmPasscodeInfoRequired:NO
  615. keychainError:NO
  616. restoredSignIn:YES
  617. oldAccessToken:NO
  618. modalCancel:NO];
  619. XCTAssertNotNil(_signIn.currentUser);
  620. id profile = OCMStrictClassMock([GIDProfileData class]);
  621. OCMStub([profile email]).andReturn(kUserEmail);
  622. // Mock for the method `addScopes`.
  623. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  624. serverClientID:nil
  625. hostedDomain:nil
  626. openIDRealm:kOpenIDRealm];
  627. OCMStub([_user configuration]).andReturn(configuration);
  628. OCMStub([_user profile]).andReturn(profile);
  629. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  630. [self OAuthLoginWithAddScopesFlow:YES
  631. authError:nil
  632. tokenError:nil
  633. emmPasscodeInfoRequired:NO
  634. keychainError:NO
  635. restoredSignIn:NO
  636. oldAccessToken:NO
  637. modalCancel:NO];
  638. NSArray<NSString *> *grantedScopes;
  639. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  640. if (grantedScopeString) {
  641. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  642. [NSCharacterSet whitespaceCharacterSet]];
  643. // Tokenize with space as a delimiter.
  644. NSMutableArray<NSString *> *parsedScopes =
  645. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  646. // Remove empty strings.
  647. [parsedScopes removeObject:@""];
  648. grantedScopes = [parsedScopes copy];
  649. }
  650. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  651. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  652. [_user verify];
  653. [profile verify];
  654. [profile stopMocking];
  655. }
  656. - (void)testOpenIDRealm {
  657. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  658. serverClientID:nil
  659. hostedDomain:nil
  660. openIDRealm:kOpenIDRealm];
  661. OCMStub(
  662. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  663. ).andDo(^(NSInvocation *invocation) {
  664. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  665. });
  666. [self OAuthLoginWithAddScopesFlow:NO
  667. authError:nil
  668. tokenError:nil
  669. emmPasscodeInfoRequired:NO
  670. keychainError:NO
  671. restoredSignIn:NO
  672. oldAccessToken:NO
  673. modalCancel:NO];
  674. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  675. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  676. }
  677. - (void)testManualNonce {
  678. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  679. serverClientID:nil
  680. hostedDomain:nil
  681. openIDRealm:kOpenIDRealm];
  682. OCMStub(
  683. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  684. ).andDo(^(NSInvocation *invocation) {
  685. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  686. });
  687. NSString* manualNonce = @"manual_nonce";
  688. [self OAuthLoginWithAddScopesFlow:NO
  689. authError:nil
  690. tokenError:nil
  691. emmPasscodeInfoRequired:NO
  692. keychainError:NO
  693. restoredSignIn:NO
  694. oldAccessToken:NO
  695. modalCancel:NO
  696. useAdditionalScopes:NO
  697. additionalScopes:@[]
  698. manualNonce:manualNonce];
  699. XCTAssertEqualObjects(_savedAuthorizationRequest.nonce,
  700. manualNonce,
  701. @"Provided nonce should match nonce in authorization request.");
  702. }
  703. - (void)testOAuthLogin_LoginHint {
  704. _hint = kUserEmail;
  705. OCMStub(
  706. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  707. ).andDo(^(NSInvocation *invocation) {
  708. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  709. });
  710. [self OAuthLoginWithAddScopesFlow:NO
  711. authError:nil
  712. tokenError:nil
  713. emmPasscodeInfoRequired:NO
  714. keychainError:NO
  715. restoredSignIn:NO
  716. oldAccessToken:NO
  717. modalCancel:NO];
  718. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  719. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  720. }
  721. - (void)testOAuthLogin_HostedDomain {
  722. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  723. serverClientID:nil
  724. hostedDomain:kHostedDomain
  725. openIDRealm:nil];
  726. OCMStub(
  727. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  728. ).andDo(^(NSInvocation *invocation) {
  729. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  730. });
  731. [self OAuthLoginWithAddScopesFlow:NO
  732. authError:nil
  733. tokenError:nil
  734. emmPasscodeInfoRequired:NO
  735. keychainError:NO
  736. restoredSignIn:NO
  737. oldAccessToken:NO
  738. modalCancel:NO];
  739. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  740. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  741. }
  742. - (void)testOAuthLogin_ConsentCanceled {
  743. [self OAuthLoginWithAddScopesFlow:NO
  744. authError:@"access_denied"
  745. tokenError:nil
  746. emmPasscodeInfoRequired:NO
  747. keychainError:NO
  748. restoredSignIn:NO
  749. oldAccessToken:NO
  750. modalCancel:NO];
  751. [self waitForExpectationsWithTimeout:1 handler:nil];
  752. XCTAssertTrue(_completionCalled, @"should call delegate");
  753. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  754. }
  755. - (void)testOAuthLogin_ModalCanceled {
  756. [self OAuthLoginWithAddScopesFlow:NO
  757. authError:nil
  758. tokenError:nil
  759. emmPasscodeInfoRequired:NO
  760. keychainError:NO
  761. restoredSignIn:NO
  762. oldAccessToken:NO
  763. modalCancel:YES];
  764. [self waitForExpectationsWithTimeout:1 handler:nil];
  765. XCTAssertTrue(_completionCalled, @"should call delegate");
  766. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  767. }
  768. - (void)testOAuthLogin_KeychainError {
  769. // This error is going be overidden by `-[GIDSignIn errorWithString:code:]`
  770. // We just need to fill in the error so that happens.
  771. NSError *keychainError = [NSError errorWithDomain:@"com.googleSignIn.throwAway"
  772. code:1
  773. userInfo:nil];
  774. OCMStub(
  775. [_keychainStore saveAuthSession:OCMOCK_ANY error:[OCMArg setTo:keychainError]]
  776. ).andDo(^(NSInvocation *invocation) {
  777. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  778. });
  779. [self OAuthLoginWithAddScopesFlow:NO
  780. authError:nil
  781. tokenError:nil
  782. emmPasscodeInfoRequired:NO
  783. keychainError:YES
  784. restoredSignIn:NO
  785. oldAccessToken:NO
  786. modalCancel:NO];
  787. [self waitForExpectationsWithTimeout:1 handler:nil];
  788. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  789. XCTAssertTrue(_completionCalled, @"should call delegate");
  790. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  791. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  792. }
  793. - (void)testSignOut {
  794. #if TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  795. // OCMStub([_authorization authState]).andReturn(_authState);
  796. #endif // TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  797. OCMStub([_authorization fetcherService]).andReturn(_fetcherService);
  798. OCMStub(
  799. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  800. ).andDo(^(NSInvocation *invocation) {
  801. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  802. });
  803. // Sign in a user so that we can then sign them out.
  804. [self OAuthLoginWithAddScopesFlow:NO
  805. authError:nil
  806. tokenError:nil
  807. emmPasscodeInfoRequired:NO
  808. keychainError:NO
  809. restoredSignIn:YES
  810. oldAccessToken:NO
  811. modalCancel:NO];
  812. XCTAssertNotNil(_signIn.currentUser);
  813. [_signIn signOut];
  814. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  815. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  816. OCMVerify([_keychainStore removeAuthSessionWithError:OCMArg.anyObjectRef]);
  817. }
  818. - (void)testNotHandleWrongScheme {
  819. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  820. @"should not handle URL");
  821. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  822. XCTAssertFalse(_completionCalled, @"should not call delegate");
  823. }
  824. - (void)testNotHandleWrongPath {
  825. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  826. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  827. XCTAssertFalse(_completionCalled, @"should not call delegate");
  828. }
  829. #pragma mark - Tests - disconnectWithCallback:
  830. // Verifies disconnect calls callback with no errors if access token is present.
  831. - (void)testDisconnect_accessToken {
  832. [[[_authorization expect] andReturn:_authState] authState];
  833. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  834. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  835. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  836. XCTestExpectation *accessTokenExpectation =
  837. [self expectationWithDescription:@"Callback called with nil error"];
  838. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  839. if (error == nil) {
  840. [accessTokenExpectation fulfill];
  841. }
  842. }];
  843. [self verifyAndRevokeToken:kAccessToken
  844. hasCallback:YES
  845. waitingForExpectations:@[accessTokenExpectation]];
  846. [_authorization verify];
  847. [_authState verify];
  848. [_tokenResponse verify];
  849. }
  850. // Verifies disconnect if access token is present.
  851. - (void)testDisconnectNoCallback_accessToken {
  852. [[[_authorization expect] andReturn:_authState] authState];
  853. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  854. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  855. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  856. [_signIn disconnectWithCompletion:nil];
  857. [self verifyAndRevokeToken:kAccessToken hasCallback:NO waitingForExpectations:@[]];
  858. [_authorization verify];
  859. [_authState verify];
  860. [_tokenResponse verify];
  861. }
  862. // Verifies disconnect calls callback with no errors if refresh token is present.
  863. - (void)testDisconnect_refreshToken {
  864. [[[_authorization expect] andReturn:_authState] authState];
  865. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  866. [[[_tokenResponse expect] andReturn:nil] accessToken];
  867. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  868. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  869. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  870. XCTestExpectation *refreshTokenExpectation =
  871. [self expectationWithDescription:@"Callback called with nil error"];
  872. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  873. if (error == nil) {
  874. [refreshTokenExpectation fulfill];
  875. }
  876. }];
  877. [self verifyAndRevokeToken:kRefreshToken
  878. hasCallback:YES
  879. waitingForExpectations:@[refreshTokenExpectation]];
  880. [_authorization verify];
  881. [_authState verify];
  882. [_tokenResponse verify];
  883. }
  884. // Verifies disconnect errors are passed along to the callback.
  885. - (void)testDisconnect_errors {
  886. [[[_authorization expect] andReturn:_authState] authState];
  887. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  888. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  889. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  890. XCTestExpectation *errorExpectation =
  891. [self expectationWithDescription:@"Callback called with an error"];
  892. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  893. if (error != nil) {
  894. [errorExpectation fulfill];
  895. }
  896. }];
  897. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  898. // Emulate result back from server.
  899. NSError *error = [self error];
  900. [self didFetch:nil error:error];
  901. [self waitForExpectations:@[errorExpectation] timeout:1];
  902. [_authorization verify];
  903. [_authState verify];
  904. [_tokenResponse verify];
  905. }
  906. // Verifies disconnect with errors
  907. - (void)testDisconnectNoCallback_errors {
  908. [[[_authorization expect] andReturn:_authState] authState];
  909. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  910. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  911. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  912. [_signIn disconnectWithCompletion:nil];
  913. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  914. // Emulate result back from server.
  915. NSError *error = [self error];
  916. [self didFetch:nil error:error];
  917. [_authorization verify];
  918. [_authState verify];
  919. [_tokenResponse verify];
  920. }
  921. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  922. - (void)testDisconnect_noTokens {
  923. [[[_authorization expect] andReturn:_authState] authState];
  924. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  925. [[[_tokenResponse expect] andReturn:nil] accessToken];
  926. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  927. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  928. XCTestExpectation *noTokensExpectation =
  929. [self expectationWithDescription:@"Callback called with nil error"];
  930. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  931. if (error == nil) {
  932. [noTokensExpectation fulfill];
  933. }
  934. }];
  935. [self waitForExpectations:@[noTokensExpectation] timeout:1];
  936. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  937. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  938. [_authorization verify];
  939. [_authState verify];
  940. [_tokenResponse verify];
  941. }
  942. // Verifies disconnect clears keychain if no tokens are present.
  943. - (void)testDisconnectNoCallback_noTokens {
  944. [[[_authorization expect] andReturn:_authState] authState];
  945. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  946. [[[_tokenResponse expect] andReturn:nil] accessToken];
  947. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  948. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  949. [_signIn disconnectWithCompletion:nil];
  950. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  951. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  952. [_authorization verify];
  953. [_authState verify];
  954. [_tokenResponse verify];
  955. }
  956. - (void)testPresentingViewControllerException {
  957. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  958. _presentingViewController = nil;
  959. #elif TARGET_OS_OSX
  960. _presentingWindow = nil;
  961. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  962. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  963. XCTAssertThrows([_signIn signInWithPresentingViewController:_presentingViewController
  964. #elif TARGET_OS_OSX
  965. XCTAssertThrows([_signIn signInWithPresentingWindow:_presentingWindow
  966. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  967. hint:_hint
  968. completion:_completion]);
  969. }
  970. - (void)testClientIDMissingException {
  971. #pragma GCC diagnostic push
  972. #pragma GCC diagnostic ignored "-Wnonnull"
  973. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  974. #pragma GCC diagnostic pop
  975. BOOL threw = NO;
  976. @try {
  977. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  978. [_signIn signInWithPresentingViewController:_presentingViewController
  979. #elif TARGET_OS_OSX
  980. [_signIn signInWithPresentingWindow:_presentingWindow
  981. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  982. completion:nil];
  983. } @catch (NSException *exception) {
  984. threw = YES;
  985. XCTAssertEqualObjects(exception.description,
  986. @"You must specify |clientID| in |GIDConfiguration|");
  987. } @finally {
  988. }
  989. XCTAssert(threw);
  990. }
  991. - (void)testSchemesNotSupportedException {
  992. [_fakeMainBundle fakeMissingAllSchemes];
  993. BOOL threw = NO;
  994. @try {
  995. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  996. [_signIn signInWithPresentingViewController:_presentingViewController
  997. #elif TARGET_OS_OSX
  998. [_signIn signInWithPresentingWindow:_presentingWindow
  999. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1000. hint:_hint
  1001. completion:_completion];
  1002. } @catch (NSException *exception) {
  1003. threw = YES;
  1004. XCTAssertEqualObjects(exception.description,
  1005. @"Your app is missing support for the following URL schemes: "
  1006. "fakeclientid");
  1007. } @finally {
  1008. }
  1009. XCTAssert(threw);
  1010. }
  1011. #pragma mark - Restarting Authentication Tests
  1012. // Verifies that URL is not handled if there is no pending sign-in
  1013. - (void)testRequiringPendingSignIn {
  1014. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  1015. XCTAssertFalse(result);
  1016. }
  1017. #pragma mark - EMM tests
  1018. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1019. - (void)testEmmSupportRequestParameters {
  1020. OCMStub(
  1021. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1022. ).andDo(^(NSInvocation *invocation) {
  1023. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1024. });
  1025. [self OAuthLoginWithAddScopesFlow:NO
  1026. authError:nil
  1027. tokenError:nil
  1028. emmPasscodeInfoRequired:NO
  1029. keychainError:NO
  1030. restoredSignIn:NO
  1031. oldAccessToken:NO
  1032. modalCancel:NO];
  1033. NSString *systemName = [UIDevice currentDevice].systemName;
  1034. if ([systemName isEqualToString:@"iPhone OS"]) {
  1035. systemName = @"iOS";
  1036. }
  1037. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  1038. systemName, [UIDevice currentDevice].systemVersion];
  1039. NSDictionary<NSString *, NSObject *> *authParams =
  1040. _savedAuthorizationRequest.additionalParameters;
  1041. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1042. if (_isEligibleForEMM) {
  1043. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  1044. @"EMM support should match in auth request");
  1045. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  1046. @"OS version should match in auth request");
  1047. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  1048. @"EMM support should match in token request");
  1049. XCTAssertEqualObjects(tokenParams[@"device_os"],
  1050. expectedOSVersion,
  1051. @"OS version should match in token request");
  1052. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1053. @"no passcode info should be in token request");
  1054. } else {
  1055. XCTAssertNil(authParams[@"emm_support"],
  1056. @"EMM support should not be in auth request for unsupported OS");
  1057. XCTAssertNil(authParams[@"device_os"],
  1058. @"OS version should not be in auth request for unsupported OS");
  1059. XCTAssertNil(tokenParams[@"emm_support"],
  1060. @"EMM support should not be in token request for unsupported OS");
  1061. XCTAssertNil(tokenParams[@"device_os"],
  1062. @"OS version should not be in token request for unsupported OS");
  1063. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1064. @"passcode info should not be in token request for unsupported OS");
  1065. }
  1066. }
  1067. - (void)testEmmPasscodeInfo {
  1068. OCMStub(
  1069. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1070. ).andDo(^(NSInvocation *invocation) {
  1071. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1072. });
  1073. [self OAuthLoginWithAddScopesFlow:NO
  1074. authError:nil
  1075. tokenError:nil
  1076. emmPasscodeInfoRequired:YES
  1077. keychainError:NO
  1078. restoredSignIn:NO
  1079. oldAccessToken:NO
  1080. modalCancel:NO];
  1081. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1082. if (_isEligibleForEMM) {
  1083. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  1084. @"passcode info should be in token request");
  1085. } else {
  1086. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1087. @"passcode info should not be in token request for unsupported OS");
  1088. }
  1089. }
  1090. - (void)testAuthEndpointEMMError {
  1091. if (!_isEligibleForEMM) {
  1092. return;
  1093. }
  1094. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  1095. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  1096. __block void (^completion)(void);
  1097. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  1098. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  1099. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  1100. [self OAuthLoginWithAddScopesFlow:NO
  1101. authError:callbackParams[@"error"]
  1102. tokenError:nil
  1103. emmPasscodeInfoRequired:NO
  1104. keychainError:NO
  1105. restoredSignIn:NO
  1106. oldAccessToken:NO
  1107. modalCancel:NO];
  1108. [mockEMMErrorHandler verify];
  1109. [mockEMMErrorHandler stopMocking];
  1110. completion();
  1111. [self waitForExpectationsWithTimeout:1 handler:nil];
  1112. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1113. XCTAssertTrue(_completionCalled, @"should call delegate");
  1114. XCTAssertNotNil(_authError, @"should have error");
  1115. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1116. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1117. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1118. }
  1119. - (void)testTokenEndpointEMMError {
  1120. if (!_isEligibleForEMM) {
  1121. return;
  1122. }
  1123. __block void (^completion)(NSError *);
  1124. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  1125. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  1126. code:12345
  1127. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  1128. id emmSupport = OCMStrictClassMock([GIDEMMSupport class]);
  1129. [[emmSupport expect] handleTokenFetchEMMError:emmError
  1130. completion:SAVE_TO_ARG_BLOCK(completion)];
  1131. [self OAuthLoginWithAddScopesFlow:NO
  1132. authError:nil
  1133. tokenError:emmError
  1134. emmPasscodeInfoRequired:NO
  1135. keychainError:NO
  1136. restoredSignIn:NO
  1137. oldAccessToken:NO
  1138. modalCancel:NO];
  1139. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  1140. code:kGIDSignInErrorCodeEMM
  1141. userInfo:emmError.userInfo];
  1142. completion(handledError);
  1143. [self waitForExpectationsWithTimeout:1 handler:nil];
  1144. [emmSupport verify];
  1145. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1146. XCTAssertTrue(_completionCalled, @"should call delegate");
  1147. XCTAssertNotNil(_authError, @"should have error");
  1148. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1149. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1150. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1151. }
  1152. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1153. #pragma mark - Helpers
  1154. // Whether or not a fetcher has been started.
  1155. - (BOOL)isFetcherStarted {
  1156. NSUInteger count = _fetcherService.fetchers.count;
  1157. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  1158. return !!count;
  1159. }
  1160. // Gets the URL being fetched.
  1161. - (NSURL *)fetchedURL {
  1162. return [_fetcherService.fetchers[0] requestURL];
  1163. }
  1164. // Emulates server returning the data as in JSON.
  1165. - (void)didFetch:(id)dataObject error:(NSError *)error {
  1166. NSData *data = nil;
  1167. if (dataObject) {
  1168. NSError *jsonError = nil;
  1169. data = [NSJSONSerialization dataWithJSONObject:dataObject
  1170. options:0
  1171. error:&jsonError];
  1172. XCTAssertNil(jsonError, @"must provide valid data");
  1173. }
  1174. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  1175. }
  1176. - (NSError *)error {
  1177. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  1178. }
  1179. // Verifies a fetcher has started for revoking token and emulates a server response.
  1180. - (void)verifyAndRevokeToken:(NSString *)token
  1181. hasCallback:(BOOL)hasCallback
  1182. waitingForExpectations:(NSArray<XCTestExpectation *> *)expectations {
  1183. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  1184. NSURL *url = [self fetchedURL];
  1185. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  1186. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  1187. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  1188. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  1189. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  1190. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  1191. @"token parameter should match");
  1192. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  1193. @"SDK version logging parameter should match");
  1194. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  1195. @"Environment logging parameter should match");
  1196. // Emulate result back from server.
  1197. [self didFetch:nil error:nil];
  1198. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  1199. if (hasCallback) {
  1200. [self waitForExpectations:expectations timeout:1];
  1201. }
  1202. }
  1203. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1204. authError:(NSString *)authError
  1205. tokenError:(NSError *)tokenError
  1206. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1207. keychainError:(BOOL)keychainError
  1208. restoredSignIn:(BOOL)restoredSignIn
  1209. oldAccessToken:(BOOL)oldAccessToken
  1210. modalCancel:(BOOL)modalCancel {
  1211. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  1212. authError:authError
  1213. tokenError:tokenError
  1214. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  1215. keychainError:keychainError
  1216. restoredSignIn:restoredSignIn
  1217. oldAccessToken:oldAccessToken
  1218. modalCancel:modalCancel
  1219. useAdditionalScopes:NO
  1220. additionalScopes:nil
  1221. manualNonce:nil];
  1222. }
  1223. // The authorization flow with parameters to control which branches to take.
  1224. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1225. authError:(NSString *)authError
  1226. tokenError:(NSError *)tokenError
  1227. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1228. keychainError:(BOOL)keychainError
  1229. restoredSignIn:(BOOL)restoredSignIn
  1230. oldAccessToken:(BOOL)oldAccessToken
  1231. modalCancel:(BOOL)modalCancel
  1232. useAdditionalScopes:(BOOL)useAdditionalScopes
  1233. additionalScopes:(NSArray *)additionalScopes
  1234. manualNonce:(NSString *)nonce {
  1235. if (restoredSignIn) {
  1236. // clearAndAuthenticateWithOptions
  1237. [[[_authorization expect] andReturn:_authState] authState];
  1238. BOOL isAuthorized = restoredSignIn;
  1239. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1240. }
  1241. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1242. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1243. OIDAuthorizationResponse *authResponse =
  1244. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1245. nonce:nonce
  1246. errorString:authError];
  1247. OIDTokenResponse *tokenResponse =
  1248. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1249. accessToken:restoredSignIn ? kAccessToken : nil
  1250. expiresIn:oldAccessToken ? @(300) : nil
  1251. refreshToken:kRefreshToken
  1252. tokenRequest:nil];
  1253. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1254. initWithConfiguration:authResponse.request.configuration
  1255. grantType:OIDGrantTypeRefreshToken
  1256. authorizationCode:nil
  1257. redirectURL:nil
  1258. clientID:authResponse.request.clientID
  1259. clientSecret:authResponse.request.clientSecret
  1260. scope:nil
  1261. refreshToken:kRefreshToken
  1262. codeVerifier:nil
  1263. additionalParameters:tokenResponse.request.additionalParameters];
  1264. if (restoredSignIn) {
  1265. // maybeFetchToken
  1266. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1267. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1268. if (oldAccessToken) {
  1269. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1270. // Corresponds to EMM support
  1271. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1272. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1273. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1274. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1275. [[[_authState expect] andReturn:tokenRequest]
  1276. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1277. }
  1278. } else {
  1279. XCTestExpectation *newAccessTokenExpectation =
  1280. [self expectationWithDescription:@"Callback called"];
  1281. GIDSignInCompletion completion = ^(GIDSignInResult *_Nullable signInResult,
  1282. NSError * _Nullable error) {
  1283. [newAccessTokenExpectation fulfill];
  1284. if (signInResult) {
  1285. XCTAssertEqualObjects(signInResult.serverAuthCode, kServerAuthCode);
  1286. } else {
  1287. XCTAssertNotNil(error, @"Should have an error if the signInResult is nil");
  1288. }
  1289. XCTAssertFalse(self->_completionCalled, @"callback already called");
  1290. self->_completionCalled = YES;
  1291. self->_authError = error;
  1292. };
  1293. if (addScopesFlow) {
  1294. [_signIn addScopes:@[kNewScope]
  1295. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1296. presentingViewController:_presentingViewController
  1297. #elif TARGET_OS_OSX
  1298. presentingWindow:_presentingWindow
  1299. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1300. completion:completion];
  1301. } else {
  1302. if (useAdditionalScopes) {
  1303. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1304. [_signIn signInWithPresentingViewController:_presentingViewController
  1305. #elif TARGET_OS_OSX
  1306. [_signIn signInWithPresentingWindow:_presentingWindow
  1307. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1308. hint:_hint
  1309. additionalScopes:additionalScopes
  1310. completion:completion];
  1311. } else {
  1312. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1313. [_signIn signInWithPresentingViewController:_presentingViewController
  1314. #elif TARGET_OS_OSX
  1315. [_signIn signInWithPresentingWindow:_presentingWindow
  1316. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1317. hint:_hint
  1318. additionalScopes:nil
  1319. nonce:nonce
  1320. completion:completion];
  1321. }
  1322. }
  1323. [_authorization verify];
  1324. [_authState verify];
  1325. XCTAssertNotNil(_savedAuthorizationRequest);
  1326. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1327. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1328. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1329. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1330. XCTAssertNotNil(_savedAuthorizationCallback);
  1331. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1332. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1333. #elif TARGET_OS_OSX
  1334. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1335. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1336. // maybeFetchToken
  1337. if (!(authError || modalCancel)) {
  1338. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1339. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1340. // Corresponds to EMM support
  1341. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1342. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1343. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1344. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1345. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1346. }
  1347. // Simulate auth endpoint response
  1348. if (modalCancel) {
  1349. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1350. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1351. userInfo:nil];
  1352. _savedAuthorizationCallback(nil, error);
  1353. } else {
  1354. _savedAuthorizationCallback(authResponse, nil);
  1355. }
  1356. if (authError || modalCancel) {
  1357. return;
  1358. }
  1359. [_authState verify];
  1360. }
  1361. if (restoredSignIn && oldAccessToken) {
  1362. XCTestExpectation *callbackShouldBeCalledExpectation =
  1363. [self expectationWithDescription:@"Callback should be called"];
  1364. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1365. NSError * _Nullable error) {
  1366. [callbackShouldBeCalledExpectation fulfill];
  1367. XCTAssertNil(error, @"should have no error");
  1368. }];
  1369. }
  1370. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1371. XCTAssertNotNil(_savedTokenRequest);
  1372. XCTAssertNotNil(_savedTokenCallback);
  1373. // OIDTokenCallback
  1374. if (tokenError) {
  1375. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1376. } else {
  1377. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1378. }
  1379. }
  1380. if (tokenError) {
  1381. _savedTokenCallback(nil, tokenError);
  1382. return;
  1383. }
  1384. // DecodeIdTokenCallback
  1385. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1386. // SaveAuthCallback
  1387. __block OIDAuthState *authState;
  1388. __block OIDTokenResponse *updatedTokenResponse;
  1389. __block OIDAuthorizationResponse *updatedAuthorizationResponse;
  1390. __block GIDProfileData *profileData;
  1391. if (keychainError) {
  1392. _saveAuthorizationReturnValue = NO;
  1393. } else {
  1394. if (addScopesFlow) {
  1395. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1396. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1397. [[_user expect] updateWithTokenResponse:SAVE_TO_ARG_BLOCK(updatedTokenResponse)
  1398. authorizationResponse:SAVE_TO_ARG_BLOCK(updatedAuthorizationResponse)
  1399. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1400. } else {
  1401. [[[_user expect] andReturn:_user] alloc];
  1402. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1403. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1404. }
  1405. }
  1406. // CompletionCallback - mock server auth code parsing
  1407. if (!keychainError) {
  1408. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1409. }
  1410. if (restoredSignIn && !oldAccessToken) {
  1411. XCTestExpectation *restoredSignInExpectation = [self expectationWithDescription:@"Callback should be called"];
  1412. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1413. NSError * _Nullable error) {
  1414. [restoredSignInExpectation fulfill];
  1415. XCTAssertNil(error, @"should have no error");
  1416. }];
  1417. } else {
  1418. // Simulate token endpoint response.
  1419. _savedTokenCallback(tokenResponse, nil);
  1420. }
  1421. if (keychainError) {
  1422. return;
  1423. }
  1424. [self waitForExpectationsWithTimeout:1 handler:nil];
  1425. [_authState verify];
  1426. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1427. if (addScopesFlow) {
  1428. XCTAssertNotNil(updatedTokenResponse);
  1429. XCTAssertNotNil(updatedAuthorizationResponse);
  1430. } else {
  1431. XCTAssertNotNil(authState);
  1432. }
  1433. // Check fat ID token decoding
  1434. XCTAssertEqualObjects(profileData.name, kFatName);
  1435. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1436. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1437. XCTAssertTrue(profileData.hasImage);
  1438. // If attempt to authenticate again, will reuse existing auth object.
  1439. _completionCalled = NO;
  1440. _keychainRemoved = NO;
  1441. _keychainSaved = NO;
  1442. _authError = nil;
  1443. __block GIDGoogleUserCompletion completion;
  1444. [[_user expect] refreshTokensIfNeededWithCompletion:SAVE_TO_ARG_BLOCK(completion)];
  1445. XCTestExpectation *restorePreviousSignInExpectation =
  1446. [self expectationWithDescription:@"Callback should be called"];
  1447. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1448. NSError * _Nullable error) {
  1449. [restorePreviousSignInExpectation fulfill];
  1450. XCTAssertNil(error, @"should have no error");
  1451. }];
  1452. completion(_user, nil);
  1453. [self waitForExpectationsWithTimeout:1 handler:nil];
  1454. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1455. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1456. if (restoredSignIn) {
  1457. // Ignore the return value
  1458. OCMVerify((void)[_keychainStore retrieveAuthSessionWithError:OCMArg.anyObjectRef]);
  1459. OCMVerify([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]);
  1460. }
  1461. }
  1462. @end