GIDSignInTest.m 64 KB

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