GIDSignInTest.m 64 KB

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