GIDSignInTest.m 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  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. tokenClaims:nil];
  576. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  577. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  578. [self OAuthLoginWithAddScopesFlow:NO
  579. authError:nil
  580. tokenError:nil
  581. emmPasscodeInfoRequired:NO
  582. keychainError:NO
  583. restoredSignIn:NO
  584. oldAccessToken:NO
  585. modalCancel:NO
  586. useAdditionalScopes:YES
  587. additionalScopes:@[ kScope ]
  588. manualNonce:nil
  589. tokenClaims:nil];
  590. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  591. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  592. [self OAuthLoginWithAddScopesFlow:NO
  593. authError:nil
  594. tokenError:nil
  595. emmPasscodeInfoRequired:NO
  596. keychainError:NO
  597. restoredSignIn:NO
  598. oldAccessToken:NO
  599. modalCancel:NO
  600. useAdditionalScopes:YES
  601. additionalScopes:@[ kScope, kScope2 ]
  602. manualNonce:nil
  603. tokenClaims:nil];
  604. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  605. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  606. }
  607. - (void)testOAuthLogin_TokenClaims {
  608. GIDTokenClaim *authTimeClaim = [GIDTokenClaim authTimeClaim];
  609. GIDTokenClaim *essentialAuthTimeClaim = [GIDTokenClaim essentialAuthTimeClaim];
  610. NSString *expectedClaimsJsonString;
  611. OCMStub([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  612. ).andDo(^(NSInvocation *invocation){
  613. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  614. });
  615. [self OAuthLoginWithAddScopesFlow:NO
  616. authError:nil
  617. tokenError:nil
  618. emmPasscodeInfoRequired:NO
  619. keychainError:NO
  620. restoredSignIn:NO
  621. oldAccessToken:NO
  622. modalCancel:NO
  623. useAdditionalScopes:NO
  624. additionalScopes:nil
  625. manualNonce:nil
  626. tokenClaims:[NSSet setWithObject:essentialAuthTimeClaim]];
  627. expectedClaimsJsonString = @"{\"id_token\":{\"auth_time\":{\"essential\":true}}}";
  628. XCTAssertEqualObjects(_savedAuthorizationRequest.additionalParameters[@"claims"], expectedClaimsJsonString, @"Claims JSON should be correctly formatted");
  629. [self OAuthLoginWithAddScopesFlow:NO
  630. authError:nil
  631. tokenError:nil
  632. emmPasscodeInfoRequired:NO
  633. keychainError:NO
  634. restoredSignIn:NO
  635. oldAccessToken:NO
  636. modalCancel:NO
  637. useAdditionalScopes:NO
  638. additionalScopes:nil
  639. manualNonce:nil
  640. tokenClaims:[NSSet setWithObject:authTimeClaim]];
  641. expectedClaimsJsonString = @"{\"id_token\":{\"auth_time\":null}}";
  642. XCTAssertEqualObjects(_savedAuthorizationRequest.additionalParameters[@"claims"], expectedClaimsJsonString, @"Claims JSON should be correctly formatted");
  643. }
  644. - (void)testOAuthLogin_TokenClaims_FailsWithError {
  645. GIDTokenClaim *authTimeClaim = [GIDTokenClaim authTimeClaim];
  646. GIDTokenClaim *essentialAuthTimeClaim = [GIDTokenClaim essentialAuthTimeClaim];
  647. XCTestExpectation *expectation =
  648. [self expectationWithDescription:@"Completion should be called with an ambiguous claims error."];
  649. GIDSignInCompletion completion = ^(GIDSignInResult * _Nullable signInResult,
  650. NSError * _Nullable error) {
  651. // Assert that the sign-in failed with the correct error.
  652. XCTAssertNil(signInResult, @"Sign-in result should be nil on failure.");
  653. XCTAssertNotNil(error, @"An error object should be returned.");
  654. XCTAssertEqual(error.code, kGIDSignInErrorCodeAmbiguousClaims,
  655. @"The error code should be for ambiguous claims.");
  656. // Fulfill the expectation to signal that the test is complete.
  657. [expectation fulfill];
  658. };
  659. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  660. [_signIn signInWithPresentingViewController:_presentingViewController
  661. #elif TARGET_OS_OSX
  662. [_signIn signInWithPresentingWindow:_presentingWindow
  663. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  664. tokenClaims:[NSSet setWithObjects:authTimeClaim, essentialAuthTimeClaim, nil]
  665. completion:completion];
  666. // Wait for the completion handler to be called
  667. [self waitForExpectationsWithTimeout:1.0 handler:nil];
  668. }
  669. - (void)testAddScopes {
  670. // Restore the previous sign-in account. This is the preparation for adding scopes.
  671. OCMStub(
  672. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  673. ).andDo(^(NSInvocation *invocation) {
  674. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  675. });
  676. [self OAuthLoginWithAddScopesFlow:NO
  677. authError:nil
  678. tokenError:nil
  679. emmPasscodeInfoRequired:NO
  680. keychainError:NO
  681. restoredSignIn:YES
  682. oldAccessToken:NO
  683. modalCancel:NO];
  684. XCTAssertNotNil(_signIn.currentUser);
  685. id profile = OCMStrictClassMock([GIDProfileData class]);
  686. OCMStub([profile email]).andReturn(kUserEmail);
  687. // Mock for the method `addScopes`.
  688. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  689. serverClientID:nil
  690. hostedDomain:nil
  691. openIDRealm:kOpenIDRealm];
  692. OCMStub([_user configuration]).andReturn(configuration);
  693. OCMStub([_user profile]).andReturn(profile);
  694. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  695. [self OAuthLoginWithAddScopesFlow:YES
  696. authError:nil
  697. tokenError:nil
  698. emmPasscodeInfoRequired:NO
  699. keychainError:NO
  700. restoredSignIn:NO
  701. oldAccessToken:NO
  702. modalCancel:NO];
  703. NSArray<NSString *> *grantedScopes;
  704. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  705. if (grantedScopeString) {
  706. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  707. [NSCharacterSet whitespaceCharacterSet]];
  708. // Tokenize with space as a delimiter.
  709. NSMutableArray<NSString *> *parsedScopes =
  710. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  711. // Remove empty strings.
  712. [parsedScopes removeObject:@""];
  713. grantedScopes = [parsedScopes copy];
  714. }
  715. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  716. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  717. [_user verify];
  718. [profile verify];
  719. [profile stopMocking];
  720. }
  721. - (void)testOpenIDRealm {
  722. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  723. serverClientID:nil
  724. hostedDomain:nil
  725. openIDRealm:kOpenIDRealm];
  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 *, NSString *> *params = _savedTokenRequest.additionalParameters;
  740. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  741. }
  742. - (void)testManualNonce {
  743. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  744. serverClientID:nil
  745. hostedDomain:nil
  746. openIDRealm:kOpenIDRealm];
  747. OCMStub(
  748. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  749. ).andDo(^(NSInvocation *invocation) {
  750. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  751. });
  752. NSString* manualNonce = @"manual_nonce";
  753. [self OAuthLoginWithAddScopesFlow:NO
  754. authError:nil
  755. tokenError:nil
  756. emmPasscodeInfoRequired:NO
  757. keychainError:NO
  758. restoredSignIn:NO
  759. oldAccessToken:NO
  760. modalCancel:NO
  761. useAdditionalScopes:NO
  762. additionalScopes:@[]
  763. manualNonce:manualNonce
  764. tokenClaims:nil];
  765. XCTAssertEqualObjects(_savedAuthorizationRequest.nonce,
  766. manualNonce,
  767. @"Provided nonce should match nonce in authorization request.");
  768. }
  769. - (void)testOAuthLogin_LoginHint {
  770. _hint = kUserEmail;
  771. OCMStub(
  772. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  773. ).andDo(^(NSInvocation *invocation) {
  774. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  775. });
  776. [self OAuthLoginWithAddScopesFlow:NO
  777. authError:nil
  778. tokenError:nil
  779. emmPasscodeInfoRequired:NO
  780. keychainError:NO
  781. restoredSignIn:NO
  782. oldAccessToken:NO
  783. modalCancel:NO];
  784. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  785. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  786. }
  787. - (void)testOAuthLogin_HostedDomain {
  788. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  789. serverClientID:nil
  790. hostedDomain:kHostedDomain
  791. openIDRealm:nil];
  792. OCMStub(
  793. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  794. ).andDo(^(NSInvocation *invocation) {
  795. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  796. });
  797. [self OAuthLoginWithAddScopesFlow:NO
  798. authError:nil
  799. tokenError:nil
  800. emmPasscodeInfoRequired:NO
  801. keychainError:NO
  802. restoredSignIn:NO
  803. oldAccessToken:NO
  804. modalCancel:NO];
  805. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  806. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  807. }
  808. - (void)testOAuthLogin_ConsentCanceled {
  809. [self OAuthLoginWithAddScopesFlow:NO
  810. authError:@"access_denied"
  811. tokenError:nil
  812. emmPasscodeInfoRequired:NO
  813. keychainError:NO
  814. restoredSignIn:NO
  815. oldAccessToken:NO
  816. modalCancel:NO];
  817. [self waitForExpectationsWithTimeout:1 handler:nil];
  818. XCTAssertTrue(_completionCalled, @"should call delegate");
  819. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  820. }
  821. - (void)testOAuthLogin_ModalCanceled {
  822. [self OAuthLoginWithAddScopesFlow:NO
  823. authError:nil
  824. tokenError:nil
  825. emmPasscodeInfoRequired:NO
  826. keychainError:NO
  827. restoredSignIn:NO
  828. oldAccessToken:NO
  829. modalCancel:YES];
  830. [self waitForExpectationsWithTimeout:1 handler:nil];
  831. XCTAssertTrue(_completionCalled, @"should call delegate");
  832. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  833. }
  834. - (void)testOAuthLogin_KeychainError {
  835. // This error is going be overidden by `-[GIDSignIn errorWithString:code:]`
  836. // We just need to fill in the error so that happens.
  837. NSError *keychainError = [NSError errorWithDomain:@"com.googleSignIn.throwAway"
  838. code:1
  839. userInfo:nil];
  840. OCMStub(
  841. [_keychainStore saveAuthSession:OCMOCK_ANY error:[OCMArg setTo:keychainError]]
  842. ).andDo(^(NSInvocation *invocation) {
  843. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  844. });
  845. [self OAuthLoginWithAddScopesFlow:NO
  846. authError:nil
  847. tokenError:nil
  848. emmPasscodeInfoRequired:NO
  849. keychainError:YES
  850. restoredSignIn:NO
  851. oldAccessToken:NO
  852. modalCancel:NO];
  853. [self waitForExpectationsWithTimeout:1 handler:nil];
  854. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  855. XCTAssertTrue(_completionCalled, @"should call delegate");
  856. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  857. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  858. }
  859. - (void)testSignOut {
  860. #if TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  861. // OCMStub([_authorization authState]).andReturn(_authState);
  862. #endif // TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  863. OCMStub([_authorization fetcherService]).andReturn(_fetcherService);
  864. OCMStub(
  865. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  866. ).andDo(^(NSInvocation *invocation) {
  867. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  868. });
  869. // Sign in a user so that we can then sign them out.
  870. [self OAuthLoginWithAddScopesFlow:NO
  871. authError:nil
  872. tokenError:nil
  873. emmPasscodeInfoRequired:NO
  874. keychainError:NO
  875. restoredSignIn:YES
  876. oldAccessToken:NO
  877. modalCancel:NO];
  878. XCTAssertNotNil(_signIn.currentUser);
  879. [_signIn signOut];
  880. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  881. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  882. OCMVerify([_keychainStore removeAuthSessionWithError:OCMArg.anyObjectRef]);
  883. }
  884. - (void)testNotHandleWrongScheme {
  885. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  886. @"should not handle URL");
  887. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  888. XCTAssertFalse(_completionCalled, @"should not call delegate");
  889. }
  890. - (void)testNotHandleWrongPath {
  891. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  892. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  893. XCTAssertFalse(_completionCalled, @"should not call delegate");
  894. }
  895. #pragma mark - Tests - disconnectWithCallback:
  896. // Verifies disconnect calls callback with no errors if access token is present.
  897. - (void)testDisconnect_accessToken {
  898. [[[_authorization expect] andReturn:_authState] authState];
  899. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  900. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  901. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  902. XCTestExpectation *accessTokenExpectation =
  903. [self expectationWithDescription:@"Callback called with nil error"];
  904. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  905. if (error == nil) {
  906. [accessTokenExpectation fulfill];
  907. }
  908. }];
  909. [self verifyAndRevokeToken:kAccessToken
  910. hasCallback:YES
  911. waitingForExpectations:@[accessTokenExpectation]];
  912. [_authorization verify];
  913. [_authState verify];
  914. [_tokenResponse verify];
  915. }
  916. // Verifies disconnect if access token is present.
  917. - (void)testDisconnectNoCallback_accessToken {
  918. [[[_authorization expect] andReturn:_authState] authState];
  919. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  920. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  921. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  922. [_signIn disconnectWithCompletion:nil];
  923. [self verifyAndRevokeToken:kAccessToken hasCallback:NO waitingForExpectations:@[]];
  924. [_authorization verify];
  925. [_authState verify];
  926. [_tokenResponse verify];
  927. }
  928. // Verifies disconnect calls callback with no errors if refresh token is present.
  929. - (void)testDisconnect_refreshToken {
  930. [[[_authorization expect] andReturn:_authState] authState];
  931. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  932. [[[_tokenResponse expect] andReturn:nil] accessToken];
  933. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  934. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  935. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  936. XCTestExpectation *refreshTokenExpectation =
  937. [self expectationWithDescription:@"Callback called with nil error"];
  938. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  939. if (error == nil) {
  940. [refreshTokenExpectation fulfill];
  941. }
  942. }];
  943. [self verifyAndRevokeToken:kRefreshToken
  944. hasCallback:YES
  945. waitingForExpectations:@[refreshTokenExpectation]];
  946. [_authorization verify];
  947. [_authState verify];
  948. [_tokenResponse verify];
  949. }
  950. // Verifies disconnect errors are passed along to the callback.
  951. - (void)testDisconnect_errors {
  952. [[[_authorization expect] andReturn:_authState] authState];
  953. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  954. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  955. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  956. XCTestExpectation *errorExpectation =
  957. [self expectationWithDescription:@"Callback called with an error"];
  958. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  959. if (error != nil) {
  960. [errorExpectation fulfill];
  961. }
  962. }];
  963. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  964. // Emulate result back from server.
  965. NSError *error = [self error];
  966. [self didFetch:nil error:error];
  967. [self waitForExpectations:@[errorExpectation] timeout:1];
  968. [_authorization verify];
  969. [_authState verify];
  970. [_tokenResponse verify];
  971. }
  972. // Verifies disconnect with errors
  973. - (void)testDisconnectNoCallback_errors {
  974. [[[_authorization expect] andReturn:_authState] authState];
  975. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  976. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  977. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  978. [_signIn disconnectWithCompletion:nil];
  979. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  980. // Emulate result back from server.
  981. NSError *error = [self error];
  982. [self didFetch:nil error:error];
  983. [_authorization verify];
  984. [_authState verify];
  985. [_tokenResponse verify];
  986. }
  987. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  988. - (void)testDisconnect_noTokens {
  989. [[[_authorization expect] andReturn:_authState] authState];
  990. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  991. [[[_tokenResponse expect] andReturn:nil] accessToken];
  992. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  993. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  994. XCTestExpectation *noTokensExpectation =
  995. [self expectationWithDescription:@"Callback called with nil error"];
  996. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  997. if (error == nil) {
  998. [noTokensExpectation fulfill];
  999. }
  1000. }];
  1001. [self waitForExpectations:@[noTokensExpectation] timeout:1];
  1002. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  1003. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  1004. [_authorization verify];
  1005. [_authState verify];
  1006. [_tokenResponse verify];
  1007. }
  1008. // Verifies disconnect clears keychain if no tokens are present.
  1009. - (void)testDisconnectNoCallback_noTokens {
  1010. [[[_authorization expect] andReturn:_authState] authState];
  1011. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1012. [[[_tokenResponse expect] andReturn:nil] accessToken];
  1013. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1014. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  1015. [_signIn disconnectWithCompletion:nil];
  1016. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  1017. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  1018. [_authorization verify];
  1019. [_authState verify];
  1020. [_tokenResponse verify];
  1021. }
  1022. - (void)testPresentingViewControllerException {
  1023. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1024. _presentingViewController = nil;
  1025. #elif TARGET_OS_OSX
  1026. _presentingWindow = nil;
  1027. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1028. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1029. XCTAssertThrows([_signIn signInWithPresentingViewController:_presentingViewController
  1030. #elif TARGET_OS_OSX
  1031. XCTAssertThrows([_signIn signInWithPresentingWindow:_presentingWindow
  1032. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1033. hint:_hint
  1034. completion:_completion]);
  1035. }
  1036. - (void)testClientIDMissingException {
  1037. #pragma GCC diagnostic push
  1038. #pragma GCC diagnostic ignored "-Wnonnull"
  1039. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  1040. #pragma GCC diagnostic pop
  1041. BOOL threw = NO;
  1042. @try {
  1043. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1044. [_signIn signInWithPresentingViewController:_presentingViewController
  1045. #elif TARGET_OS_OSX
  1046. [_signIn signInWithPresentingWindow:_presentingWindow
  1047. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1048. completion:nil];
  1049. } @catch (NSException *exception) {
  1050. threw = YES;
  1051. XCTAssertEqualObjects(exception.description,
  1052. @"You must specify |clientID| in |GIDConfiguration|");
  1053. } @finally {
  1054. }
  1055. XCTAssert(threw);
  1056. }
  1057. - (void)testSchemesNotSupportedException {
  1058. [_fakeMainBundle fakeMissingAllSchemes];
  1059. BOOL threw = NO;
  1060. @try {
  1061. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1062. [_signIn signInWithPresentingViewController:_presentingViewController
  1063. #elif TARGET_OS_OSX
  1064. [_signIn signInWithPresentingWindow:_presentingWindow
  1065. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1066. hint:_hint
  1067. completion:_completion];
  1068. } @catch (NSException *exception) {
  1069. threw = YES;
  1070. XCTAssertEqualObjects(exception.description,
  1071. @"Your app is missing support for the following URL schemes: "
  1072. "fakeclientid");
  1073. } @finally {
  1074. }
  1075. XCTAssert(threw);
  1076. }
  1077. #pragma mark - Restarting Authentication Tests
  1078. // Verifies that URL is not handled if there is no pending sign-in
  1079. - (void)testRequiringPendingSignIn {
  1080. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  1081. XCTAssertFalse(result);
  1082. }
  1083. #pragma mark - EMM tests
  1084. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1085. - (void)testEmmSupportRequestParameters {
  1086. OCMStub(
  1087. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1088. ).andDo(^(NSInvocation *invocation) {
  1089. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1090. });
  1091. [self OAuthLoginWithAddScopesFlow:NO
  1092. authError:nil
  1093. tokenError:nil
  1094. emmPasscodeInfoRequired:NO
  1095. keychainError:NO
  1096. restoredSignIn:NO
  1097. oldAccessToken:NO
  1098. modalCancel:NO];
  1099. NSString *systemName = [UIDevice currentDevice].systemName;
  1100. if ([systemName isEqualToString:@"iPhone OS"]) {
  1101. systemName = @"iOS";
  1102. }
  1103. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  1104. systemName, [UIDevice currentDevice].systemVersion];
  1105. NSDictionary<NSString *, NSObject *> *authParams =
  1106. _savedAuthorizationRequest.additionalParameters;
  1107. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1108. if (_isEligibleForEMM) {
  1109. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  1110. @"EMM support should match in auth request");
  1111. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  1112. @"OS version should match in auth request");
  1113. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  1114. @"EMM support should match in token request");
  1115. XCTAssertEqualObjects(tokenParams[@"device_os"],
  1116. expectedOSVersion,
  1117. @"OS version should match in token request");
  1118. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1119. @"no passcode info should be in token request");
  1120. } else {
  1121. XCTAssertNil(authParams[@"emm_support"],
  1122. @"EMM support should not be in auth request for unsupported OS");
  1123. XCTAssertNil(authParams[@"device_os"],
  1124. @"OS version should not be in auth request for unsupported OS");
  1125. XCTAssertNil(tokenParams[@"emm_support"],
  1126. @"EMM support should not be in token request for unsupported OS");
  1127. XCTAssertNil(tokenParams[@"device_os"],
  1128. @"OS version should not be in token request for unsupported OS");
  1129. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1130. @"passcode info should not be in token request for unsupported OS");
  1131. }
  1132. }
  1133. - (void)testEmmPasscodeInfo {
  1134. OCMStub(
  1135. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1136. ).andDo(^(NSInvocation *invocation) {
  1137. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1138. });
  1139. [self OAuthLoginWithAddScopesFlow:NO
  1140. authError:nil
  1141. tokenError:nil
  1142. emmPasscodeInfoRequired:YES
  1143. keychainError:NO
  1144. restoredSignIn:NO
  1145. oldAccessToken:NO
  1146. modalCancel:NO];
  1147. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1148. if (_isEligibleForEMM) {
  1149. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  1150. @"passcode info should be in token request");
  1151. } else {
  1152. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1153. @"passcode info should not be in token request for unsupported OS");
  1154. }
  1155. }
  1156. - (void)testAuthEndpointEMMError {
  1157. if (!_isEligibleForEMM) {
  1158. return;
  1159. }
  1160. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  1161. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  1162. __block void (^completion)(void);
  1163. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  1164. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  1165. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  1166. [self OAuthLoginWithAddScopesFlow:NO
  1167. authError:callbackParams[@"error"]
  1168. tokenError:nil
  1169. emmPasscodeInfoRequired:NO
  1170. keychainError:NO
  1171. restoredSignIn:NO
  1172. oldAccessToken:NO
  1173. modalCancel:NO];
  1174. [mockEMMErrorHandler verify];
  1175. [mockEMMErrorHandler stopMocking];
  1176. completion();
  1177. [self waitForExpectationsWithTimeout:1 handler:nil];
  1178. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1179. XCTAssertTrue(_completionCalled, @"should call delegate");
  1180. XCTAssertNotNil(_authError, @"should have error");
  1181. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1182. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1183. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1184. }
  1185. - (void)testTokenEndpointEMMError {
  1186. if (!_isEligibleForEMM) {
  1187. return;
  1188. }
  1189. __block void (^completion)(NSError *);
  1190. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  1191. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  1192. code:12345
  1193. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  1194. id emmSupport = OCMStrictClassMock([GIDEMMSupport class]);
  1195. [[emmSupport expect] handleTokenFetchEMMError:emmError
  1196. completion:SAVE_TO_ARG_BLOCK(completion)];
  1197. [self OAuthLoginWithAddScopesFlow:NO
  1198. authError:nil
  1199. tokenError:emmError
  1200. emmPasscodeInfoRequired:NO
  1201. keychainError:NO
  1202. restoredSignIn:NO
  1203. oldAccessToken:NO
  1204. modalCancel:NO];
  1205. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  1206. code:kGIDSignInErrorCodeEMM
  1207. userInfo:emmError.userInfo];
  1208. completion(handledError);
  1209. [self waitForExpectationsWithTimeout:1 handler:nil];
  1210. [emmSupport verify];
  1211. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1212. XCTAssertTrue(_completionCalled, @"should call delegate");
  1213. XCTAssertNotNil(_authError, @"should have error");
  1214. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1215. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1216. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1217. }
  1218. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1219. #pragma mark - Helpers
  1220. // Whether or not a fetcher has been started.
  1221. - (BOOL)isFetcherStarted {
  1222. NSUInteger count = _fetcherService.fetchers.count;
  1223. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  1224. return !!count;
  1225. }
  1226. // Gets the URL being fetched.
  1227. - (NSURL *)fetchedURL {
  1228. return [_fetcherService.fetchers[0] requestURL];
  1229. }
  1230. // Emulates server returning the data as in JSON.
  1231. - (void)didFetch:(id)dataObject error:(NSError *)error {
  1232. NSData *data = nil;
  1233. if (dataObject) {
  1234. NSError *jsonError = nil;
  1235. data = [NSJSONSerialization dataWithJSONObject:dataObject
  1236. options:0
  1237. error:&jsonError];
  1238. XCTAssertNil(jsonError, @"must provide valid data");
  1239. }
  1240. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  1241. }
  1242. - (NSError *)error {
  1243. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  1244. }
  1245. // Verifies a fetcher has started for revoking token and emulates a server response.
  1246. - (void)verifyAndRevokeToken:(NSString *)token
  1247. hasCallback:(BOOL)hasCallback
  1248. waitingForExpectations:(NSArray<XCTestExpectation *> *)expectations {
  1249. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  1250. NSURL *url = [self fetchedURL];
  1251. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  1252. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  1253. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  1254. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  1255. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  1256. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  1257. @"token parameter should match");
  1258. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  1259. @"SDK version logging parameter should match");
  1260. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  1261. @"Environment logging parameter should match");
  1262. // Emulate result back from server.
  1263. [self didFetch:nil error:nil];
  1264. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  1265. if (hasCallback) {
  1266. [self waitForExpectations:expectations timeout:1];
  1267. }
  1268. }
  1269. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1270. authError:(NSString *)authError
  1271. tokenError:(NSError *)tokenError
  1272. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1273. keychainError:(BOOL)keychainError
  1274. restoredSignIn:(BOOL)restoredSignIn
  1275. oldAccessToken:(BOOL)oldAccessToken
  1276. modalCancel:(BOOL)modalCancel {
  1277. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  1278. authError:authError
  1279. tokenError:tokenError
  1280. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  1281. keychainError:keychainError
  1282. restoredSignIn:restoredSignIn
  1283. oldAccessToken:oldAccessToken
  1284. modalCancel:modalCancel
  1285. useAdditionalScopes:NO
  1286. additionalScopes:nil
  1287. manualNonce:nil
  1288. tokenClaims:nil];
  1289. }
  1290. // The authorization flow with parameters to control which branches to take.
  1291. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1292. authError:(NSString *)authError
  1293. tokenError:(NSError *)tokenError
  1294. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1295. keychainError:(BOOL)keychainError
  1296. restoredSignIn:(BOOL)restoredSignIn
  1297. oldAccessToken:(BOOL)oldAccessToken
  1298. modalCancel:(BOOL)modalCancel
  1299. useAdditionalScopes:(BOOL)useAdditionalScopes
  1300. additionalScopes:(NSArray *)additionalScopes
  1301. manualNonce:(NSString *)nonce
  1302. tokenClaims:(NSSet *)tokenClaims {
  1303. if (restoredSignIn) {
  1304. // clearAndAuthenticateWithOptions
  1305. [[[_authorization expect] andReturn:_authState] authState];
  1306. BOOL isAuthorized = restoredSignIn;
  1307. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1308. }
  1309. NSDictionary<NSString *, NSString *> *additionalParameters = emmPasscodeInfoRequired ?
  1310. @{ @"emm_passcode_info_required" : @"1" } : nil;
  1311. OIDAuthorizationResponse *authResponse =
  1312. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1313. nonce:nonce
  1314. errorString:authError];
  1315. OIDTokenResponse *tokenResponse =
  1316. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  1317. accessToken:restoredSignIn ? kAccessToken : nil
  1318. expiresIn:oldAccessToken ? @(300) : nil
  1319. refreshToken:kRefreshToken
  1320. tokenRequest:nil];
  1321. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1322. initWithConfiguration:authResponse.request.configuration
  1323. grantType:OIDGrantTypeRefreshToken
  1324. authorizationCode:nil
  1325. redirectURL:nil
  1326. clientID:authResponse.request.clientID
  1327. clientSecret:authResponse.request.clientSecret
  1328. scope:nil
  1329. refreshToken:kRefreshToken
  1330. codeVerifier:nil
  1331. additionalParameters:tokenResponse.request.additionalParameters];
  1332. if (restoredSignIn) {
  1333. // maybeFetchToken
  1334. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1335. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1336. if (oldAccessToken) {
  1337. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1338. // Corresponds to EMM support
  1339. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1340. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1341. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1342. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1343. [[[_authState expect] andReturn:tokenRequest]
  1344. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1345. }
  1346. } else {
  1347. XCTestExpectation *newAccessTokenExpectation =
  1348. [self expectationWithDescription:@"Callback called"];
  1349. GIDSignInCompletion completion = ^(GIDSignInResult *_Nullable signInResult,
  1350. NSError * _Nullable error) {
  1351. [newAccessTokenExpectation fulfill];
  1352. if (signInResult) {
  1353. XCTAssertEqualObjects(signInResult.serverAuthCode, kServerAuthCode);
  1354. } else {
  1355. XCTAssertNotNil(error, @"Should have an error if the signInResult is nil");
  1356. }
  1357. XCTAssertFalse(self->_completionCalled, @"callback already called");
  1358. self->_completionCalled = YES;
  1359. self->_authError = error;
  1360. };
  1361. if (addScopesFlow) {
  1362. [_signIn addScopes:@[kNewScope]
  1363. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1364. presentingViewController:_presentingViewController
  1365. #elif TARGET_OS_OSX
  1366. presentingWindow:_presentingWindow
  1367. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1368. completion:completion];
  1369. } else {
  1370. if (useAdditionalScopes) {
  1371. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1372. [_signIn signInWithPresentingViewController:_presentingViewController
  1373. #elif TARGET_OS_OSX
  1374. [_signIn signInWithPresentingWindow:_presentingWindow
  1375. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1376. hint:_hint
  1377. additionalScopes:additionalScopes
  1378. completion:completion];
  1379. } else {
  1380. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1381. [_signIn signInWithPresentingViewController:_presentingViewController
  1382. #elif TARGET_OS_OSX
  1383. [_signIn signInWithPresentingWindow:_presentingWindow
  1384. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1385. hint:_hint
  1386. additionalScopes:nil
  1387. nonce:nonce
  1388. tokenClaims:tokenClaims
  1389. completion:completion];
  1390. }
  1391. }
  1392. [_authorization verify];
  1393. [_authState verify];
  1394. XCTAssertNotNil(_savedAuthorizationRequest);
  1395. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1396. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1397. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1398. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1399. XCTAssertNotNil(_savedAuthorizationCallback);
  1400. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1401. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1402. #elif TARGET_OS_OSX
  1403. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1404. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1405. // maybeFetchToken
  1406. if (!(authError || modalCancel)) {
  1407. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1408. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1409. // Corresponds to EMM support
  1410. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1411. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1412. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1413. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1414. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1415. }
  1416. // Simulate auth endpoint response
  1417. if (modalCancel) {
  1418. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1419. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1420. userInfo:nil];
  1421. _savedAuthorizationCallback(nil, error);
  1422. } else {
  1423. _savedAuthorizationCallback(authResponse, nil);
  1424. }
  1425. if (authError || modalCancel) {
  1426. return;
  1427. }
  1428. [_authState verify];
  1429. }
  1430. if (restoredSignIn && oldAccessToken) {
  1431. XCTestExpectation *callbackShouldBeCalledExpectation =
  1432. [self expectationWithDescription:@"Callback should be called"];
  1433. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1434. NSError * _Nullable error) {
  1435. [callbackShouldBeCalledExpectation fulfill];
  1436. XCTAssertNil(error, @"should have no error");
  1437. }];
  1438. }
  1439. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1440. XCTAssertNotNil(_savedTokenRequest);
  1441. XCTAssertNotNil(_savedTokenCallback);
  1442. // OIDTokenCallback
  1443. if (tokenError) {
  1444. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1445. } else {
  1446. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1447. }
  1448. }
  1449. if (tokenError) {
  1450. _savedTokenCallback(nil, tokenError);
  1451. return;
  1452. }
  1453. // DecodeIdTokenCallback
  1454. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1455. // SaveAuthCallback
  1456. __block OIDAuthState *authState;
  1457. __block OIDTokenResponse *updatedTokenResponse;
  1458. __block OIDAuthorizationResponse *updatedAuthorizationResponse;
  1459. __block GIDProfileData *profileData;
  1460. if (keychainError) {
  1461. _saveAuthorizationReturnValue = NO;
  1462. } else {
  1463. if (addScopesFlow) {
  1464. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1465. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1466. [[_user expect] updateWithTokenResponse:SAVE_TO_ARG_BLOCK(updatedTokenResponse)
  1467. authorizationResponse:SAVE_TO_ARG_BLOCK(updatedAuthorizationResponse)
  1468. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1469. } else {
  1470. [[[_user expect] andReturn:_user] alloc];
  1471. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1472. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1473. }
  1474. }
  1475. // CompletionCallback - mock server auth code parsing
  1476. if (!keychainError) {
  1477. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1478. }
  1479. if (restoredSignIn && !oldAccessToken) {
  1480. XCTestExpectation *restoredSignInExpectation = [self expectationWithDescription:@"Callback should be called"];
  1481. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1482. NSError * _Nullable error) {
  1483. [restoredSignInExpectation fulfill];
  1484. XCTAssertNil(error, @"should have no error");
  1485. }];
  1486. } else {
  1487. // Simulate token endpoint response.
  1488. _savedTokenCallback(tokenResponse, nil);
  1489. }
  1490. if (keychainError) {
  1491. return;
  1492. }
  1493. [self waitForExpectationsWithTimeout:1 handler:nil];
  1494. [_authState verify];
  1495. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1496. if (addScopesFlow) {
  1497. XCTAssertNotNil(updatedTokenResponse);
  1498. XCTAssertNotNil(updatedAuthorizationResponse);
  1499. } else {
  1500. XCTAssertNotNil(authState);
  1501. }
  1502. // Check fat ID token decoding
  1503. XCTAssertEqualObjects(profileData.name, kFatName);
  1504. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1505. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1506. XCTAssertTrue(profileData.hasImage);
  1507. // If attempt to authenticate again, will reuse existing auth object.
  1508. _completionCalled = NO;
  1509. _keychainRemoved = NO;
  1510. _keychainSaved = NO;
  1511. _authError = nil;
  1512. __block GIDGoogleUserCompletion completion;
  1513. [[_user expect] refreshTokensIfNeededWithCompletion:SAVE_TO_ARG_BLOCK(completion)];
  1514. XCTestExpectation *restorePreviousSignInExpectation =
  1515. [self expectationWithDescription:@"Callback should be called"];
  1516. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1517. NSError * _Nullable error) {
  1518. [restorePreviousSignInExpectation fulfill];
  1519. XCTAssertNil(error, @"should have no error");
  1520. }];
  1521. completion(_user, nil);
  1522. [self waitForExpectationsWithTimeout:1 handler:nil];
  1523. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1524. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1525. if (restoredSignIn) {
  1526. // Ignore the return value
  1527. OCMVerify((void)[_keychainStore retrieveAuthSessionWithError:OCMArg.anyObjectRef]);
  1528. OCMVerify([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]);
  1529. }
  1530. }
  1531. @end