GIDSignInTest.m 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  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. #import "GoogleSignIn/Sources/GIDClaimsInternalOptions.h"
  30. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  31. #import <AppCheckCore/GACAppCheckToken.h>
  32. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/GIDAppCheck.h"
  33. #import "GoogleSignIn/Sources/GIDAppCheck/Implementations/Fake/GIDAppCheckProviderFake.h"
  34. #import "GoogleSignIn/Sources/GIDEMMErrorHandler.h"
  35. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  36. #import "GoogleSignIn/Sources/GIDAuthStateMigration/Fake/GIDFakeAuthStateMigration.h"
  37. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcher.h"
  38. #import "GoogleSignIn/Tests/Unit/GIDFakeFetcherService.h"
  39. #import "GoogleSignIn/Tests/Unit/GIDFakeMainBundle.h"
  40. #import "GoogleSignIn/Tests/Unit/OIDAuthorizationResponse+Testing.h"
  41. #import "GoogleSignIn/Tests/Unit/OIDTokenResponse+Testing.h"
  42. #ifdef SWIFT_PACKAGE
  43. @import AppAuth;
  44. @import GTMSessionFetcherCore;
  45. @import OCMock;
  46. #else
  47. #import <AppAuth/OIDAuthState.h>
  48. #import <AppAuth/OIDAuthorizationRequest.h>
  49. #import <AppAuth/OIDAuthorizationResponse.h>
  50. #import <AppAuth/OIDAuthorizationService.h>
  51. #import <AppAuth/OIDError.h>
  52. #import <AppAuth/OIDGrantTypes.h>
  53. #import <AppAuth/OIDTokenRequest.h>
  54. #import <AppAuth/OIDTokenResponse.h>
  55. #import <AppAuth/OIDURLQueryComponent.h>
  56. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  57. #import <AppAuth/OIDAuthorizationService+IOS.h>
  58. #elif TARGET_OS_OSX
  59. #import <AppAuth/OIDAuthorizationService+Mac.h>
  60. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  61. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  62. #import <OCMock/OCMock.h>
  63. #endif
  64. // Create a BLOCK to store the actual address for arg in param.
  65. #define SAVE_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  66. param = arg;\
  67. return YES;\
  68. }]
  69. #define COPY_TO_ARG_BLOCK(param) [OCMArg checkWithBlock:^(id arg) {\
  70. param = [arg copy];\
  71. return YES;\
  72. }]
  73. /// `NSUserDefaults` suite name for testing with `GIDAppCheck`.
  74. static NSString *const kUserDefaultsSuiteName = @"GIDAppCheckKeySuiteName";
  75. static NSString * const kFakeGaiaID = @"123456789";
  76. static NSString * const kFakeIDToken = @"FakeIDToken";
  77. static NSString * const kClientId = @"FakeClientID";
  78. static NSString * const kDotReversedClientId = @"FakeClientID";
  79. static NSString * const kClientId2 = @"FakeClientID2";
  80. static NSString * const kServerClientId = @"FakeServerClientID";
  81. static NSString * const kLanguage = @"FakeLanguage";
  82. static NSString * const kScope = @"FakeScope";
  83. static NSString * const kScope2 = @"FakeScope2";
  84. static NSString * const kAuthCode = @"FakeAuthCode";
  85. static NSString * const kKeychainName = @"auth";
  86. static NSString * const kUserEmail = @"FakeUserEmail";
  87. static NSString * const kVerifier = @"FakeVerifier";
  88. static NSString * const kOpenIDRealm = @"FakeRealm";
  89. static NSString * const kFakeHostedDomain = @"fakehosteddomain.com";
  90. static NSString * const kFakeUserName = @"fake username";
  91. static NSString * const kFakeUserGivenName = @"fake";
  92. static NSString * const kFakeUserFamilyName = @"username";
  93. static NSString * const kFakeUserPictureURL = @"fake_user_picture_url";
  94. static NSString * const kContinueURL = @"com.google.UnitTests:/oauth2callback";
  95. static NSString * const kContinueURLWithClientID = @"FakeClientID:/oauth2callback";
  96. static NSString * const kWrongSchemeURL = @"wrong.app:/oauth2callback";
  97. static NSString * const kWrongPathURL = @"com.google.UnitTests:/wrong_path";
  98. static NSString * const kEMMRestartAuthURL =
  99. @"com.google.UnitTests:///emmcallback?action=restart_auth";
  100. static NSString * const kEMMWrongPathURL =
  101. @"com.google.UnitTests:///unknowcallback?action=restart_auth";
  102. static NSString * const kEMMWrongActionURL =
  103. @"com.google.UnitTests:///emmcallback?action=unrecognized";
  104. static NSString * const kDevicePolicyAppBundleID = @"com.google.DevicePolicy";
  105. static NSString * const kAppHasRunBeforeKey = @"GPP_AppHasRunBefore";
  106. static NSString * const kFingerprintKeychainName = @"fingerprint";
  107. static NSString * const kVerifierKeychainName = @"verifier";
  108. static NSString * const kVerifierKey = @"verifier";
  109. static NSString * const kOpenIDRealmKey = @"openid.realm";
  110. static NSString * const kSavedKeychainServiceName = @"saved-keychain";
  111. static NSString * const kKeychainAccountName = @"GooglePlus";
  112. static NSString * const kUserNameKey = @"name";
  113. static NSString * const kUserGivenNameKey = @"givenName";
  114. static NSString * const kUserFamilyNameKey = @"familyName";
  115. static NSString * const kUserImageKey = @"picture";
  116. static NSString * const kAppName = @"UnitTests";
  117. static NSString * const kUserIDKey = @"userID";
  118. static NSString * const kHostedDomainKey = @"hostedDomain";
  119. static NSString * const kIDTokenExpirationKey = @"idTokenExp";
  120. static NSString * const kScopeKey = @"scope";
  121. // Basic profile (Fat ID Token / userinfo endpoint) keys
  122. static NSString *const kBasicProfilePictureKey = @"picture";
  123. static NSString *const kBasicProfileNameKey = @"name";
  124. static NSString *const kBasicProfileGivenNameKey = @"given_name";
  125. static NSString *const kBasicProfileFamilyNameKey = @"family_name";
  126. static NSString * const kCustomKeychainName = @"CUSTOM_KEYCHAIN_NAME";
  127. static NSString * const kAddActivity = @"http://schemas.google.com/AddActivity";
  128. static NSString * const kErrorDomain = @"ERROR_DOMAIN";
  129. static NSInteger const kErrorCode = 212;
  130. static NSString *const kDriveScope = @"https://www.googleapis.com/auth/drive";
  131. static NSString *const kTokenURL = @"https://oauth2.googleapis.com/token";
  132. static NSString *const kFakeURL = @"http://foo.com";
  133. static NSString *const kEMMSupport = @"1";
  134. static NSString *const kGrantedScope = @"grantedScope";
  135. static NSString *const kNewScope = @"newScope";
  136. static NSString *const kEssentialAuthTimeClaimsJsonString =
  137. @"{\"id_token\":{\"auth_time\":{\"essential\":true}}}";
  138. static NSString *const kNonEssentialAuthTimeClaimsJsonString =
  139. @"{\"id_token\":{\"auth_time\":{\"essential\":false}}}";
  140. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  141. // This category is used to allow the test to swizzle a private method.
  142. @interface UIViewController (Testing)
  143. // This private method provides access to the window. It's declared here to avoid a warning about
  144. // an unrecognized selector in the test.
  145. - (UIWindow *)_window;
  146. @end
  147. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  148. // This class extension exposes GIDSignIn methods to our tests.
  149. @interface GIDSignIn ()
  150. // Exposing private method so we can call it to disambiguate between interactive and non-interactive
  151. // sign-in attempts for the purposes of testing the GIDSignInUIDelegate (which should not be
  152. // called in the case of a non-interactive sign in).
  153. - (void)authenticateMaybeInteractively:(BOOL)interactive withParams:(NSDictionary *)params;
  154. - (BOOL)assertValidPresentingViewContoller;
  155. @end
  156. @interface GIDSignInTest : XCTestCase {
  157. @private
  158. // Whether or not the OS version is eligible for EMM.
  159. BOOL _isEligibleForEMM;
  160. // Mock |OIDAuthState|.
  161. id _authState;
  162. // Mock |OIDTokenResponse|.
  163. id _tokenResponse;
  164. // Mock |OIDTokenRequest|.
  165. id _tokenRequest;
  166. // Mock |GTMAuthSession|.
  167. id _authorization;
  168. // Mock |GTMKeychainStore|.
  169. id _keychainStore;
  170. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  171. // Mock |UIViewController|.
  172. id _presentingViewController;
  173. #elif TARGET_OS_OSX
  174. // Mock |NSWindow|.
  175. id _presentingWindow;
  176. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  177. // Mock for |GIDGoogleUser|.
  178. id _user;
  179. // Mock for |OIDAuthorizationService|
  180. id _oidAuthorizationService;
  181. // Parameter saved from delegate call.
  182. NSError *_authError;
  183. // Whether callback block has been called.
  184. BOOL _completionCalled;
  185. // Fake for |GIDAuthStateMigration|.
  186. GIDFakeAuthStateMigration *_authStateMigrationService;
  187. // Fake fetcher service to emulate network requests.
  188. GIDFakeFetcherService *_fetcherService;
  189. // Fake [NSBundle mainBundle];
  190. GIDFakeMainBundle *_fakeMainBundle;
  191. // Whether |saveParamsToKeychainForName:authentication:| has been called.
  192. BOOL _keychainSaved;
  193. // Whether |removeAuthFromKeychainForName:| has been called.
  194. BOOL _keychainRemoved;
  195. // The |GIDSignIn| object being tested.
  196. GIDSignIn *_signIn;
  197. // The configuration to be used when testing |GIDSignIn|.
  198. GIDConfiguration *_configuration;
  199. // The login hint to be used when testing |GIDSignIn|.
  200. NSString *_hint;
  201. // The completion to be used when testing |GIDSignIn|.
  202. GIDSignInCompletion _completion;
  203. // The saved authorization request.
  204. OIDAuthorizationRequest *_savedAuthorizationRequest;
  205. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  206. // The saved presentingViewController from the authorization request.
  207. UIViewController *_savedPresentingViewController;
  208. #elif TARGET_OS_OSX
  209. // The saved presentingWindow from the authorization request.
  210. NSWindow *_savedPresentingWindow;
  211. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  212. // The saved authorization callback.
  213. OIDAuthorizationCallback _savedAuthorizationCallback;
  214. // The saved token request.
  215. OIDTokenRequest *_savedTokenRequest;
  216. // The saved token request callback.
  217. OIDTokenCallback _savedTokenCallback;
  218. // Status returned by saveAuthorization:toKeychainForName:
  219. BOOL _saveAuthorizationReturnValue;
  220. // Test userDefaults for use with `GIDAppCheck`
  221. NSUserDefaults *_testUserDefaults;
  222. }
  223. @end
  224. @implementation GIDSignInTest
  225. #pragma mark - Lifecycle
  226. - (void)setUp {
  227. [super setUp];
  228. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  229. _isEligibleForEMM = [UIDevice currentDevice].systemVersion.integerValue >= 9;
  230. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  231. _saveAuthorizationReturnValue = YES;
  232. // States
  233. _completionCalled = NO;
  234. _keychainSaved = NO;
  235. _keychainRemoved = NO;
  236. // Mocks
  237. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  238. _presentingViewController = OCMStrictClassMock([UIViewController class]);
  239. #elif TARGET_OS_OSX
  240. _presentingWindow = OCMStrictClassMock([NSWindow class]);
  241. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  242. _authState = OCMClassMock([OIDAuthState class]);
  243. OCMStub([_authState alloc]).andReturn(_authState);
  244. OCMStub([_authState initWithAuthorizationResponse:OCMOCK_ANY]).andReturn(_authState);
  245. _tokenResponse = OCMStrictClassMock([OIDTokenResponse class]);
  246. _tokenRequest = OCMStrictClassMock([OIDTokenRequest class]);
  247. _authorization = OCMStrictClassMock([GTMAuthSession class]);
  248. _keychainStore = OCMStrictClassMock([GTMKeychainStore class]);
  249. OCMStub(
  250. [_keychainStore retrieveAuthSessionWithItemName:OCMOCK_ANY error:OCMArg.anyObjectRef]
  251. ).andReturn(_authorization);
  252. OCMStub([_keychainStore retrieveAuthSessionWithError:nil]).andReturn(_authorization);
  253. OCMStub([_authorization alloc]).andReturn(_authorization);
  254. OCMStub([_authorization initWithAuthState:OCMOCK_ANY]).andReturn(_authorization);
  255. OCMStub(
  256. [_keychainStore removeAuthSessionWithError:OCMArg.anyObjectRef]
  257. ).andDo(^(NSInvocation *invocation) {
  258. self->_keychainRemoved = YES;
  259. });
  260. _user = OCMStrictClassMock([GIDGoogleUser class]);
  261. _oidAuthorizationService = OCMStrictClassMock([OIDAuthorizationService class]);
  262. OCMStub([_oidAuthorizationService
  263. presentAuthorizationRequest:SAVE_TO_ARG_BLOCK(self->_savedAuthorizationRequest)
  264. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  265. presentingViewController:SAVE_TO_ARG_BLOCK(self->_savedPresentingViewController)
  266. #elif TARGET_OS_OSX
  267. presentingWindow:SAVE_TO_ARG_BLOCK(self->_savedPresentingWindow)
  268. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  269. callback:COPY_TO_ARG_BLOCK(self->_savedAuthorizationCallback)]);
  270. OCMStub([self->_oidAuthorizationService
  271. performTokenRequest:SAVE_TO_ARG_BLOCK(self->_savedTokenRequest)
  272. originalAuthorizationResponse:[OCMArg any]
  273. callback:COPY_TO_ARG_BLOCK(self->_savedTokenCallback)]);
  274. // Fakes
  275. _authStateMigrationService = [[GIDFakeAuthStateMigration alloc] init];
  276. _fetcherService = [[GIDFakeFetcherService alloc] init];
  277. _fakeMainBundle = [[GIDFakeMainBundle alloc] init];
  278. [_fakeMainBundle startFakingWithClientID:kClientId];
  279. [_fakeMainBundle fakeAllSchemesSupported];
  280. // Object under test
  281. _testUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:kUserDefaultsSuiteName];
  282. [_testUserDefaults setBool:YES forKey:kAppHasRunBeforeKey];
  283. _signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  284. authStateMigrationService:_authStateMigrationService];
  285. _hint = nil;
  286. __weak GIDSignInTest *weakSelf = self;
  287. _completion = ^(GIDSignInResult *_Nullable signInResult, NSError * _Nullable error) {
  288. GIDSignInTest *strongSelf = weakSelf;
  289. if (!signInResult) {
  290. XCTAssertNotNil(error, @"should have an error if the signInResult is nil");
  291. }
  292. XCTAssertFalse(strongSelf->_completionCalled, @"callback already called");
  293. strongSelf->_completionCalled = YES;
  294. strongSelf->_authError = error;
  295. };
  296. }
  297. - (void)tearDown {
  298. OCMVerifyAll(_authState);
  299. OCMVerifyAll(_tokenResponse);
  300. OCMVerifyAll(_tokenRequest);
  301. OCMVerifyAll(_authorization);
  302. OCMVerifyAll(_user);
  303. OCMVerifyAll(_oidAuthorizationService);
  304. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  305. OCMVerifyAll(_presentingViewController);
  306. #elif TARGET_OS_OSX
  307. OCMVerifyAll(_presentingWindow);
  308. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  309. [_testUserDefaults removePersistentDomainForName:kUserDefaultsSuiteName];
  310. [_fakeMainBundle stopFaking];
  311. [super tearDown];
  312. }
  313. #pragma mark - Tests
  314. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  315. - (void)testConfigureSucceeds {
  316. if (@available(iOS 14, *)) {
  317. XCTestExpectation *configureSucceedsExpecation =
  318. [self expectationWithDescription:@"Configure succeeds expectation"];
  319. GACAppCheckToken *token = [[GACAppCheckToken alloc] initWithToken:@"foo"
  320. expirationDate:[NSDate distantFuture]];
  321. GIDAppCheckProviderFake *fakeProvider =
  322. [[GIDAppCheckProviderFake alloc] initWithAppCheckToken:token error:nil];
  323. GIDAppCheck *appCheck = [[GIDAppCheck alloc] initWithAppCheckProvider:fakeProvider
  324. userDefaults:_testUserDefaults];
  325. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  326. authStateMigrationService:_authStateMigrationService
  327. appCheck:appCheck];
  328. [signIn configureWithCompletion:^(NSError * _Nullable error) {
  329. XCTAssertNil(error);
  330. [configureSucceedsExpecation fulfill];
  331. }];
  332. [self waitForExpectations:@[configureSucceedsExpecation] timeout:1];
  333. XCTAssertTrue(appCheck.isPrepared);
  334. }
  335. }
  336. - (void)testConfigureFailsNoTokenOrError {
  337. if (@available(iOS 14, *)) {
  338. XCTestExpectation *configureFailsExpecation =
  339. [self expectationWithDescription:@"Configure fails expectation"];
  340. GIDAppCheckProviderFake *fakeProvider =
  341. [[GIDAppCheckProviderFake alloc] initWithAppCheckToken:nil error:nil];
  342. GIDAppCheck *appCheck =
  343. [[GIDAppCheck alloc] initWithAppCheckProvider:fakeProvider
  344. userDefaults:_testUserDefaults];
  345. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:_keychainStore
  346. authStateMigrationService:_authStateMigrationService
  347. appCheck:appCheck];
  348. // Should fail if missing both token and error
  349. [signIn configureWithCompletion:^(NSError * _Nullable error) {
  350. XCTAssertNotNil(error);
  351. XCTAssertEqual(error.code, kGIDAppCheckUnexpectedError);
  352. [configureFailsExpecation fulfill];
  353. }];
  354. [self waitForExpectations:@[configureFailsExpecation] timeout:1];
  355. XCTAssertFalse(appCheck.isPrepared);
  356. }
  357. }
  358. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  359. - (void)testInitWithKeychainStore {
  360. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  361. GIDSignIn *signIn;
  362. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  363. authStateMigrationService:_authStateMigrationService];
  364. XCTAssertNotNil(signIn.configuration);
  365. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  366. XCTAssertNil(signIn.configuration.serverClientID);
  367. XCTAssertNil(signIn.configuration.hostedDomain);
  368. XCTAssertNil(signIn.configuration.openIDRealm);
  369. }
  370. - (void)testInitWithKeychainStore_noConfig {
  371. [_fakeMainBundle fakeWithClientID:nil
  372. serverClientID:nil
  373. hostedDomain:nil
  374. openIDRealm:nil];
  375. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  376. GIDSignIn *signIn;
  377. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  378. authStateMigrationService:_authStateMigrationService];
  379. XCTAssertNil(signIn.configuration);
  380. }
  381. - (void)testInitWithKeychainStore_fullConfig {
  382. [_fakeMainBundle fakeWithClientID:kClientId
  383. serverClientID:kServerClientId
  384. hostedDomain:kFakeHostedDomain
  385. openIDRealm:kOpenIDRealm];
  386. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  387. GIDSignIn *signIn;
  388. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  389. authStateMigrationService:_authStateMigrationService];
  390. XCTAssertNotNil(signIn.configuration);
  391. XCTAssertEqual(signIn.configuration.clientID, kClientId);
  392. XCTAssertEqual(signIn.configuration.serverClientID, kServerClientId);
  393. XCTAssertEqual(signIn.configuration.hostedDomain, kFakeHostedDomain);
  394. XCTAssertEqual(signIn.configuration.openIDRealm, kOpenIDRealm);
  395. }
  396. - (void)testInitWithKeychainStore_invalidConfig {
  397. [_fakeMainBundle fakeWithClientID:@[ @"bad", @"config", @"values" ]
  398. serverClientID:nil
  399. hostedDomain:nil
  400. openIDRealm:nil];
  401. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:@"foo"];
  402. GIDSignIn *signIn;
  403. signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  404. authStateMigrationService:_authStateMigrationService];
  405. XCTAssertNil(signIn.configuration);
  406. }
  407. - (void)testInitWithKeychainStore_attemptsMigration {
  408. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  409. _authStateMigrationService.migrationInvokedCallback =
  410. ^(NSURL *tokenURL, NSString *callbackPath, BOOL isFreshInstall) {
  411. XCTAssertFalse(isFreshInstall);
  412. [expectation fulfill];
  413. };
  414. GTMKeychainStore *store = [[GTMKeychainStore alloc] initWithItemName:kKeychainName];
  415. GIDSignIn *signIn = [[GIDSignIn alloc] initWithKeychainStore:store
  416. authStateMigrationService:_authStateMigrationService];
  417. XCTAssertNotNil(signIn.configuration);
  418. [self waitForExpectationsWithTimeout:1 handler:nil];
  419. }
  420. - (void)testRestorePreviousSignInNoRefresh_hasPreviousUser {
  421. [[[_authorization stub] andReturn:_authState] authState];
  422. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  423. [[_authorization expect] setDelegate:OCMOCK_ANY];
  424. #endif // TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  425. OCMStub([_authState lastTokenResponse]).andReturn(_tokenResponse);
  426. OCMStub([_authState refreshToken]).andReturn(kRefreshToken);
  427. [[_authState expect] setStateChangeDelegate:OCMOCK_ANY];
  428. id idTokenDecoded = OCMClassMock([OIDIDToken class]);
  429. OCMStub([idTokenDecoded alloc]).andReturn(idTokenDecoded);
  430. OCMStub([idTokenDecoded initWithIDTokenString:OCMOCK_ANY]).andReturn(idTokenDecoded);
  431. OCMStub([idTokenDecoded subject]).andReturn(kFakeGaiaID);
  432. // Mock generating a GIDConfiguration when initializing GIDGoogleUser.
  433. OIDAuthorizationResponse *authResponse =
  434. [OIDAuthorizationResponse testInstance];
  435. OCMStub([_authState lastAuthorizationResponse]).andReturn(authResponse);
  436. OCMStub([_tokenResponse idToken]).andReturn(kFakeIDToken);
  437. OCMStub([_tokenResponse request]).andReturn(_tokenRequest);
  438. OCMStub([_tokenRequest additionalParameters]).andReturn(nil);
  439. OCMStub([_tokenResponse accessToken]).andReturn(kAccessToken);
  440. OCMStub([_tokenResponse accessTokenExpirationDate]).andReturn(nil);
  441. [_signIn restorePreviousSignInNoRefresh];
  442. [idTokenDecoded verify];
  443. XCTAssertEqual(_signIn.currentUser.userID, kFakeGaiaID);
  444. [idTokenDecoded stopMocking];
  445. }
  446. - (void)testRestoredPreviousSignInNoRefresh_hasNoPreviousUser {
  447. [[[_authorization expect] andReturn:nil] authState];
  448. [_signIn restorePreviousSignInNoRefresh];
  449. [_authorization verify];
  450. XCTAssertNil(_signIn.currentUser);
  451. }
  452. - (void)testHasPreviousSignIn_HasBeenAuthenticated {
  453. [[[_authorization expect] andReturn:_authState] authState];
  454. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  455. XCTAssertTrue([_signIn hasPreviousSignIn], @"should return |YES|");
  456. [_authorization verify];
  457. [_authState verify];
  458. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  459. XCTAssertFalse(_completionCalled, @"should not call delegate");
  460. XCTAssertNil(_authError, @"should have no error");
  461. }
  462. - (void)testHasPreviousSignIn_HasNotBeenAuthenticated {
  463. [[[_authorization expect] andReturn:_authState] authState];
  464. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  465. XCTAssertFalse([_signIn hasPreviousSignIn], @"should return |NO|");
  466. [_authorization verify];
  467. [_authState verify];
  468. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  469. XCTAssertFalse(_completionCalled, @"should not call delegate");
  470. }
  471. - (void)testRestorePreviousSignInWhenSignedOut {
  472. [[[_authorization expect] andReturn:_authState] authState];
  473. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  474. _completionCalled = NO;
  475. _authError = nil;
  476. XCTestExpectation *expectation = [self expectationWithDescription:@"Callback should be called."];
  477. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser *_Nullable user,
  478. NSError * _Nullable error) {
  479. [expectation fulfill];
  480. XCTAssertNotNil(error, @"error should not have been nil");
  481. XCTAssertEqual(error.domain,
  482. kGIDSignInErrorDomain,
  483. @"error domain should have been the sign-in error domain.");
  484. XCTAssertEqual(error.code,
  485. kGIDSignInErrorCodeHasNoAuthInKeychain,
  486. @"error code should have been the 'NoAuthInKeychain' error code.");
  487. }];
  488. [self waitForExpectationsWithTimeout:1 handler:nil];
  489. [_authorization verify];
  490. [_authState verify];
  491. }
  492. - (void)testNotRestorePreviousSignInWhenSignedOutAndCompletionIsNil {
  493. [[[_authorization expect] andReturn:_authState] authState];
  494. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:NO]] isAuthorized];
  495. [_signIn restorePreviousSignInWithCompletion:nil];
  496. XCTAssertNil(_signIn.currentUser);
  497. }
  498. - (void)testRestorePreviousSignInWhenCompletionIsNil {
  499. [[[_authorization expect] andReturn:_authState] authState];
  500. [[_keychainStore expect] saveAuthSession:OCMOCK_ANY error:[OCMArg anyObjectRef]];
  501. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:YES]] isAuthorized];
  502. OIDTokenResponse *tokenResponse =
  503. [OIDTokenResponse testInstanceWithIDToken:[OIDTokenResponse fatIDToken]
  504. accessToken:kAccessToken
  505. expiresIn:nil
  506. refreshToken:kRefreshToken
  507. tokenRequest:nil];
  508. [[[_authState stub] andReturn:tokenResponse] lastTokenResponse];
  509. // TODO: Create a real GIDGoogleUser to verify the signed in user value(#306).
  510. [[[_user stub] andReturn:_user] alloc];
  511. (void)[[[_user expect] andReturn:_user] initWithAuthState:OCMOCK_ANY
  512. profileData:OCMOCK_ANY];
  513. XCTAssertNil(_signIn.currentUser);
  514. [_signIn restorePreviousSignInWithCompletion:nil];
  515. XCTAssertNotNil(_signIn.currentUser);
  516. }
  517. - (void)testOAuthLogin {
  518. OCMStub(
  519. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  520. ).andDo(^(NSInvocation *invocation) {
  521. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  522. });
  523. [self OAuthLoginWithAddScopesFlow:NO
  524. authError:nil
  525. tokenError:nil
  526. emmPasscodeInfoRequired:NO
  527. claimsAsJSONRequired:NO
  528. keychainError:NO
  529. restoredSignIn:NO
  530. oldAccessToken:NO
  531. modalCancel:NO];
  532. }
  533. - (void)testOAuthLogin_RestoredSignIn {
  534. OCMStub(
  535. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  536. ).andDo(^(NSInvocation *invocation) {
  537. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  538. });
  539. [self OAuthLoginWithAddScopesFlow:NO
  540. authError:nil
  541. tokenError:nil
  542. emmPasscodeInfoRequired:NO
  543. claimsAsJSONRequired:NO
  544. keychainError:NO
  545. restoredSignIn:YES
  546. oldAccessToken:NO
  547. modalCancel:NO];
  548. }
  549. - (void)testOAuthLogin_RestoredSignInOldAccessToken {
  550. OCMStub(
  551. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  552. ).andDo(^(NSInvocation *invocation) {
  553. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  554. });
  555. [self OAuthLoginWithAddScopesFlow:NO
  556. authError:nil
  557. tokenError:nil
  558. emmPasscodeInfoRequired:NO
  559. claimsAsJSONRequired:NO
  560. keychainError:NO
  561. restoredSignIn:YES
  562. oldAccessToken:YES
  563. modalCancel:NO];
  564. }
  565. - (void)testOAuthLogin_AdditionalScopes {
  566. NSString *expectedScopeString;
  567. OCMStub(
  568. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  569. ).andDo(^(NSInvocation *invocation) {
  570. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  571. });
  572. [self OAuthLoginWithAddScopesFlow:NO
  573. authError:nil
  574. tokenError:nil
  575. emmPasscodeInfoRequired:NO
  576. claimsAsJSONRequired:NO
  577. keychainError:NO
  578. claimsError:NO
  579. restoredSignIn:NO
  580. oldAccessToken:NO
  581. modalCancel:NO
  582. useAdditionalScopes:YES
  583. additionalScopes:nil
  584. manualNonce:nil
  585. claims:nil];
  586. expectedScopeString = [@[ @"email", @"profile" ] componentsJoinedByString:@" "];
  587. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  588. [self OAuthLoginWithAddScopesFlow:NO
  589. authError:nil
  590. tokenError:nil
  591. emmPasscodeInfoRequired:NO
  592. claimsAsJSONRequired:NO
  593. keychainError:NO
  594. claimsError:NO
  595. restoredSignIn:NO
  596. oldAccessToken:NO
  597. modalCancel:NO
  598. useAdditionalScopes:YES
  599. additionalScopes:@[ kScope ]
  600. manualNonce:nil
  601. claims:nil];
  602. expectedScopeString = [@[ kScope, @"email", @"profile" ] componentsJoinedByString:@" "];
  603. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  604. [self OAuthLoginWithAddScopesFlow:NO
  605. authError:nil
  606. tokenError:nil
  607. emmPasscodeInfoRequired:NO
  608. claimsAsJSONRequired:NO
  609. keychainError:NO
  610. claimsError:NO
  611. restoredSignIn:NO
  612. oldAccessToken:NO
  613. modalCancel:NO
  614. useAdditionalScopes:YES
  615. additionalScopes:@[ kScope, kScope2 ]
  616. manualNonce:nil
  617. claims:nil];
  618. expectedScopeString = [@[ kScope, kScope2, @"email", @"profile" ] componentsJoinedByString:@" "];
  619. XCTAssertEqualObjects(_savedAuthorizationRequest.scope, expectedScopeString);
  620. }
  621. - (void)testOAuthLogin_WithClaims_FormatsParametersCorrectly {
  622. GIDClaim *authTimeClaim = [GIDClaim authTimeClaim];
  623. GIDClaim *essentialAuthTimeClaim = [GIDClaim essentialAuthTimeClaim];
  624. OCMStub([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  625. ).andDo(^(NSInvocation *invocation){
  626. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  627. });
  628. [self OAuthLoginWithAddScopesFlow:NO
  629. authError:nil
  630. tokenError:nil
  631. emmPasscodeInfoRequired:NO
  632. claimsAsJSONRequired:NO
  633. keychainError:NO
  634. claimsError:NO
  635. restoredSignIn:NO
  636. oldAccessToken:NO
  637. modalCancel:NO
  638. useAdditionalScopes:NO
  639. additionalScopes:nil
  640. manualNonce:nil
  641. claims:[NSSet setWithObject:essentialAuthTimeClaim]];
  642. XCTAssertEqualObjects(_savedAuthorizationRequest.additionalParameters[@"claims"],
  643. kEssentialAuthTimeClaimsJsonString,
  644. @"Claims JSON should be correctly formatted");
  645. [self OAuthLoginWithAddScopesFlow:NO
  646. authError:nil
  647. tokenError:nil
  648. emmPasscodeInfoRequired:NO
  649. claimsAsJSONRequired:NO
  650. keychainError:NO
  651. claimsError:NO
  652. restoredSignIn:NO
  653. oldAccessToken:NO
  654. modalCancel:NO
  655. useAdditionalScopes:NO
  656. additionalScopes:nil
  657. manualNonce:nil
  658. claims:[NSSet setWithObject:authTimeClaim]];
  659. XCTAssertEqualObjects(_savedAuthorizationRequest.additionalParameters[@"claims"],
  660. kNonEssentialAuthTimeClaimsJsonString,
  661. @"Claims JSON should be correctly formatted");
  662. }
  663. - (void)testOAuthLogin_WithClaims_ReturnsIdTokenWithCorrectClaims {
  664. GIDClaim *authTimeClaim = [GIDClaim authTimeClaim];
  665. OCMStub([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  666. ).andDo(^(NSInvocation *invocation){
  667. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  668. });
  669. [self OAuthLoginWithAddScopesFlow:NO
  670. authError:nil
  671. tokenError:nil
  672. emmPasscodeInfoRequired:NO
  673. claimsAsJSONRequired:NO
  674. keychainError:NO
  675. claimsError:NO
  676. restoredSignIn:NO
  677. oldAccessToken:NO
  678. modalCancel:NO
  679. useAdditionalScopes:NO
  680. additionalScopes:nil
  681. manualNonce:nil
  682. claims:[NSSet setWithObject:authTimeClaim]];
  683. XCTAssertNotNil(_signIn.currentUser, @"The currentUser should not be nil after a successful sign-in.");
  684. NSString *idTokenString = _signIn.currentUser.idToken.tokenString;
  685. XCTAssertNotNil(idTokenString, @"ID token string should not be nil.");
  686. NSArray<NSString *> *components = [idTokenString componentsSeparatedByString:@"."];
  687. XCTAssertEqual(components.count, 3, @"JWT should have 3 parts.");
  688. NSData *payloadData = [[NSData alloc]
  689. initWithBase64EncodedString:components[1]
  690. options:NSDataBase64DecodingIgnoreUnknownCharacters];
  691. NSDictionary *claims = [NSJSONSerialization JSONObjectWithData:payloadData options:0 error:nil];
  692. XCTAssertEqualObjects(claims[@"auth_time"],
  693. kAuthTime,
  694. @"The 'auth_time' claim should be present and correct.");
  695. }
  696. - (void)testAddScopes {
  697. // Restore the previous sign-in account. This is the preparation for adding scopes.
  698. OCMStub(
  699. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  700. ).andDo(^(NSInvocation *invocation) {
  701. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  702. });
  703. [self OAuthLoginWithAddScopesFlow:NO
  704. authError:nil
  705. tokenError:nil
  706. emmPasscodeInfoRequired:NO
  707. claimsAsJSONRequired:NO
  708. keychainError:NO
  709. restoredSignIn:YES
  710. oldAccessToken:NO
  711. modalCancel:NO];
  712. XCTAssertNotNil(_signIn.currentUser);
  713. id profile = OCMStrictClassMock([GIDProfileData class]);
  714. OCMStub([profile email]).andReturn(kUserEmail);
  715. // Mock for the method `addScopes`.
  716. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  717. serverClientID:nil
  718. hostedDomain:nil
  719. openIDRealm:kOpenIDRealm];
  720. OCMStub([_user configuration]).andReturn(configuration);
  721. OCMStub([_user profile]).andReturn(profile);
  722. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  723. OCMStub([_user authState]).andReturn(_authState);
  724. [self OAuthLoginWithAddScopesFlow:YES
  725. authError:nil
  726. tokenError:nil
  727. emmPasscodeInfoRequired:NO
  728. claimsAsJSONRequired:NO
  729. keychainError:NO
  730. restoredSignIn:NO
  731. oldAccessToken:NO
  732. modalCancel:NO];
  733. NSArray<NSString *> *grantedScopes;
  734. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  735. if (grantedScopeString) {
  736. grantedScopeString = [grantedScopeString stringByTrimmingCharactersInSet:
  737. [NSCharacterSet whitespaceCharacterSet]];
  738. // Tokenize with space as a delimiter.
  739. NSMutableArray<NSString *> *parsedScopes =
  740. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  741. // Remove empty strings.
  742. [parsedScopes removeObject:@""];
  743. grantedScopes = [parsedScopes copy];
  744. }
  745. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  746. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  747. [_user verify];
  748. [profile verify];
  749. [profile stopMocking];
  750. }
  751. - (void)testAddScopes_WithPreviouslyRequestedClaims {
  752. GIDClaim *authTimeClaim = [GIDClaim authTimeClaim];
  753. // Restore the previous sign-in account. This is the preparation for adding scopes.
  754. OCMStub(
  755. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  756. ).andDo(^(NSInvocation *invocation) {
  757. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  758. });
  759. [self OAuthLoginWithAddScopesFlow:NO
  760. authError:nil
  761. tokenError:nil
  762. emmPasscodeInfoRequired:NO
  763. claimsAsJSONRequired:NO
  764. keychainError:NO
  765. claimsError:NO
  766. restoredSignIn:NO
  767. oldAccessToken:NO
  768. modalCancel:NO
  769. useAdditionalScopes:NO
  770. additionalScopes:nil
  771. manualNonce:nil
  772. claims:[NSSet setWithObject:authTimeClaim]];
  773. XCTAssertNotNil(_signIn.currentUser);
  774. id profile = OCMStrictClassMock([GIDProfileData class]);
  775. OCMStub([profile email]).andReturn(kUserEmail);
  776. GIDConfiguration *configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  777. serverClientID:nil
  778. hostedDomain:nil
  779. openIDRealm:kOpenIDRealm];
  780. OCMStub([_user configuration]).andReturn(configuration);
  781. OCMStub([_user profile]).andReturn(profile);
  782. OCMStub([_user grantedScopes]).andReturn(@[kGrantedScope]);
  783. OCMStub([_user authState]).andReturn(_authState);
  784. [self OAuthLoginWithAddScopesFlow:YES
  785. authError:nil
  786. tokenError:nil
  787. emmPasscodeInfoRequired:NO
  788. claimsAsJSONRequired:YES
  789. keychainError:NO
  790. restoredSignIn:NO
  791. oldAccessToken:NO
  792. modalCancel:NO];
  793. NSArray<NSString *> *grantedScopes;
  794. NSString *grantedScopeString = _savedAuthorizationRequest.scope;
  795. if (grantedScopeString) {
  796. NSCharacterSet *whiteSpaceChars = [NSCharacterSet whitespaceCharacterSet];
  797. grantedScopeString =
  798. [grantedScopeString stringByTrimmingCharactersInSet:whiteSpaceChars];
  799. NSMutableArray<NSString *> *parsedScopes =
  800. [[grantedScopeString componentsSeparatedByString:@" "] mutableCopy];
  801. [parsedScopes removeObject:@""];
  802. grantedScopes = [parsedScopes copy];
  803. }
  804. NSArray<NSString *> *expectedScopes = @[kNewScope, kGrantedScope];
  805. XCTAssertEqualObjects(grantedScopes, expectedScopes);
  806. XCTAssertEqualObjects(_savedAuthorizationRequest.additionalParameters[@"claims"],
  807. kNonEssentialAuthTimeClaimsJsonString,
  808. @"Claims JSON should be correctly formatted");
  809. [_user verify];
  810. [profile verify];
  811. }
  812. - (void)testOpenIDRealm {
  813. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  814. serverClientID:nil
  815. hostedDomain:nil
  816. openIDRealm:kOpenIDRealm];
  817. OCMStub(
  818. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  819. ).andDo(^(NSInvocation *invocation) {
  820. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  821. });
  822. [self OAuthLoginWithAddScopesFlow:NO
  823. authError:nil
  824. tokenError:nil
  825. emmPasscodeInfoRequired:NO
  826. claimsAsJSONRequired:NO
  827. keychainError:NO
  828. restoredSignIn:NO
  829. oldAccessToken:NO
  830. modalCancel:NO];
  831. NSDictionary<NSString *, NSString *> *params = _savedTokenRequest.additionalParameters;
  832. XCTAssertEqual(params[kOpenIDRealmKey], kOpenIDRealm, @"OpenID Realm should match.");
  833. }
  834. - (void)testManualNonce {
  835. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  836. serverClientID:nil
  837. hostedDomain:nil
  838. openIDRealm:kOpenIDRealm];
  839. OCMStub(
  840. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  841. ).andDo(^(NSInvocation *invocation) {
  842. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  843. });
  844. NSString* manualNonce = @"manual_nonce";
  845. [self OAuthLoginWithAddScopesFlow:NO
  846. authError:nil
  847. tokenError:nil
  848. emmPasscodeInfoRequired:NO
  849. claimsAsJSONRequired:NO
  850. keychainError:NO
  851. claimsError:NO
  852. restoredSignIn:NO
  853. oldAccessToken:NO
  854. modalCancel:NO
  855. useAdditionalScopes:NO
  856. additionalScopes:@[]
  857. manualNonce:manualNonce
  858. claims:nil];
  859. XCTAssertEqualObjects(_savedAuthorizationRequest.nonce,
  860. manualNonce,
  861. @"Provided nonce should match nonce in authorization request.");
  862. }
  863. - (void)testOAuthLogin_LoginHint {
  864. _hint = kUserEmail;
  865. OCMStub(
  866. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  867. ).andDo(^(NSInvocation *invocation) {
  868. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  869. });
  870. [self OAuthLoginWithAddScopesFlow:NO
  871. authError:nil
  872. tokenError:nil
  873. emmPasscodeInfoRequired:NO
  874. claimsAsJSONRequired:NO
  875. keychainError:NO
  876. restoredSignIn:NO
  877. oldAccessToken:NO
  878. modalCancel:NO];
  879. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  880. XCTAssertEqualObjects(params[@"login_hint"], kUserEmail, @"login hint should match");
  881. }
  882. - (void)testOAuthLogin_HostedDomain {
  883. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:kClientId
  884. serverClientID:nil
  885. hostedDomain:kHostedDomain
  886. openIDRealm:nil];
  887. OCMStub(
  888. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  889. ).andDo(^(NSInvocation *invocation) {
  890. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  891. });
  892. [self OAuthLoginWithAddScopesFlow:NO
  893. authError:nil
  894. tokenError:nil
  895. emmPasscodeInfoRequired:NO
  896. claimsAsJSONRequired:NO
  897. keychainError:NO
  898. restoredSignIn:NO
  899. oldAccessToken:NO
  900. modalCancel:NO];
  901. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  902. XCTAssertEqualObjects(params[@"hd"], kHostedDomain, @"hosted domain should match");
  903. }
  904. - (void)testOAuthLogin_ConsentCanceled {
  905. [self OAuthLoginWithAddScopesFlow:NO
  906. authError:@"access_denied"
  907. tokenError:nil
  908. emmPasscodeInfoRequired:NO
  909. claimsAsJSONRequired:NO
  910. keychainError:NO
  911. restoredSignIn:NO
  912. oldAccessToken:NO
  913. modalCancel:NO];
  914. [self waitForExpectationsWithTimeout:1 handler:nil];
  915. XCTAssertTrue(_completionCalled, @"should call delegate");
  916. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  917. }
  918. - (void)testOAuthLogin_ModalCanceled {
  919. [self OAuthLoginWithAddScopesFlow:NO
  920. authError:nil
  921. tokenError:nil
  922. emmPasscodeInfoRequired:NO
  923. claimsAsJSONRequired:NO
  924. keychainError:NO
  925. restoredSignIn:NO
  926. oldAccessToken:NO
  927. modalCancel:YES];
  928. [self waitForExpectationsWithTimeout:1 handler:nil];
  929. XCTAssertTrue(_completionCalled, @"should call delegate");
  930. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeCanceled);
  931. }
  932. - (void)testOAuthLogin_KeychainError {
  933. // This error is going be overidden by `-[GIDSignIn errorWithString:code:]`
  934. // We just need to fill in the error so that happens.
  935. NSError *keychainError = [NSError errorWithDomain:@"com.googleSignIn.throwAway"
  936. code:1
  937. userInfo:nil];
  938. OCMStub(
  939. [_keychainStore saveAuthSession:OCMOCK_ANY error:[OCMArg setTo:keychainError]]
  940. ).andDo(^(NSInvocation *invocation) {
  941. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  942. });
  943. [self OAuthLoginWithAddScopesFlow:NO
  944. authError:nil
  945. tokenError:nil
  946. emmPasscodeInfoRequired:NO
  947. claimsAsJSONRequired:NO
  948. keychainError:YES
  949. restoredSignIn:NO
  950. oldAccessToken:NO
  951. modalCancel:NO];
  952. [self waitForExpectationsWithTimeout:1 handler:nil];
  953. XCTAssertFalse(_keychainSaved, @"should save to keychain");
  954. XCTAssertTrue(_completionCalled, @"should call delegate");
  955. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  956. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeKeychain);
  957. }
  958. - (void)testOAuthLogin_Claims_FailsWithError {
  959. GIDClaim *authTimeClaim = [GIDClaim authTimeClaim];
  960. GIDClaim *essentialAuthTimeClaim = [GIDClaim essentialAuthTimeClaim];
  961. NSSet *conflictingClaims = [NSSet setWithObjects:authTimeClaim, essentialAuthTimeClaim, nil];
  962. [self OAuthLoginWithAddScopesFlow:NO
  963. authError:nil
  964. tokenError:nil
  965. emmPasscodeInfoRequired:NO
  966. claimsAsJSONRequired:NO
  967. keychainError:NO
  968. claimsError:YES
  969. restoredSignIn:NO
  970. oldAccessToken:NO
  971. modalCancel:NO
  972. useAdditionalScopes:NO
  973. additionalScopes:nil
  974. manualNonce:nil
  975. claims:conflictingClaims];
  976. // Wait for the completion handler to be called
  977. [self waitForExpectationsWithTimeout:1.0 handler:nil];
  978. XCTAssertNotNil(_authError, @"An error object should have been returned.");
  979. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeAmbiguousClaims,
  980. @"The error code should be for ambiguous claims.");
  981. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain,
  982. @"The error domain should be the GIDSignIn error domain.");
  983. XCTAssertEqualObjects(_authError.localizedDescription, kGIDClaimErrorDescription,
  984. @"The error description should clearly explain the ambiguity.");
  985. }
  986. - (void)testSignOut {
  987. #if TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  988. // OCMStub([_authorization authState]).andReturn(_authState);
  989. #endif // TARGET_OS_IOS || !TARGET_OS_MACCATALYST
  990. OCMStub([_authorization fetcherService]).andReturn(_fetcherService);
  991. OCMStub(
  992. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  993. ).andDo(^(NSInvocation *invocation) {
  994. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  995. });
  996. // Sign in a user so that we can then sign them out.
  997. [self OAuthLoginWithAddScopesFlow:NO
  998. authError:nil
  999. tokenError:nil
  1000. emmPasscodeInfoRequired:NO
  1001. claimsAsJSONRequired:NO
  1002. keychainError:NO
  1003. restoredSignIn:YES
  1004. oldAccessToken:NO
  1005. modalCancel:NO];
  1006. XCTAssertNotNil(_signIn.currentUser);
  1007. [_signIn signOut];
  1008. XCTAssertNil(_signIn.currentUser, @"should not have a current user");
  1009. XCTAssertTrue(_keychainRemoved, @"should remove keychain");
  1010. OCMVerify([_keychainStore removeAuthSessionWithError:OCMArg.anyObjectRef]);
  1011. }
  1012. - (void)testNotHandleWrongScheme {
  1013. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongSchemeURL]],
  1014. @"should not handle URL");
  1015. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1016. XCTAssertFalse(_completionCalled, @"should not call delegate");
  1017. }
  1018. - (void)testNotHandleWrongPath {
  1019. XCTAssertFalse([_signIn handleURL:[NSURL URLWithString:kWrongPathURL]], @"should not handle URL");
  1020. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1021. XCTAssertFalse(_completionCalled, @"should not call delegate");
  1022. }
  1023. #pragma mark - Tests - disconnectWithCallback:
  1024. // Verifies disconnect calls callback with no errors if access token is present.
  1025. - (void)testDisconnect_accessToken {
  1026. [[[_authorization expect] andReturn:_authState] authState];
  1027. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1028. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  1029. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  1030. XCTestExpectation *accessTokenExpectation =
  1031. [self expectationWithDescription:@"Callback called with nil error"];
  1032. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  1033. if (error == nil) {
  1034. [accessTokenExpectation fulfill];
  1035. }
  1036. }];
  1037. [self verifyAndRevokeToken:kAccessToken
  1038. hasCallback:YES
  1039. waitingForExpectations:@[accessTokenExpectation]];
  1040. [_authorization verify];
  1041. [_authState verify];
  1042. [_tokenResponse verify];
  1043. }
  1044. // Verifies disconnect if access token is present.
  1045. - (void)testDisconnectNoCallback_accessToken {
  1046. [[[_authorization expect] andReturn:_authState] authState];
  1047. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1048. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  1049. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  1050. [_signIn disconnectWithCompletion:nil];
  1051. [self verifyAndRevokeToken:kAccessToken hasCallback:NO waitingForExpectations:@[]];
  1052. [_authorization verify];
  1053. [_authState verify];
  1054. [_tokenResponse verify];
  1055. }
  1056. // Verifies disconnect calls callback with no errors if refresh token is present.
  1057. - (void)testDisconnect_refreshToken {
  1058. [[[_authorization expect] andReturn:_authState] authState];
  1059. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1060. [[[_tokenResponse expect] andReturn:nil] accessToken];
  1061. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1062. [[[_tokenResponse expect] andReturn:kRefreshToken] refreshToken];
  1063. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  1064. XCTestExpectation *refreshTokenExpectation =
  1065. [self expectationWithDescription:@"Callback called with nil error"];
  1066. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  1067. if (error == nil) {
  1068. [refreshTokenExpectation fulfill];
  1069. }
  1070. }];
  1071. [self verifyAndRevokeToken:kRefreshToken
  1072. hasCallback:YES
  1073. waitingForExpectations:@[refreshTokenExpectation]];
  1074. [_authorization verify];
  1075. [_authState verify];
  1076. [_tokenResponse verify];
  1077. }
  1078. // Verifies disconnect errors are passed along to the callback.
  1079. - (void)testDisconnect_errors {
  1080. [[[_authorization expect] andReturn:_authState] authState];
  1081. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1082. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  1083. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  1084. XCTestExpectation *errorExpectation =
  1085. [self expectationWithDescription:@"Callback called with an error"];
  1086. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  1087. if (error != nil) {
  1088. [errorExpectation fulfill];
  1089. }
  1090. }];
  1091. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  1092. // Emulate result back from server.
  1093. NSError *error = [self error];
  1094. [self didFetch:nil error:error];
  1095. [self waitForExpectations:@[errorExpectation] timeout:1];
  1096. [_authorization verify];
  1097. [_authState verify];
  1098. [_tokenResponse verify];
  1099. }
  1100. // Verifies disconnect with errors
  1101. - (void)testDisconnectNoCallback_errors {
  1102. [[[_authorization expect] andReturn:_authState] authState];
  1103. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1104. [[[_tokenResponse expect] andReturn:kAccessToken] accessToken];
  1105. [[[_authorization expect] andReturn:_fetcherService] fetcherService];
  1106. [_signIn disconnectWithCompletion:nil];
  1107. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  1108. // Emulate result back from server.
  1109. NSError *error = [self error];
  1110. [self didFetch:nil error:error];
  1111. [_authorization verify];
  1112. [_authState verify];
  1113. [_tokenResponse verify];
  1114. }
  1115. // Verifies disconnect calls callback with no errors and clears keychain if no tokens are present.
  1116. - (void)testDisconnect_noTokens {
  1117. [[[_authorization expect] andReturn:_authState] authState];
  1118. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1119. [[[_tokenResponse expect] andReturn:nil] accessToken];
  1120. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1121. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  1122. XCTestExpectation *noTokensExpectation =
  1123. [self expectationWithDescription:@"Callback called with nil error"];
  1124. [_signIn disconnectWithCompletion:^(NSError * _Nullable error) {
  1125. if (error == nil) {
  1126. [noTokensExpectation fulfill];
  1127. }
  1128. }];
  1129. [self waitForExpectations:@[noTokensExpectation] timeout:1];
  1130. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  1131. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  1132. [_authorization verify];
  1133. [_authState verify];
  1134. [_tokenResponse verify];
  1135. }
  1136. // Verifies disconnect clears keychain if no tokens are present.
  1137. - (void)testDisconnectNoCallback_noTokens {
  1138. [[[_authorization expect] andReturn:_authState] authState];
  1139. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1140. [[[_tokenResponse expect] andReturn:nil] accessToken];
  1141. [[[_authState expect] andReturn:_tokenResponse] lastTokenResponse];
  1142. [[[_tokenResponse expect] andReturn:nil] refreshToken];
  1143. [_signIn disconnectWithCompletion:nil];
  1144. XCTAssertFalse([self isFetcherStarted], @"should not fetch");
  1145. XCTAssertTrue(_keychainRemoved, @"keychain should be removed");
  1146. [_authorization verify];
  1147. [_authState verify];
  1148. [_tokenResponse verify];
  1149. }
  1150. - (void)testPresentingViewControllerException {
  1151. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1152. _presentingViewController = nil;
  1153. #elif TARGET_OS_OSX
  1154. _presentingWindow = nil;
  1155. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1156. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1157. XCTAssertThrows([_signIn signInWithPresentingViewController:_presentingViewController
  1158. #elif TARGET_OS_OSX
  1159. XCTAssertThrows([_signIn signInWithPresentingWindow:_presentingWindow
  1160. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1161. hint:_hint
  1162. completion:_completion]);
  1163. }
  1164. - (void)testClientIDMissingException {
  1165. #pragma GCC diagnostic push
  1166. #pragma GCC diagnostic ignored "-Wnonnull"
  1167. _signIn.configuration = [[GIDConfiguration alloc] initWithClientID:nil];
  1168. #pragma GCC diagnostic pop
  1169. BOOL threw = NO;
  1170. @try {
  1171. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1172. [_signIn signInWithPresentingViewController:_presentingViewController
  1173. #elif TARGET_OS_OSX
  1174. [_signIn signInWithPresentingWindow:_presentingWindow
  1175. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1176. completion:nil];
  1177. } @catch (NSException *exception) {
  1178. threw = YES;
  1179. XCTAssertEqualObjects(exception.description,
  1180. @"You must specify |clientID| in |GIDConfiguration|");
  1181. } @finally {
  1182. }
  1183. XCTAssert(threw);
  1184. }
  1185. - (void)testSchemesNotSupportedException {
  1186. [_fakeMainBundle fakeMissingAllSchemes];
  1187. BOOL threw = NO;
  1188. @try {
  1189. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1190. [_signIn signInWithPresentingViewController:_presentingViewController
  1191. #elif TARGET_OS_OSX
  1192. [_signIn signInWithPresentingWindow:_presentingWindow
  1193. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1194. hint:_hint
  1195. completion:_completion];
  1196. } @catch (NSException *exception) {
  1197. threw = YES;
  1198. XCTAssertEqualObjects(exception.description,
  1199. @"Your app is missing support for the following URL schemes: "
  1200. "fakeclientid");
  1201. } @finally {
  1202. }
  1203. XCTAssert(threw);
  1204. }
  1205. #pragma mark - Restarting Authentication Tests
  1206. // Verifies that URL is not handled if there is no pending sign-in
  1207. - (void)testRequiringPendingSignIn {
  1208. BOOL result = [_signIn handleURL:[NSURL URLWithString:kEMMRestartAuthURL]];
  1209. XCTAssertFalse(result);
  1210. }
  1211. #pragma mark - EMM tests
  1212. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1213. - (void)testEmmSupportRequestParameters {
  1214. OCMStub(
  1215. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1216. ).andDo(^(NSInvocation *invocation) {
  1217. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1218. });
  1219. [self OAuthLoginWithAddScopesFlow:NO
  1220. authError:nil
  1221. tokenError:nil
  1222. emmPasscodeInfoRequired:NO
  1223. claimsAsJSONRequired:NO
  1224. keychainError:NO
  1225. restoredSignIn:NO
  1226. oldAccessToken:NO
  1227. modalCancel:NO];
  1228. NSString *systemName = [UIDevice currentDevice].systemName;
  1229. if ([systemName isEqualToString:@"iPhone OS"]) {
  1230. systemName = @"iOS";
  1231. }
  1232. NSString *expectedOSVersion = [NSString stringWithFormat:@"%@ %@",
  1233. systemName, [UIDevice currentDevice].systemVersion];
  1234. NSDictionary<NSString *, NSObject *> *authParams =
  1235. _savedAuthorizationRequest.additionalParameters;
  1236. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1237. if (_isEligibleForEMM) {
  1238. XCTAssertEqualObjects(authParams[@"emm_support"], kEMMSupport,
  1239. @"EMM support should match in auth request");
  1240. XCTAssertEqualObjects(authParams[@"device_os"], expectedOSVersion,
  1241. @"OS version should match in auth request");
  1242. XCTAssertEqualObjects(tokenParams[@"emm_support"], kEMMSupport,
  1243. @"EMM support should match in token request");
  1244. XCTAssertEqualObjects(tokenParams[@"device_os"],
  1245. expectedOSVersion,
  1246. @"OS version should match in token request");
  1247. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1248. @"no passcode info should be in token request");
  1249. } else {
  1250. XCTAssertNil(authParams[@"emm_support"],
  1251. @"EMM support should not be in auth request for unsupported OS");
  1252. XCTAssertNil(authParams[@"device_os"],
  1253. @"OS version should not be in auth request for unsupported OS");
  1254. XCTAssertNil(tokenParams[@"emm_support"],
  1255. @"EMM support should not be in token request for unsupported OS");
  1256. XCTAssertNil(tokenParams[@"device_os"],
  1257. @"OS version should not be in token request for unsupported OS");
  1258. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1259. @"passcode info should not be in token request for unsupported OS");
  1260. }
  1261. }
  1262. - (void)testEmmPasscodeInfo {
  1263. OCMStub(
  1264. [_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]
  1265. ).andDo(^(NSInvocation *invocation) {
  1266. self->_keychainSaved = self->_saveAuthorizationReturnValue;
  1267. });
  1268. [self OAuthLoginWithAddScopesFlow:NO
  1269. authError:nil
  1270. tokenError:nil
  1271. emmPasscodeInfoRequired:YES
  1272. claimsAsJSONRequired:NO
  1273. keychainError:NO
  1274. restoredSignIn:NO
  1275. oldAccessToken:NO
  1276. modalCancel:NO];
  1277. NSDictionary<NSString *, NSString *> *tokenParams = _savedTokenRequest.additionalParameters;
  1278. if (_isEligibleForEMM) {
  1279. XCTAssertNotNil(tokenParams[@"emm_passcode_info"],
  1280. @"passcode info should be in token request");
  1281. } else {
  1282. XCTAssertNil(tokenParams[@"emm_passcode_info"],
  1283. @"passcode info should not be in token request for unsupported OS");
  1284. }
  1285. }
  1286. - (void)testAuthEndpointEMMError {
  1287. if (!_isEligibleForEMM) {
  1288. return;
  1289. }
  1290. id mockEMMErrorHandler = OCMStrictClassMock([GIDEMMErrorHandler class]);
  1291. [[[mockEMMErrorHandler stub] andReturn:mockEMMErrorHandler] sharedInstance];
  1292. __block void (^completion)(void);
  1293. NSDictionary<NSString *, NSString *> *callbackParams = @{ @"error" : @"EMM Specific Error" };
  1294. [[[mockEMMErrorHandler expect] andReturnValue:@YES]
  1295. handleErrorFromResponse:callbackParams completion:SAVE_TO_ARG_BLOCK(completion)];
  1296. [self OAuthLoginWithAddScopesFlow:NO
  1297. authError:callbackParams[@"error"]
  1298. tokenError:nil
  1299. emmPasscodeInfoRequired:NO
  1300. claimsAsJSONRequired:NO
  1301. keychainError:NO
  1302. restoredSignIn:NO
  1303. oldAccessToken:NO
  1304. modalCancel:NO];
  1305. [mockEMMErrorHandler verify];
  1306. [mockEMMErrorHandler stopMocking];
  1307. completion();
  1308. [self waitForExpectationsWithTimeout:1 handler:nil];
  1309. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1310. XCTAssertTrue(_completionCalled, @"should call delegate");
  1311. XCTAssertNotNil(_authError, @"should have error");
  1312. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1313. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1314. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1315. }
  1316. - (void)testTokenEndpointEMMError {
  1317. if (!_isEligibleForEMM) {
  1318. return;
  1319. }
  1320. __block void (^completion)(NSError *);
  1321. NSDictionary *errorJSON = @{ @"error" : @"EMM Specific Error" };
  1322. NSError *emmError = [NSError errorWithDomain:@"anydomain"
  1323. code:12345
  1324. userInfo:@{ OIDOAuthErrorFieldError : errorJSON }];
  1325. id emmSupport = OCMStrictClassMock([GIDEMMSupport class]);
  1326. [[emmSupport expect] handleTokenFetchEMMError:emmError
  1327. completion:SAVE_TO_ARG_BLOCK(completion)];
  1328. [self OAuthLoginWithAddScopesFlow:NO
  1329. authError:nil
  1330. tokenError:emmError
  1331. emmPasscodeInfoRequired:NO
  1332. claimsAsJSONRequired:NO
  1333. keychainError:NO
  1334. restoredSignIn:NO
  1335. oldAccessToken:NO
  1336. modalCancel:NO];
  1337. NSError *handledError = [NSError errorWithDomain:kGIDSignInErrorDomain
  1338. code:kGIDSignInErrorCodeEMM
  1339. userInfo:emmError.userInfo];
  1340. completion(handledError);
  1341. [self waitForExpectationsWithTimeout:1 handler:nil];
  1342. [emmSupport verify];
  1343. XCTAssertFalse(_keychainSaved, @"should not save to keychain");
  1344. XCTAssertTrue(_completionCalled, @"should call delegate");
  1345. XCTAssertNotNil(_authError, @"should have error");
  1346. XCTAssertEqualObjects(_authError.domain, kGIDSignInErrorDomain);
  1347. XCTAssertEqual(_authError.code, kGIDSignInErrorCodeEMM);
  1348. XCTAssertNil(_signIn.currentUser, @"should not have current user");
  1349. }
  1350. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1351. #pragma mark - Helpers
  1352. // Whether or not a fetcher has been started.
  1353. - (BOOL)isFetcherStarted {
  1354. NSUInteger count = _fetcherService.fetchers.count;
  1355. XCTAssertTrue(count <= 1, @"Only one fetcher is supported");
  1356. return !!count;
  1357. }
  1358. // Gets the URL being fetched.
  1359. - (NSURL *)fetchedURL {
  1360. return [_fetcherService.fetchers[0] requestURL];
  1361. }
  1362. // Emulates server returning the data as in JSON.
  1363. - (void)didFetch:(id)dataObject error:(NSError *)error {
  1364. NSData *data = nil;
  1365. if (dataObject) {
  1366. NSError *jsonError = nil;
  1367. data = [NSJSONSerialization dataWithJSONObject:dataObject
  1368. options:0
  1369. error:&jsonError];
  1370. XCTAssertNil(jsonError, @"must provide valid data");
  1371. }
  1372. [_fetcherService.fetchers[0] didFinishWithData:data error:error];
  1373. }
  1374. - (NSError *)error {
  1375. return [NSError errorWithDomain:kErrorDomain code:kErrorCode userInfo:nil];
  1376. }
  1377. // Verifies a fetcher has started for revoking token and emulates a server response.
  1378. - (void)verifyAndRevokeToken:(NSString *)token
  1379. hasCallback:(BOOL)hasCallback
  1380. waitingForExpectations:(NSArray<XCTestExpectation *> *)expectations {
  1381. XCTAssertTrue([self isFetcherStarted], @"should start fetching");
  1382. NSURL *url = [self fetchedURL];
  1383. XCTAssertEqualObjects([url scheme], @"https", @"scheme must match");
  1384. XCTAssertEqualObjects([url host], @"accounts.google.com", @"host must match");
  1385. XCTAssertEqualObjects([url path], @"/o/oauth2/revoke", @"path must match");
  1386. OIDURLQueryComponent *queryComponent = [[OIDURLQueryComponent alloc] initWithURL:url];
  1387. NSDictionary<NSString *, NSObject<NSCopying> *> *params = queryComponent.dictionaryValue;
  1388. XCTAssertEqualObjects([params valueForKey:@"token"], token,
  1389. @"token parameter should match");
  1390. XCTAssertEqualObjects([params valueForKey:kSDKVersionLoggingParameter], GIDVersion(),
  1391. @"SDK version logging parameter should match");
  1392. XCTAssertEqualObjects([params valueForKey:kEnvironmentLoggingParameter], GIDEnvironment(),
  1393. @"Environment logging parameter should match");
  1394. // Emulate result back from server.
  1395. [self didFetch:nil error:nil];
  1396. XCTAssertTrue(_keychainRemoved, @"should clear saved keychain name");
  1397. if (hasCallback) {
  1398. [self waitForExpectations:expectations timeout:1];
  1399. }
  1400. }
  1401. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1402. authError:(NSString *)authError
  1403. tokenError:(NSError *)tokenError
  1404. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1405. claimsAsJSONRequired:(BOOL)claimsAsJSONRequired
  1406. keychainError:(BOOL)keychainError
  1407. restoredSignIn:(BOOL)restoredSignIn
  1408. oldAccessToken:(BOOL)oldAccessToken
  1409. modalCancel:(BOOL)modalCancel {
  1410. [self OAuthLoginWithAddScopesFlow:addScopesFlow
  1411. authError:authError
  1412. tokenError:tokenError
  1413. emmPasscodeInfoRequired:emmPasscodeInfoRequired
  1414. claimsAsJSONRequired:claimsAsJSONRequired
  1415. keychainError:keychainError
  1416. claimsError:NO
  1417. restoredSignIn:restoredSignIn
  1418. oldAccessToken:oldAccessToken
  1419. modalCancel:modalCancel
  1420. useAdditionalScopes:NO
  1421. additionalScopes:nil
  1422. manualNonce:nil
  1423. claims:nil];
  1424. }
  1425. // The authorization flow with parameters to control which branches to take.
  1426. - (void)OAuthLoginWithAddScopesFlow:(BOOL)addScopesFlow
  1427. authError:(NSString *)authError
  1428. tokenError:(NSError *)tokenError
  1429. emmPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1430. claimsAsJSONRequired:(BOOL)claimsAsJSONRequired
  1431. keychainError:(BOOL)keychainError
  1432. claimsError:(BOOL)claimsError
  1433. restoredSignIn:(BOOL)restoredSignIn
  1434. oldAccessToken:(BOOL)oldAccessToken
  1435. modalCancel:(BOOL)modalCancel
  1436. useAdditionalScopes:(BOOL)useAdditionalScopes
  1437. additionalScopes:(NSArray *)additionalScopes
  1438. manualNonce:(NSString *)nonce
  1439. claims:(NSSet *)claims {
  1440. if (restoredSignIn) {
  1441. // clearAndAuthenticateWithOptions
  1442. [[[_authorization expect] andReturn:_authState] authState];
  1443. BOOL isAuthorized = restoredSignIn;
  1444. [[[_authState expect] andReturnValue:[NSNumber numberWithBool:isAuthorized]] isAuthorized];
  1445. }
  1446. NSDictionary<NSString *, NSString *> *additionalParameters =
  1447. [self additionalParametersWithEMMPasscodeInfoRequired:emmPasscodeInfoRequired
  1448. claimsAsJSONRequired:claimsAsJSONRequired];
  1449. OIDAuthorizationResponse *authResponse =
  1450. [OIDAuthorizationResponse testInstanceWithAdditionalParameters:additionalParameters
  1451. nonce:nonce
  1452. errorString:authError];
  1453. NSString *idToken = claims ? [OIDTokenResponse fatIDTokenWithAuthTime] : [OIDTokenResponse fatIDToken];
  1454. OIDTokenResponse *tokenResponse =
  1455. [OIDTokenResponse testInstanceWithIDToken:idToken
  1456. accessToken:restoredSignIn ? kAccessToken : nil
  1457. expiresIn:oldAccessToken ? @(300) : nil
  1458. refreshToken:kRefreshToken
  1459. tokenRequest:nil];
  1460. if (claims) {
  1461. // Creating this stub to use `currentUser.idToken`.
  1462. id mockIDToken = OCMClassMock([GIDToken class]);
  1463. OCMStub([mockIDToken tokenString]).andReturn(tokenResponse.idToken);
  1464. OCMStub([_user idToken]).andReturn(mockIDToken);
  1465. }
  1466. OIDTokenRequest *tokenRequest = [[OIDTokenRequest alloc]
  1467. initWithConfiguration:authResponse.request.configuration
  1468. grantType:OIDGrantTypeRefreshToken
  1469. authorizationCode:nil
  1470. redirectURL:nil
  1471. clientID:authResponse.request.clientID
  1472. clientSecret:authResponse.request.clientSecret
  1473. scope:nil
  1474. refreshToken:kRefreshToken
  1475. codeVerifier:nil
  1476. additionalParameters:tokenResponse.request.additionalParameters];
  1477. if (restoredSignIn) {
  1478. // maybeFetchToken
  1479. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1480. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1481. if (oldAccessToken) {
  1482. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1483. // Corresponds to EMM support
  1484. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1485. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1486. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1487. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1488. [[[_authState expect] andReturn:tokenRequest]
  1489. tokenRefreshRequestWithAdditionalParameters:[OCMArg any]];
  1490. }
  1491. } else {
  1492. XCTestExpectation *newAccessTokenExpectation =
  1493. [self expectationWithDescription:@"Callback called"];
  1494. GIDSignInCompletion completion = ^(GIDSignInResult *_Nullable signInResult,
  1495. NSError * _Nullable error) {
  1496. [newAccessTokenExpectation fulfill];
  1497. if (signInResult) {
  1498. XCTAssertEqualObjects(signInResult.serverAuthCode, kServerAuthCode);
  1499. } else {
  1500. XCTAssertNotNil(error, @"Should have an error if the signInResult is nil");
  1501. }
  1502. XCTAssertFalse(self->_completionCalled, @"callback already called");
  1503. self->_completionCalled = YES;
  1504. self->_authError = error;
  1505. };
  1506. if (addScopesFlow) {
  1507. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1508. [_signIn addScopes:@[kNewScope]
  1509. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1510. presentingViewController:_presentingViewController
  1511. #elif TARGET_OS_OSX
  1512. presentingWindow:_presentingWindow
  1513. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1514. completion:completion];
  1515. } else {
  1516. if (useAdditionalScopes) {
  1517. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1518. [_signIn signInWithPresentingViewController:_presentingViewController
  1519. #elif TARGET_OS_OSX
  1520. [_signIn signInWithPresentingWindow:_presentingWindow
  1521. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1522. hint:_hint
  1523. additionalScopes:additionalScopes
  1524. completion:completion];
  1525. } else {
  1526. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1527. [_signIn signInWithPresentingViewController:_presentingViewController
  1528. #elif TARGET_OS_OSX
  1529. [_signIn signInWithPresentingWindow:_presentingWindow
  1530. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1531. hint:_hint
  1532. additionalScopes:nil
  1533. nonce:nonce
  1534. claims:claims
  1535. completion:completion];
  1536. }
  1537. }
  1538. // When token claims are invalid, sign-in fails skipping the entire authorization flow.
  1539. // Thus, no need to verify `_authorization` or `_authState` as they won't be generated.
  1540. if (claimsError) {
  1541. return;
  1542. }
  1543. [_authorization verify];
  1544. [_authState verify];
  1545. XCTAssertNotNil(_savedAuthorizationRequest);
  1546. NSDictionary<NSString *, NSObject *> *params = _savedAuthorizationRequest.additionalParameters;
  1547. XCTAssertEqualObjects(params[@"include_granted_scopes"], @"true");
  1548. XCTAssertEqualObjects(params[kSDKVersionLoggingParameter], GIDVersion());
  1549. XCTAssertEqualObjects(params[kEnvironmentLoggingParameter], GIDEnvironment());
  1550. XCTAssertNotNil(_savedAuthorizationCallback);
  1551. #if TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1552. XCTAssertEqual(_savedPresentingViewController, _presentingViewController);
  1553. #elif TARGET_OS_OSX
  1554. XCTAssertEqual(_savedPresentingWindow, _presentingWindow);
  1555. #endif // TARGET_OS_IOS || TARGET_OS_MACCATALYST
  1556. // maybeFetchToken
  1557. if (!(authError || modalCancel)) {
  1558. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1559. #if TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1560. // Corresponds to EMM support
  1561. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1562. #endif // TARGET_OS_IOS && !TARGET_OS_MACCATALYST
  1563. [[[_authState expect] andReturn:nil] lastTokenResponse];
  1564. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1565. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1566. }
  1567. // Simulate auth endpoint response
  1568. if (modalCancel) {
  1569. NSError *error = [NSError errorWithDomain:OIDGeneralErrorDomain
  1570. code:OIDErrorCodeUserCanceledAuthorizationFlow
  1571. userInfo:nil];
  1572. _savedAuthorizationCallback(nil, error);
  1573. } else {
  1574. _savedAuthorizationCallback(authResponse, nil);
  1575. }
  1576. if (authError || modalCancel) {
  1577. return;
  1578. }
  1579. [_authState verify];
  1580. }
  1581. if (restoredSignIn && oldAccessToken) {
  1582. XCTestExpectation *callbackShouldBeCalledExpectation =
  1583. [self expectationWithDescription:@"Callback should be called"];
  1584. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1585. NSError * _Nullable error) {
  1586. [callbackShouldBeCalledExpectation fulfill];
  1587. XCTAssertNil(error, @"should have no error");
  1588. }];
  1589. }
  1590. if (!restoredSignIn || (restoredSignIn && oldAccessToken)) {
  1591. XCTAssertNotNil(_savedTokenRequest);
  1592. XCTAssertNotNil(_savedTokenCallback);
  1593. // OIDTokenCallback
  1594. if (tokenError) {
  1595. [[_authState expect] updateWithTokenResponse:nil error:tokenError];
  1596. } else {
  1597. [[_authState expect] updateWithTokenResponse:[OCMArg any] error:nil];
  1598. }
  1599. }
  1600. if (tokenError) {
  1601. _savedTokenCallback(nil, tokenError);
  1602. return;
  1603. }
  1604. // DecodeIdTokenCallback
  1605. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1606. // SaveAuthCallback
  1607. __block OIDAuthState *authState;
  1608. __block OIDTokenResponse *updatedTokenResponse;
  1609. __block OIDAuthorizationResponse *updatedAuthorizationResponse;
  1610. __block GIDProfileData *profileData;
  1611. if (keychainError) {
  1612. _saveAuthorizationReturnValue = NO;
  1613. } else {
  1614. if (addScopesFlow) {
  1615. [[[_authState expect] andReturn:authResponse] lastAuthorizationResponse];
  1616. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1617. [[_user expect] updateWithTokenResponse:SAVE_TO_ARG_BLOCK(updatedTokenResponse)
  1618. authorizationResponse:SAVE_TO_ARG_BLOCK(updatedAuthorizationResponse)
  1619. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1620. } else {
  1621. [[[_user expect] andReturn:_user] alloc];
  1622. (void)[[[_user expect] andReturn:_user] initWithAuthState:SAVE_TO_ARG_BLOCK(authState)
  1623. profileData:SAVE_TO_ARG_BLOCK(profileData)];
  1624. }
  1625. }
  1626. // CompletionCallback - mock server auth code parsing
  1627. if (!keychainError) {
  1628. [[[_authState expect] andReturn:tokenResponse] lastTokenResponse];
  1629. }
  1630. if (restoredSignIn && !oldAccessToken) {
  1631. XCTestExpectation *restoredSignInExpectation = [self expectationWithDescription:@"Callback should be called"];
  1632. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1633. NSError * _Nullable error) {
  1634. [restoredSignInExpectation fulfill];
  1635. XCTAssertNil(error, @"should have no error");
  1636. }];
  1637. } else {
  1638. // Simulate token endpoint response.
  1639. _savedTokenCallback(tokenResponse, nil);
  1640. }
  1641. if (keychainError) {
  1642. return;
  1643. }
  1644. [self waitForExpectationsWithTimeout:1 handler:nil];
  1645. [_authState verify];
  1646. XCTAssertTrue(_keychainSaved, @"should save to keychain");
  1647. if (addScopesFlow) {
  1648. XCTAssertNotNil(updatedTokenResponse);
  1649. XCTAssertNotNil(updatedAuthorizationResponse);
  1650. } else {
  1651. XCTAssertNotNil(authState);
  1652. }
  1653. // Check fat ID token decoding
  1654. XCTAssertEqualObjects(profileData.name, kFatName);
  1655. XCTAssertEqualObjects(profileData.givenName, kFatGivenName);
  1656. XCTAssertEqualObjects(profileData.familyName, kFatFamilyName);
  1657. XCTAssertTrue(profileData.hasImage);
  1658. // If attempt to authenticate again, will reuse existing auth object.
  1659. _completionCalled = NO;
  1660. _keychainRemoved = NO;
  1661. _keychainSaved = NO;
  1662. _authError = nil;
  1663. __block GIDGoogleUserCompletion completion;
  1664. [[_user expect] refreshTokensIfNeededWithCompletion:SAVE_TO_ARG_BLOCK(completion)];
  1665. XCTestExpectation *restorePreviousSignInExpectation =
  1666. [self expectationWithDescription:@"Callback should be called"];
  1667. [_signIn restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
  1668. NSError * _Nullable error) {
  1669. [restorePreviousSignInExpectation fulfill];
  1670. XCTAssertNil(error, @"should have no error");
  1671. }];
  1672. completion(_user, nil);
  1673. [self waitForExpectationsWithTimeout:1 handler:nil];
  1674. XCTAssertFalse(_keychainRemoved, @"should not remove keychain");
  1675. XCTAssertFalse(_keychainSaved, @"should not save to keychain again");
  1676. if (restoredSignIn) {
  1677. // Ignore the return value
  1678. OCMVerify((void)[_keychainStore retrieveAuthSessionWithError:OCMArg.anyObjectRef]);
  1679. OCMVerify([_keychainStore saveAuthSession:OCMOCK_ANY error:OCMArg.anyObjectRef]);
  1680. }
  1681. }
  1682. #pragma mark - Private Helpers
  1683. - (NSDictionary<NSString *, NSString *> *)
  1684. additionalParametersWithEMMPasscodeInfoRequired:(BOOL)emmPasscodeInfoRequired
  1685. claimsAsJSONRequired:(BOOL)claimsAsJSONRequired {
  1686. NSMutableDictionary<NSString *, NSString *> *additionalParameters =
  1687. [NSMutableDictionary dictionary];
  1688. if (emmPasscodeInfoRequired) {
  1689. additionalParameters[@"emm_passcode_info_required"] = @"1";
  1690. }
  1691. if (claimsAsJSONRequired) {
  1692. additionalParameters[@"claims"] = kNonEssentialAuthTimeClaimsJsonString;
  1693. }
  1694. return [additionalParameters copy];
  1695. }
  1696. @end